jQuery if checkbox is checked
if ($(‘input.checkbox_check’).is(‘:checked’)) {
if ($(‘input.checkbox_check’).is(‘:checked’)) {
Use .is(‘:checked’) to determine whether or not it’s checked, and then set your value accordingly. More information here.
you have to use the ‘prop’ function : .prop(‘checked’, true); Before jQuery 1.6 (see user2063626’s answer): .attr(‘checked’,’checked’)
To get the value of the Value attribute you can do something like this: $(“input[type=”checkbox”]”).val(); Or if you have set a class or id for it, you can: $(‘#check_id’).val(); $(‘.check_class’).val(); However this will return the same value whether it is checked or not, this can be confusing as it is different to the submitted form … Read more
Tested in JSFiddle and does what you’re asking for.This approach has the added benefit of firing when a label associated with a checkbox is clicked. Updated Answer: $(document).ready(function() { //set initial state. $(‘#textbox1’).val(this.checked); $(‘#checkbox1’).change(function() { if(this.checked) { var returnVal = confirm(“Are you sure?”); $(this).prop(“checked”, returnVal); } $(‘#textbox1’).val(this.checked); }); }); Original Answer: $(document).ready(function() { //set initial … Read more
Javascript: // Check document.getElementById(“checkbox”).checked = true; // Uncheck document.getElementById(“checkbox”).checked = false; jQuery (1.6+): // Check $(“#checkbox”).prop(“checked”, true); // Uncheck $(“#checkbox”).prop(“checked”, false); jQuery (1.5-): // Check $(“#checkbox”).attr(“checked”, true); // Uncheck $(“#checkbox”).attr(“checked”, false);
you can use this: <input type=”checkbox” onclick=”return false;”/> This works because returning false from the click event stops the chain of execution continuing.
UPDATE: The below answer references the state of things before widespread availability of CSSĀ 3. In modern browsers (including Internet Explorer 9 and later) it is more straightforward to create checkbox replacements with your preferred styling, without using JavaScript. Here are some useful links: Creating Custom Form Checkboxes with Just CSS Easy CSS Checkbox Generator Stuff … Read more
Method 1: Wrap Label Tag Wrap the checkbox within a label tag: <label><input type=”checkbox” name=”checkbox” value=”value”>Text</label> Method 2: Use the for Attribute Use the for attribute (match the checkbox id): <input type=”checkbox” name=”checkbox” id=”checkbox_id” value=”value”> <label for=”checkbox_id”>Text</label> NOTE: ID must be unique on the page! Explanation Since the other answers don’t mention it, a label … Read more
$(‘#’ + id).is(“:checked”) That gets if the checkbox is checked. For an array of checkboxes with the same name you can get the list of checked ones by: var $boxes = $(‘input[name=thename]:checked’); Then to loop through them and see what’s checked you can do: $boxes.each(function(){ // Do stuff here with this }); To find how … Read more