Reputation: 23
I have one textfield with id=uName. when i press enter button i want jquery to detect it and submit the form. But its not detecting the enter key pressed event.
How to resolve this?
code:
<s:textfield cssClass="inputselect" name="uname" id="uname" />
<script type="text/javascript">
$(document.getElementById('uname')).keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13') {
document.getElementById("formID").action="searchbaseuom";
document.getElementById("formID").submit();
}
});
</script>
Upvotes: 0
Views: 178
Reputation: 17522
I made some changes to your code, hope this helps, but you are mixing jquery with javascript, which tells us you have not grasped how jquery works.
hope this helps.
<s:textfield cssClass="inputselect" name="uname" id="uname" />
<script type="text/javascript">
$('#uname').keypress(function(event){
var keycode = (event.keyCode) ? event.keyCode : event.which;//note changes
if(keycode == '13'){
$("#formID").attr('action',"searchbaseuom").submit();
}
});
</script>
Update
Also if you have put the script tag on the head tags, then you will need a on ready function which means when page has loaded properly, then carry the following instructions.
because the form may loud after the above script this would mean that your event has not been attached so you will need to put the whole script on the following code.
$(function (){//when document is ready line.
// script goes here
});
this is the same as
$(document).ready(function(){
//script here.
});
the only difference is that one is shorter than the other.
Upvotes: 2
Reputation: 196002
Make sure your code is run after the DOM is ready.
<script type="text/javascript">
$(function(){
$('#uname').keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode === 13){
$('#formID').attr('action','searchbaseuom').submit();
}
});
});
</script>
Upvotes: 0