change input type for input field from string to int in javascript

To change the input type for an input field from string to int in JavaScript, you can use the parseInt() method.

<input type="text" id="inputField" />
<button onclick="convertToInt()">Convert to Integer</button>
99 chars
3 lines
index.tsx
function convertToInt() {
  // Get the input field value
  var inputField = document.getElementById("inputField").value;
  
  // Convert the input field value to an integer
  var convertedInt = parseInt(inputField);
  
  // Check if the conversion was successful
  if(!isNaN(convertedInt)) {
    // Change the input type to number
    document.getElementById("inputField").type = "number";
    // Set the value of the input field to the converted integer
    document.getElementById("inputField").value = convertedInt;
  } else {
    alert("Please enter a valid integer.");
  }
}
580 chars
18 lines

In this example, we first define an input field with an id of inputField, and a button that calls the convertToInt() function when clicked.

Inside the convertToInt() function, we use the parseInt() method to convert the value of the input field to an integer. We then check if the conversion was successful using isNaN(), and if so, we display an error message. If the conversion was successful, we change the type of the input field to "number" using document.getElementById("inputField").type = "number"; and set the value of the input field to the converted integer.

gistlibby LogSnag