Girish Tiwari
Girish Tiwari

Reputation: 59

jQuery cannot trigger button click from another button click

My goal is to replace a button with another button, but I am running into some issues. I am able to trigger the first button click and I am able to cause an alert with the second button click, but for some reason when I try to trigger the first button click in the click event handler of the second button, it doesn't work. What am I doing wrong? For some context, I'm doing this in Powerapps Portals by adding a Content Snippet.

$(window).load(function() {

     //Code to Add Custom 'Register' Button (and Hide the original one- currently commented out)
     $('#SubmitButton').after('<input type="submit" name="ctl00$ctl00$ContentContainer$MainContent$MainContent$mySubmitButton" value="Register" id="mySubmitButton" class="btn btn-primary">');

     //$('#SubmitButton').hide(); *THIS WORKS*
     //$("#SubmitButton").click(); *THIS ALSO WORKS*

     $("#mySubmitButton").click(function()
     {
          //window.alert('yes!'); *THIS WORKS*
          $("#SubmitButton").click(); // *THIS DOES NOT WORK*
     });


});

Upvotes: 2

Views: 811

Answers (1)

Unmitigated
Unmitigated

Reputation: 89527

You need to prevent the default action to stop the form from submitting when the button is clicked.

$("#mySubmitButton").click(function(e){
    e.preventDefault(); 
    $("#SubmitButton").click();
});

Alternatively, you can set the button's type to "button" so clicking it does not submit the form by default.

$('#SubmitButton').after('<input type="button" name="ctl00$ctl00$ContentContainer$MainContent$MainContent$mySubmitButton" value="Register" id="mySubmitButton" class="btn btn-primary">');

Upvotes: 3

Related Questions