Setting "Checked" For a Checkbox With Jquery

Setting checked for a checkbox with jQuery

Modern jQuery

Use .prop():

$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);

DOM API

If you're working with just one element, you can always just access the underlying HTMLInputElement and modify its .checked property:

$('.myCheckbox')[0].checked = true;
$('.myCheckbox')[0].checked = false;

The benefit to using the .prop() and .attr() methods instead of this is that they will operate on all matched elements.

jQuery 1.5.x and below

The .prop() method is not available, so you need to use .attr().

$('.myCheckbox').attr('checked', true);
$('.myCheckbox').attr('checked', false);

Note that this is the approach used by jQuery's unit tests prior to version 1.6 and is preferable to using $('.myCheckbox').removeAttr('checked'); since the latter will, if the box was initially checked, change the behaviour of a call to .reset() on any form that contains it – a subtle but probably unwelcome behaviour change.

For more context, some incomplete discussion of the changes to the handling of the checked attribute/property in the transition from 1.5.x to 1.6 can be found in the version 1.6 release notes and the Attributes vs. Properties section of the .prop() documentation.

Setting checked for a checkbox with jQuery

Modern jQuery

Use .prop():

$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);

DOM API

If you're working with just one element, you can always just access the underlying HTMLInputElement and modify its .checked property:

$('.myCheckbox')[0].checked = true;
$('.myCheckbox')[0].checked = false;

The benefit to using the .prop() and .attr() methods instead of this is that they will operate on all matched elements.

jQuery 1.5.x and below

The .prop() method is not available, so you need to use .attr().

$('.myCheckbox').attr('checked', true);
$('.myCheckbox').attr('checked', false);

Note that this is the approach used by jQuery's unit tests prior to version 1.6 and is preferable to using $('.myCheckbox').removeAttr('checked'); since the latter will, if the box was initially checked, change the behaviour of a call to .reset() on any form that contains it – a subtle but probably unwelcome behaviour change.

For more context, some incomplete discussion of the changes to the handling of the checked attribute/property in the transition from 1.5.x to 1.6 can be found in the version 1.6 release notes and the Attributes vs. Properties section of the .prop() documentation.

check / uncheck checkbox using jquery?

For jQuery 1.6+ :

.attr() is deprecated for properties; use the new .prop() function instead as:

$('#myCheckbox').prop('checked', true); // Checks it
$('#myCheckbox').prop('checked', false); // Unchecks it

For jQuery < 1.6:

To check/uncheck a checkbox, use the attribute checked and alter that. With jQuery you can do:

$('#myCheckbox').attr('checked', true); // Checks it
$('#myCheckbox').attr('checked', false); // Unchecks it

Cause you know, in HTML, it would look something like:

<input type="checkbox" id="myCheckbox" checked="checked" /> <!-- Checked -->
<input type="checkbox" id="myCheckbox" /> <!-- Unchecked -->

However, you cannot trust the .attr() method to get the value of the checkbox (if you need to). You will have to rely in the .prop() method.

how to check dynamically created checkbox is checked using jquery

Your code is not working because your event handler is created before the dynamic checkboxes are. To bypass this, you can bind an event handler to the whole document or, for better performance, to the parent that contains all your checkboxes :

$(document).on('change',"input[type='checkbox']",function () {

// your code here...

});

Checking the checkbox in jquery

You need to use the .is() method and the :checked selector.

On clicking of a checkbox - you iterate over the checkboxes with the required class (using the .each() method) and can test each to see if its checked or not.

Note the little ternary equation in there to demonstrate an alternative to the traditional if/ else block - but it does the same thing (the "?" line is equivalent to true and the ":" is equivalent to false / else....

EDIT - I have updated the function to match your needs. Basically you need to check if all the checkboxes are checked and if so - submit the form and if not - raise the error modal.

The following amended code should do that for you.

$('input[type="checkbox"]').click(function(){

let total = 0;
let checked = 0;

$('.checkboxRequired').each(function(index){
total += 1;
if( $(this).is(':checked') ) {checked +=1 }
})

total === checked
? ($('.orderForm').submit(), console.log('Form Submitted'))
: $('#errorModal').modal('show');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

<label> <input type="checkbox" class="checkbox checkboxRequired"/> Checkbox 1</label><br/>
<label> <input type="checkbox" class="checkbox "/> Checkbox 2</label><br/>
<label> <input type="checkbox" class="checkbox checkboxRequired"/> Checkbox 3</label><br/>
<label> <input type="checkbox" class="checkbox checkboxRequired"/> Checkbox 4</label><br/>
<label> <input type="checkbox" class="checkbox "/> Checkbox 5</label>

<!-- form
<form class="orderForm" method="post"></form>
-->

<!-- Modal -->
<div id="errorModal" class="modal fade" role="dialog">
<div class="modal-dialog modal-sm">

<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Error Modal Header</h4>
</div>
<div class="modal-body">
<p>There is a disturbance in the force..... not all required checkboxes are checked</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>

</div>
</div>

Check if checkbox is checked with jQuery

IDs must be unique in your document, meaning that you shouldn't do this:

<input type="checkbox" name="chk[]" id="chk[]" value="Apples" />
<input type="checkbox" name="chk[]" id="chk[]" value="Bananas" />

Instead, drop the ID, and then select them by name, or by a containing element:

<fieldset id="checkArray">
<input type="checkbox" name="chk[]" value="Apples" />

<input type="checkbox" name="chk[]" value="Bananas" />
</fieldset>

And now the jQuery:

var atLeastOneIsChecked = $('#checkArray:checkbox:checked').length > 0;
//there should be no space between identifier and selector

// or, without the container:

var atLeastOneIsChecked = $('input[name="chk[]"]:checked').length > 0;

Jquery set checkbox checked if value passed = 1

I just solved my question, needed to change the location of the prop to my main view:

    <!-- Send Data to modal -->
<script type="text/javascript">
$('#edit').on('show.bs.modal', function(event) {
var button = $(event.relatedTarget); // Button that triggered the modal
var id = button.data('id'); // Extract info from data-* attributes
var admin = button.data('admin');
var expert = button.data('expert');
var modal = $(this);
$('#edit_form').attr('action', '{{URL::to('/')}}/AdminPanel/'+id); //No spaces!!!
modal.find('#admin_field').val(admin).each(function(e){
if($(this).val() == 1){
$(this).prop("checked", true);
}
});
modal.find('#expert_field').val(expert).each(function(e){
if($(this).val() == 1){
$(this).prop("checked", true);
}
});
</script>

<!-- Modal -->
<div class="form-group row">
<div class="col-xs-8 col-sm-7 col-md-6">
<label for="admin_field" class="col-md-4 col-form-label text-md-right">{{ __('Admin?') }}
<input id="admin_field" type="checkbox" class="w3-check" name="Admin">
</label>
</div>
</div>

<script type="text/javascript">
$( document ).ready(function() {
// Checkbox instead of on:off 1:0
$('input:checkbox').on('change', function(){
this.value = this.checked ? 1 : 0;
}).change();
});
</script>

Jquery Checkbox not changing

You have to use .prop() for this, also you don't need for loop to set the attribute/prop: here is a fiddle and a working snippet:

$('input[type=checkbox]#selection').on('change', function() {

let rows = $("input[type=checkbox].vacancy_select");

rows.prop('checked', this.checked);

});

$('input[type=checkbox].vacancy_select').on('change', function() {

let selectedRows = $("input[type=checkbox].vacancy_select:checked").length;

let allElements = $('input[type=checkbox].vacancy_select').length;

let checked = false;

if(selectedRows === allElements) {

checked = true;

}

$('input[type=checkbox]#selection').prop('checked', checked)

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="checkbox" id="selection" name="selection">Selection

<input type="checkbox" class="vacancy_select" data-vacancy-id="1">

<input type="checkbox" class="vacancy_select" data-vacancy-id="2">

<input type="checkbox" class="vacancy_select" data-vacancy-id="3">

<input type="checkbox" class="vacancy_select" data-vacancy-id="4">

jQuery - Checkbox Checked

Just use attribute selctor in jquery

$("input[name='price_range']").click(function() {
$("input[name='price_range']").removeProp('checked');
$(this).prop('checked', true);
console.log(this.value);
});


Related Topics



Leave a reply



Submit