Lochinvar
Lochinvar

Reputation: 93

Checkbox 'checked' value inconsistently undefined

I have a long table of items each with a checkbox. Onchange I call a function which merely alerts the checked value:

<input class="selectedCB" id="13" onchange="showInput(13);" type="checkbox">
<input class="selectedCB" id="14" onchange="showInput(14);" type="checkbox">
<script language="JavaScript" type="text/javascript"><!--
  function showInput(idx) {
    alert($('#'+idx).prop('checked'));    
  }
//--></script>

In my page (full of other script and stuff) I get undefined from some and the correct value from others. In a 'clean' test page they work perfectly. I am unsure where to start looking for what else might be making some remain undefined when checked. Any ideas?

Upvotes: 0

Views: 1892

Answers (3)

Arun P Johny
Arun P Johny

Reputation: 388316

Try using the :checked selector and .is() filter method

<input class="selectedCB" id="13" onchange="showInput(13);" type="checkbox">
<input class="selectedCB" id="14" onchange="showInput(14);" type="checkbox">
<script language="JavaScript" type="text/javascript"><!--
  function showInput(idx) {
    alert($('#'+idx).is(':checked'));    
  }
//--></script>

Upvotes: 1

colestrode
colestrode

Reputation: 10658

Since you are getting undefined on some checkboxes, but not others, I would bet you have some typos when assigning handlers.

Try assigning your handler once for all checkboxes and see if that helps:

$(function() {
    $('input[type="checkbox"].selectedCB').on('change', function(e) {
        alert($(this).prop('checked'));
    };
});

Upvotes: 0

palaѕн
palaѕн

Reputation: 73906

You can set the onchange attribute like:

 onchange="showInput(this.checked);"

and the javascript like:

function showInput(ischecked) {
    alert(ischecked);
}  

FIDDLE DEMO

Upvotes: 3

Related Questions