Question

I am trying to call an onclick function to a dynamically created input in javascript, but to no avail, it's not working and ruins the rest of the page from functioning assuming because the syntax is wrong or something is missing. I looked at other questions and I look at mine, the syntax is correct, but I don't understand why the onclick function doesn't work.

JavaScript Code:

// create an input element
var frm = document.getElementById("result");
var submitBtn = document.createElement("input");
submitBtn.type = "submit";
submitBtn.value = "Confirm Purchase";
frm.appendChild(submitBtn);

submitBtn.onClick function()
{
    var question = prompt('Are you sure you want to purchase these items?');
}
// create an input element
var resetBtn = document.createElement("input");
resetBtn.type = "button";
resetBtn.value = "Reset All";
resetBtn.style = "margin:5px";
frm.appendChild(resetBtn);
resetBtn.onClick function()
{
var question = prompt('Are you sure you want to remove all these selected items?');
}

HTML Code:

<div id="resultForm">
    <h1>Your DSLR Selections...</h1>
        <form id="result">
            <!--Store User Selection Text Node Element Here-->
            <!--<p>Your DSLR budget range selected was:</p>
            <p>The DSLR brand you selected was:</p>
            <p>The type of photography you selected was:</p>
            <p>The type of lenses you selected was:</p>
            <input type="submit" value="Confirm Purchase"/>
            <input type="button" value="Reset All"/>-->
        </form>
</div>

No correct solution

OTHER TIPS

You're missing both equals sign

submitBtn.onClick = function()
{
    ...
}
resetBtn.onClick = function()
{
    ...
}

The way to attach events in most browsers (IE 9 and above) is to use addEventListener like this:

element.addEventListener('click', function() { /* do stuff here*/ }, false);

So your code should look like:

submitBtn.addEventListener('click', function()
{
    var question = prompt('Are you sure you want to remove all these selected items?');
}

Try with

resetBtn.onClick = function() ...

use assignment, as in

submitBtn.onClick = function() {
    var question = prompt('Are you sure you want to purchase these items?');
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top