Hi everyone,
So i'm working on a default form button script, which is really easy
and i was able to get it to work. Problem is i have a div/panel
listening to click events and i need to get the default button from
the event.target property. Thing is when i trigger the default
button's click event programmatically, i get the last element before
the user hit the "enter" key instead of the button. The only way i can
get around this is to dispatch the event manually. Anybody else run
into this and is there something built into jquery to resolve this?
Here's an example:
<div id="panel">
<div id="login" style="margin: 20px; padding: 20px; width:
300px; background: #ccc;" tabindex=1>
<div style="margin: 5px 0;"><input type="text"
id="username" /></div>
<div style="margin: 5px 0;"><input type="text"
id="password" /></div>
<input type="submit" value="Sign in" id="signIn" />
</div>
</div>
<script language="javascript" type="text/javascript">
function simulateClick(obj)
{
var evt = document.createEvent("MouseEvents");
evt.initEvent("click", true, true, document.defaultView,
1, 0, 0, 0, 0, false, false, false, false, 0, null);
obj.dispatchEvent(evt);
}
$(function(){
$("#login").keypress(function(event){
if (event.keyCode == 13)
{
// does not return correct "target"
// $("#signIn")[0].click();
// this will return the correct element in the target property
simulateClick($("#signIn")[0]);
event.preventDefault();
}
});
$("#panel").click(function(event){
// i need to get the default button that was clicked, instead i'm
getting the last element before the "enter" was pressed
// so user types username and password and hits enter, i will get
"password" for event.target instead of the
// default button which actually triggered the click event.
alert(this.id + " - " + event.target.id);
});
})
</script>