简体   繁体   中英

event.preventDefault() not being honored for a jquery.trigger(“click”)

There are checkboxes within a form on my page:

<form id="oneform" action="blah..">
    <input type="checkbox" name="checkboxes" id="chkbox1"/>Checkbox1
    <input type="checkbox" name="checkboxes" id="chkbox2"/>Checkbox2
...

NOTE : upon checking/unchecking any checkbox this form is submitted. Here is jQuery code:

$("input[name='checkboxes']").bind("click",function(e) {
    e.preventDefault(); 
    ....

    $("#oneform").submit();
});

The role of e.preventDefault() in above function is : if the checkbox was checked and the box is clicked, prevent default will ensure that it remains in checked condition for the browser to record checkbox state before form submission. So after form submission the checkbox will be unchecked as expected and on "Back button" I will see the checkbox checked again. This works for me as expected

Then I have a div on that form which shows list of elements displaying name of checkboxes checked.

<div>
  <% This is a JSTL code: for each element  %>
      <a class="close-tag" href="#" value="<% JSTL put the checkbox id %>"><span><% jSTL put checkbox name</span> X</a>
  <% end %>
</div>

If you clicked on 'X' there is a jQuery Handler as shown below:

$(".close-tag").bind('click', function(e) {
 e.preventDefault() // again for same reasons as mentioned above

// get the name of checkbox id from event target
.....
 var selector = ... // checkbox id 

// fake the checkbox clicking event
$("#"+selector).trigger("click");
// doing the above goes to the above jquery snippet as you would expect.

// the checkbox also remains checked as expected due to e.preventDefault()
// However on server side it should send the checkbox as "unchecked" instead it sends as  checked

});

Did I miss to add anything? It does not work on FF, Chrome Thanks for any pointers!

Update By replacing $(selector).trigger() with vanilla JS alternative: document.getElementById(selector).click() ...I was able to solve this. Works as expected on FF, IE8/9, safari, chrome, opera yay!

Update:

Actually, I missed something really obvious. When you call trigger() you need to specify the event you want to trigger, so it needs to be trigger('click') .


If I'm reading it correctly, you're saying it still showed as checked, but you want it to report to the server as being unchecked.

That's not quite possible. An element doesn't have two states like that, just one.

What you could do though is change the check box to unchecked, submit the form, then mark it as checked again.

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