简体   繁体   中英

Get value of a check box in JavaScript?

I am a newbie to jquery. I have this code written. I want to get the value of 'newValue' when the checkbox is checked. But this code returns 'undefined'.

Please can someone help to get the state of the checkbox: the return value should be true or false, 1 or 0.

$(tableCell).empty();
/Checkbox
 $('<input type="checkbox" checked class="EditContactRow" style="width: 20%" />').appendTo($(tableCell)).val(controlValue).blur(function () {
  var newValue = $(tableCell).find('checkbox').val();
.....
.....
}

Thanks

Ahoy, Olumide Omolayo

your code seems a little bit messy but it can be fixed for sure. Where is your HTML, would you please add it to your question?

If you need an example: if you have a checkbox you would take it's value by selecting it like this

var myCheckboxValue = $('#myCheckbox').val();

your code:

$('<input type="checkbox" checked class="EditContactRow" style="width: 20%" />')

will not work. since $() is used to access jQuery selectors, those SELECT an element in the HTML/DOM, then you do something with the element. (see this video )

If you want to ADD an element to the HTML/DOM you'd probably use something like

$("#myDiv").html('my html that will be added to the element with id="myDiv"');

Hope this helps. Feel free to ask more :)

PS If you post your full code here, we might able to help you much more than just write at random here. People might be able to actually give you the fixed version :)

just a small syntax error.

Change this line var newValue = $(tableCell).find('checkbox').val();

to

var newValue = $(tableCell).find('input[type="checkbox"]').val();

The problem was .find('checkbox') you are trying to find a element who's name is checkbox and you dont have one.. the attempt should be to find a element 's whos type is "checkbox" so use the syntax .find('input[type="checkbox"]')

Correct answer to my question from Reddy

var newValue = $(tableCell).find('input[type="checkbox"]').val();

Thank you all

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