js_student-92
js_student-92

Reputation: 29

Sending form data to vanilla js

I am trying to send the result from a number input to a js function, and can't seem to make it work. I have tried with some answers from other questions in the site, but was still unable. My code goes something like this:

<input type="number" name="example">
<INPUT TYPE="button" NAME="button" Value="Click" onClick="how(example)">
<script type="text/javascript">
function how(example){
alert("example");
}
</script>

Thanks!

Upvotes: 1

Views: 1553

Answers (3)

Priyanka Maurya
Priyanka Maurya

Reputation: 385

Give the id of your number input. May be it will useful.

<input type="number" name="example" id="example">
<INPUT TYPE="button" NAME="button" Value="Click" onClick="how()">
<script type="text/javascript">
    function how(){
        var number = $('#example').val();
        alert(number);
    }
</script>

Upvotes: 1

Sheshank S.
Sheshank S.

Reputation: 3298

This might help you (this code will make it so that it alerts the value in number):

function alertval(){
  alert(document.getElementById("example").value);
}
<input type="number" name="example" id="example">
<INPUT TYPE="button" NAME="button" Value="Click" onClick="alertval()">

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 371168

Use .value to get the value of a text/number input or textarea element.

const numInput = document.querySelector('input[type="number"]')
document.querySelector('input[type="button"]')
  .addEventListener('click', () => {
    console.log(numInput.value);
  });
<input type="number" name="example">
<input type="button" value='click'>

Try to use addEventListener rather than HTML-inline-eval handlers, or on*-handlers; keeping all of your Javascript in the Javascript itself is helpful and is a good habit to get into.

Upvotes: 0

Related Questions