Nisarg Kudgunti
Nisarg Kudgunti

Reputation: 101

How to add onclick function to a button in typescript

I have created an onclick function for a button that will create an input box along with another button.

For the first button I have created the function in typescript and within it I have created a create element for the input box and the button.

When I click the first button, I am supposed to get an input box and a button next to it. When I provide an input and click the button, I want to display its value. But, I am unable to use the onclick function for the second button.

Here's the typescript code,

var Id: HTMLInputElement = <HTMLInputElement>document.getElementById("Id")

function getModels() {
    let quantity:HTMLInputElement=<HTMLInputElement>document.createElement("input");
    quantity.type = "number"
    quantity.id = "quan"
    document.body.appendChild(quantity)

    var getQuantity:HTMLInputElement=<HTMLInputElement>document.getElementById("quan");
    var btn:HTMLButtonElement=<HTMLButtonElement>document.createElement("button");
    btn.onclick="getquantity()"

    Display.innerHTML += getQuantity 
}

The onclick function couldn't be added like that. I am getting an Error:Type 'string' is not assignable to type '(this: GlobalEventHandlers, ev: MouseEvent) => any'.

Here's the HTML code,

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="car.js" defer></script>
    <title>Car Dealer</title>
</head>
<body>
    <input type="number" name="Enter Id" id="Id">
    <button onclick="getModels()" value="Get Models" >Get Models</button>
    <br/>
    <p id="display"></p>
</body>
</html>

How am I supposed to use the onclick function for the second button?

Upvotes: 1

Views: 17258

Answers (2)

Kinglish
Kinglish

Reputation: 23664

onclick is an event handler which passes a single argument event. Inline event listeners are not good coding practice as it mixes your presentation with your logic. Try updating your code separating out the listener.

Example #1

let btn:HTMLButtonElement=<HTMLButtonElement>document.createElement("button");
btn.addEventListener('click', (e:Event) => getQuantity());

Example #2

<button id='btn-models' value="Get Models" >Get Models</button>

then in your .TS

document.querySelector('#btn-models').addEventListener('click', (e:Event) => getModels());

Upvotes: 1

Brian Burton
Brian Burton

Reputation: 3842

It's expecting a callback function, not a string. Assuming getquantity() is an existing function, just change this line:

btn.onclick="getquantity()"

to this:

btn.onclick = getquantity;

Upvotes: 0

Related Questions