Reputation: 680
I have a textbox where onchange event adds some element at runtime. Due to this the submit button's position is changed. If user enters something in the textbox and clicks on the button the onclick event does not fire. I suspect its because at the same time the position of the button changes and browser thinks the click happened on page and not on the button.
Is there a way I can handle this situation? I can not move the button above the element which is added at runtime.
I have created a sample jsfiddle: http://jsfiddle.net/WV3Q8/3/
HTML:
<p>Enter something</p>
<input type="text" id="input" onchange="onChange()">
<div id="log"></div>
<button value="Go" style="display:block" type="button" onclick="submit();" id="btn-submit">Submit</button>
JavaScript:
function onChange(){
var value = $('#input').val();
$('#log').append('<p>New value: ' + value + '</p>');
}
function submit(){
alert('value submitted');
}
Edit 1
Test Case (Question is about 2nd test case) Its happening in all browsers (Chrome, IE 10 etc):
Edit 2: I can not use other key events like keyup, keydown or keypress because of obvious reasons (they fire on every keypress). setimeout too is out of question since there are some radio buttons which are generated at runtime on the onchange event of textbox. Its no wise to click on submit button without showing these radio buttons to user.
Upvotes: 7
Views: 1888
Reputation: 4904
Working Fiddle
A way out is to use onkeypress
<input type="text" id="input" onkeypress="onChange();">
UPDATE
If it is possible for you to use mousedown
event, it work's good.
Upvotes: 1
Reputation: 85545
This is not good solution but you can trigger the submit function for your case like this:
function onChange(){
var value = $('#input').val();
$('#log').append('<p>New value: ' + value + '</p>');
submit();
}
function submit(){
alert('value submitted');
}
Upvotes: 0
Reputation: 193261
I would use setTimeout
with keyup event:
var time;
function onChange() {
clearTimeout(time);
time = setTimeout(function() {
var value = $('#input').val();
$('#log').append('<p>New value: ' + value + '</p>');
}, 200);
}
It will append text once user finishes typing.
Upvotes: 0
Reputation: 1949
You are missing a return true statement in onChange()
Here is the code on jsfiddle
function onChange(){
var randomVal = Math.floor((Math.random()*100)+1);
$('#log').append('<p>New value: ' + randomVal + '</p>');
return true;
}
function submit(){
alert('value submitted');
}
EDIT: Alternative solution might be calling onChange() inside submit().
Upvotes: 0