Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

button onclick does not fire when its position is changed

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):

  1. Enter something in the textbox and hit tab, p element is added and button's position is moved. Now click on submit button. An alert is shown.
  2. Enter something in the textbox and click on the submit button. p element is added but the alert is not shown.

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.

like image 708
Neeraj Gulia Avatar asked Mar 28 '14 10:03

Neeraj Gulia


1 Answers

For your edit #2 you have to delay the append with setTimeout() method like this:

setTimeout(function(){
    $('#log').append('<p>New value: ' + randomVal + '</p>');
},100);

Fiddle

like image 100
Jai Avatar answered Sep 21 '22 06:09

Jai