Get the value of the input for jQuery and JS
Get the value for jQuery
You must refer to the INPUT tag through id or name. Then use .val().
$("#id_login").val(); $("input[name='login']").val(); <INPUT id="id_login" name="login" value="Jony">
Sample code.
<script> function get_value() { var val_by_id = $("#id_login").val(); var val_by_name = $("input[name=login]").val(); alert (val_by_id + " " + val_by_name); } </script> <P><INPUT id="id_login" name="login" value="Jony"></P> <P><button onClick="get_value();">OK</button></P>
Get the value for JS
You must use the getElementById, getElementsByName, getElementsByClassName operator. And then .value.
document.getElementById('id_login').value; document.getElementsByName('login')[0].value; document.getElementsByClassName('login_class')[0].value; <INPUT id="id_login" name="login" class="login_class">
Sample code.
<script> function get_value() { var val_id = document.getElementById( "id_login" ).value; var val_name = document.getElementsByName( "login" )[0].value; var val_class = document.getElementsByClassName( "login_class" )[0].value; alert (val_id + " " + val_name + " " + val_class); } </script> <P><INPUT id="id_login" name="login" class="login_class" value="Jony"></P> <P><button onClick="get_value();">OK</button></P>
Possible mistakes.
Why does not the getElementsByName, getElementsByClassName operator work.
If you use the getElementsByName or getElementsByClassName operator, then you must add [0].
It is not right. This is mistake.
var val_name = document.getElementsByName( "login" ).value; document.getElementsByClassName('login_class').value;
This is the correct code.
var val_name = document.getElementsByName( "login" )[0].value; document.getElementsByClassName('login_class')[0].value;
Categories: