wasis12
wasis12

Reputation: 1

How to pass value from html input to javascript correctly?

How can I pass value from html input to javascript I have value_1 = 0 but when I change it in input form I want code inside if to happen.

<body>
<input type="number" name="a" id="commands"><br>
<canvas id="myChart1"></canvas>

<script>
const value_1 = 0;
const value_1 = document.getElementById("commands").value;

if(value_1 != 0)
{
 //code
}
</script>    
</body>

Upvotes: 0

Views: 300

Answers (4)

Madeefar Abbas
Madeefar Abbas

Reputation: 124

You can pass value from html to JavaScript correctly using following code:

HTML:

<form onsubmit="return getValue('commands')">
  <input type="number" name="a" id="commands">
  <canvas id="myChart1"></canvas>
</form>

JavaScript:

<script>
    function getValue(id) {
        let value_1 = 0;
        value_1 = document.getElementById(id).value;
        alert(value_1);
        
        if(value_1 != 0)
        {
         //code
        }
        return false;
    }
</script>

Upvotes: 0

Petr Fořt Fru-Fru
Petr Fořt Fru-Fru

Reputation: 1006

add a listener for the 'keyup' event, as follows:

document.getElementById("commands").addEventListener('keyup', (e) => {
   let value = document.getElementById("commands").value;
   if (value !== 0) {
      // code
   }
});

Or like this:

document.getElementById("commands").onkeyup = function(e) {
   let value = document.getElementById("commands").value;
   if (value !== 0) {
      // code
   }
}

or with jQuery:

$('#commands').on('keyup', (e) => {
   let value = $('#commands').val();
   if (value !== 0) {
      // code
   }
});

Upvotes: 1

Sultan Shindi
Sultan Shindi

Reputation: 11

If I understood,

To track input value changes you could do so by:

  1. Initialize the variable:
var inputValue = "";
  1. Listen for input changes (There are multiple ways to do it, I will use the one which listen whenever user clicks button on the input):
document.getElementById("commands").addEventListener("keyup", function(event) {
  inputValue = document.getElementById("commands").value;
  
  // Here you can do anything, incase you need to have a callback whenever the value changes.
  // Example:
  if(inputValue != 0) {
    // code.
  }
});

Upvotes: 0

llo
llo

Reputation: 135

You can use addEventListener with change event type or use the onchange property.

Example:

    <script>
    const value_1 = document.getElementById("commands");

    value_1.onchange = function(){
        if(value_1.value != 0)
        {
            console.log("Not 0");//code
        }
    }
    </script> 

Upvotes: 0

Related Questions