Grayson Mitchell
Grayson Mitchell

Reputation: 1187

Checkbox onchange function

I have a page with a set of checkbox's, that I want to run a Javascript function on when there is a change (I have done something very similar with dropdown's - and that worked)

However with the checkbox's I have three problems:

  1. my onChange event only runs "sometimes" (you have to change the focus between the different checkbox controls

  2. when it does run it is returning the result of the previous checkbox (not the one just clicked on)

  3. the jQuery always return the value true

Checkbox creation

<%= Html.CheckBox("sl-" + row.Id, value, new { onChange = "SuitabilityChecked("+row.Id+", "+key+")"})%>

Javascript

function SuitabilityChecked(providerId, parentRecordId) {
            var params = {};
            params.providerId = providerId;
            params.parentRecordId = parentRecordId;

            var value = $("#sl-" + providerId).val();               
            
            params.value = value;            
            $.getJSON("SuitabilityChecked", params, null);
        };

Upvotes: 3

Views: 7288

Answers (2)

statenjason
statenjason

Reputation: 5190

What's happening:

  1. Checkbox A clicked
  2. Checkbox B clicked
  3. Checkbox A has lost focus and fires onChange

Which makes it seem as if Checkbox B is returning the result of Checkbox A. If you were to press Tab after clicking Checkbox B in this scenario, you'd notice that its onChange would fire.

Upvotes: 0

Donald Byrd
Donald Byrd

Reputation: 7788

Browsers are funny about radio buttons and check boxes and can delay the onchange until focus change. Try adding an onclick event to blur or call the change event directly.

Maybe something like this using jQuery Live (untested, off the top of my head):

$(':checkbox').live('click', function() { $(this).change(); });

Upvotes: 3

Related Questions