简体   繁体   中英

Adding onclick event to input field programmatically in javascript doesn't work

I want my Input field to look like this:

<input type="submit" value="Remove" onclick="deleteRow(this)">

But it's not working. I've tried to:

Input.onclick = function () { deleteRow(this); };

Doesn't work as well. My deleteRow function looks like:

    function deleteRow(o) {
        var p = o.parentNode.parentNode;
        p.parentNode.removeChild(p);
    } 

Any suggestions on how to make it work?

You can add an id to your input field and attach the onclick event to it:

 function DeleteRow(o) { var p = o.parentNode.parentNode; p.parentNode.removeChild(p); } document.getElementById("myinput").onclick = function () { DeleteRow(this); }; 
 <input type="submit" id="myinput" value="Remove" onclick="DeleteRow(this)"> 

Try this one. If you have no purpose of submitting, change type=submit to type=button

 function DeleteRow(o) { var p = o.parentNode.parentNode; console.log(p); p.parentNode.removeChild(p); } 
 <div id="one"> <div id="two"> Goint to be deleted <form id="three"> <input type="button" value="Remove" onclick="DeleteRow(this)"> </form> </div> </div> 

but if you need to keep type=submit , i think you should pass event parameter as well like this

<!-- in case you need to use submit, pass event as parameter-->
<input type="submit" value="Remove" onclick="DeleteRow(this, event)">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM