Reputation: 468
As i'm trying to get the values from html to jquery using onkeyup function for getting key pressed data by ID i tried but i could not able to get the value in alert i don't know whats wrong in my code. Can Anyone Help Me.
Here is my code:
$(document).ready(function() {
$('#test').keypress(function() {
var value = document.getElementById('test').value;
alert("value",value);
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<input id="test" type="text">
Upvotes: 2
Views: 1231
Reputation: 1288
Remove
alert("value", value);
Comma and Add alert("value : " + value);
$('#test').keypress(function() {
var value = document.getElementById('test').value;
alert("value :"+ value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input id="test" type="text">
Upvotes: 2
Reputation: 6130
Dont mix javascript with jquery, you only need $(this).val() to get the value, use keyup ()
$(document).ready(function() {
$('#test').keyup(function() {
var _value = $(this).val();
alert("value " + _value);
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<input id="test" type="text">
Upvotes: 0
Reputation: 18099
Use keyup
and modify alert as given below:
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(
function() {
$('#test').keyup(
function() {
var value = document.getElementById('test').value;
alert(value);
});
})
</script>
<input id="test" type="text">
In your code, the event is fired on keypress, hence it takes the old value. So, in case of empty input field, it will alert the empty value but in case of keyup, it will alert the value which is already filled by the user.
Demo with keyup: http://jsfiddle.net/lotusgodkk/GCu2D/4020/
Demo with keypress: http://jsfiddle.net/lotusgodkk/GCu2D/4023/
Upvotes: 0
Reputation: 1135
Try this..
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>$(document).ready(
function() {
$('#test').keypress(
function() {
var values = document.getElementById('test').value;
alert("value"+values);
});
})</script>
</head>
<body>
<input id="test" type="text" value="2">
</body>
</html>
Upvotes: 0
Reputation: 337570
Your logic is correct. The issue is because you're providing two arguments to alert()
when it only accepts a single one.
Aside from that you should use console.log
for debugging, and you can access the element which triggered the event by using the this
keyword in the event handler. Try this:
$(document).ready(function() {
$('#test').keypress(function() {
var value = $(this).val();
console.log("value", value);
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="test" type="text">
Also note that keyup
or input
may be a more appropriate event to use, as keypress
fires before the new key is added to the value of the element.
Upvotes: 3