How to disable checkbox with jquery? - javascript

I searched more time with it but it's not work, I want to checkbox is disabled, user not check and can check it if some condition. Ok, now, I tried disabled them. I use jquery 2.1.3
<input type="checkbox" class="checkbox1" id="chk" name="check[]" value="U01" />Banana
<input type="checkbox" class="checkbox1" id="chk" name="check[]" value="U02" />Orange
<input type="checkbox" class="checkbox1" id="chk" name="check[]" value="U03" />Apple
<input type="checkbox" class="checkbox1" id="chk" name="check[]" value="U04" />Candy
$(window).load(function () {
$('#chk').prop('disabled', true);
});

id should be unique. You cannot have four checkboxes with the same id.
You can try other selectors to select the whole range of checkboxes, like .checkbox1 (by class), input[type="checkbox"] (by tag/attribute). Once you've fixed the ids, you could even try #chk1, #chk2, #chk3, #chk4.
The snippet below uses the classname 'chk' instead of the id 'chk'. Also, it uses attr to set the attribute although it did work for me using prop as well.
$(window).load(function() {
$('.chk').attr('disabled', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="chk" name="check[]" value="U01" />Banana
<input type="checkbox" class="chk" name="check[]" value="U02" />Orange
<input type="checkbox" class="chk" name="check[]" value="U03" />Apple
<input type="checkbox" class="chk" name="check[]" value="U04" />Candy

You already changed the ID but you can also put the class in the same attribute such as:
<input type="checkbox" class="checkbox1 chk" name="check[]" value="U01" />Banana
Then you can use jQuery to either disable or check a checkbox depending on you needs like so
To disable:
$(function () {
$('.chk').prop('disabled', true);
});
To "precheck":
$(function () {
$('.chk').prop('checked', true);
});
You can change the selector to fit IDs or classes even elements and change the properties between true or false according to your needs.

HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="checkbox1" class="chk" name="check[]" value="U01" />Banana
<input type="checkbox" class="checkbox1" class="chk" name="check[]" value="U02" />Orange
<input type="checkbox" class="checkbox1" class="chk" name="check[]" value="U03" />Apple
<input type="checkbox" class="checkbox1" class="chk" name="check[]" value="U04" />Candy
Javascript/jQuery
$(function() {
$("input.checkbox1").prop("disabled", true);
});

Related

Push and pop data from array based on checkbox check and uncheck value using jQuery

var listvalues = []
$('.check').on('change', function() {
var val = this.checked ? this.value : '';
listvalues.push(val)
$('#show').html(listvalues);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" type="text/javascript"></script>
<input type="checkbox" class="check" value="1" />1
<input type="checkbox" class="check" value="2" />2
<input type="checkbox" class="check" value="3" />3
<input type="checkbox" class="check" value="4" />4
<div id="show"> </div>
I have a code which should push and pop checkbox value based on checkbox check and uncheck, for example if I check and checkbox it should show the value in a div and if I unselect the checkbox the value should disappear from div, and it should not allow anyone to append duplicate data.
But what I did appends even if it is duplicate it appends the data. Can anyone help me on this?
and i wanted to create separate div for each checkbox
Instead of push & pop value from array, you can get all checked values with listvalues = $('.check:checked').toArray().map(x => x.value); and display it.
$('.check:checked') will only return .check which are checked. Then .toArray() will convert jquery object into array & get use .map(x => x.value) to fetch only value from checked elements.
var listvalues = []
$('.check').on('change', function() {
listvalues = $('.check:checked').toArray().map(x => x.value).join(', ');
$('#show').html(listvalues);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" type="text/javascript"></script>
<input type="checkbox" class="check" value="1" />1
<input type="checkbox" class="check" value="2" />2
<input type="checkbox" class="check" value="3" />3
<input type="checkbox" class="check" value="4" />4
<div id="show"> </div>
To remove you can use filter to exclude the unchecked item. I'm not sure what you want to achieve with different divs, please explain.
var listvalues = []
$('.check').on('change', function() {
if(this.checked){
listvalues.push(this.value);
}
else {
listvalues = listvalues.filter(item => item != this.value);
}
$('#show').html(listvalues.sort());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" type="text/javascript"></script>
<input type="checkbox" class="check" value="1" />1
<input type="checkbox" class="check" value="2" />2
<input type="checkbox" class="check" value="3" />3
<input type="checkbox" class="check" value="4" />4
<div id="show"> </div>

How does one, from a checkbox group and preferably with jQuery, collect array data and does assign this data to a hidden target element's value?

I have a group of equally named checkboxes ...
<input type="checkbox" class="checkbox" name="checkbox[]" value="1" checked />
<input type="checkbox" class="checkbox" name="checkbox[]" value="2" checked />
<input type="checkbox" class="checkbox" name="checkbox[]" value="3" checked />
and a hidden form element ...
<input type="hidden" class="target" name="target[]" value="" />
Using jQuery, I want to copy all checked checkbox values in form of a value-list in its stringified array literal notation to the hidden target element's value.
I have tried the following ...
$(".checkbox").each(function(idx, val) {
$('input[name="target['+idx+']"]').val(this.value);
});
... without success. How can I generate and assign the correct result?
map() the :checked checkboxes to create array of their values, then stringify that array
const checkedVals = $(".checkbox:checked").map((i,el) => el.value).get()
$('input[name="target[]"]').val(JSON.stringify(checkedVals))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="checkbox" name="checkbox[]" value="1" checked />
<input type="checkbox" class="checkbox" name="checkbox[]" value="2" />
<input type="checkbox" class="checkbox" name="checkbox[]" value="3" checked />
<input class="target" name="target[]" value="">
basic jQuery approach which does the following ...
Query all equally named ... [name="checkbox[]"] ... and also :checked checkboxes,
and convert the resulting jQuery collection into a native array ... toArray().
Make use of an array's native map method in order to return an array of (checked) checkbox values,
which immediately after gets converted via JSON.stringify into its string representation (of an array literal notation),
and assigned to the hidden target element's (via jQuery $('input[name="target[]"]')[0]) value.
$('input[name="target[]"]')[0].value = JSON.stringify(
$('[type="checkbox"][name="checkbox[]"]:checked')
.toArray()
.map(elm => elm.value)
);
console.log(
'target[] :: value :',
$('input[name="target[]"]')[0].value
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="checkbox" name="checkbox[]" value="1" checked />
<input type="checkbox" class="checkbox" name="checkbox[]" value="2" />
<input type="checkbox" class="checkbox" name="checkbox[]" value="3" checked />
<input type="hidden" class="target" name="target[]" value="">
a jQuery free variant of the above approach with checkbox change event handling ...
function updateCheckboxTargetValue() {
document
.querySelector('input[name="target[]"]')
.value = JSON.stringify([
...document
.querySelectorAll(
'[type="checkbox"][name="checkbox[]"]:checked'
)
].map(elm => elm.value)
);
console.log(
'target[] :: value :',
document.querySelector('input[name="target[]"]').value
);
}
function handleCheckboxChange(evt) {
if (evt.target.matches('[type="checkbox"][name="checkbox[]"]')) {
updateCheckboxTargetValue();
}
}
updateCheckboxTargetValue();
document.addEventListener('change', handleCheckboxChange);
<input type="checkbox" class="checkbox" name="checkbox[]" value="1" checked />
<input type="checkbox" class="checkbox" name="checkbox[]" value="2" />
<input type="checkbox" class="checkbox" name="checkbox[]" value="3" checked />
<input type="hidden" class="target" name="target[]" value="">

How to add ID and label tag to checkbox with jQuery

I have the following HTML code (that I can't access/amend) for one of my many checkboxes:
<input type="checkbox" class="cat_input" name="subcategory1a" value="1">
I want to turn the checkbox into a toggle, for which I understand I need a <label> tag associated with the 'ID' of the checkbox. Unfortunately, the HTML code as per above has only the input tag without ID and no <label> tag.
To create a checkbox toggle I understand I would need a unique ID and associated <label> tag for each checkbox such as for example:
<input type="checkbox" class="cat_input" name="subcategory1a" value="1" ID="checkbox1"> <label for="checkbox1"></label>
I have two questions:
How can I add the ID and <label> tag with jQuery to my existing <input> tag to create a code as per the example?
Given that I have c. 40-50 checkboxes of which each needs its own ID and label tag, is there a way to make the jQuery code compact as opposed to copy paste the code 40-50x?
I would much appreciate your help. Thank you very much in advance!
EDIT
<script>
$('input[type="checkbox"]').each(function(i, v) {
var checkbox = $(this);
checkbox.attr("id", ("checkbox_" + (i + 1)))
checkbox.after($("<label>").attr("for", checkbox.attr("id")));
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="geodir-filter-cat gd-type-single gd-field-fieldset"><span>Header</span>
<ul>
<li><input type="checkbox" class="cat_input" name="subcategory1a" value="1" /> </li>
<li><input type="checkbox" class="cat_input" name="subcategory1b" value="1" /> </li>
</l>
</div>
You can iterate over each checkbox and add the label after it.
Example:
$('input[type="checkbox"]').each(function() {
var checkbox = $(this);
checkbox.after($("<label>").attr("for", checkbox.attr("id")));
});
In case your initial input doesn't have an id attribute set, then set it manually first:
$('input[type="checkbox"]').each(function(i, v) {
$(this).attr("id", ("checkbox_" + i))
$(this).after($("<label>").attr("for", $(this).attr("id")));
});
EDIT 1:
Putting this code into <head> is not going to work, as the content that this code addressing is not yet loaded at that time. Either put this code before closing </body> tag or use ready function.
$(function() {
// code above is here
});
According your given markup please see below:
$('.cat_input').each(function() {
var checkbox = $(this);
checkbox.attr('id', 'checkbox'+checkbox.index()); // Adding ID attribute
checkbox.after($("<label for='checkbox"+ checkbox.index() +"'>").text(checkbox.val())); // Adding label with for attribute
});
And HTML I assumed like following:
<input type="checkbox" class="cat_input" name="subcategory1a" value="1">
<input type="checkbox" class="cat_input" name="subcategory1a" value="2">
<input type="checkbox" class="cat_input" name="subcategory1a" value="3">
<input type="checkbox" class="cat_input" name="subcategory1a" value="4">
<input type="checkbox" class="cat_input" name="subcategory1a" value="5">
I always prefer to do it like <label><input /><span></span></label> for me I think its simple to use and to style/css it
$(document).ready(function(){
$('.cat_input').each(function(i){ // index start from 0
i = i + 1;
$(this).val(i).attr('id' , 'checkbox' + i).wrap('<label></label>').closest('label').append('<span>'+i+'</span>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="cat_input" name="subcategory1a" />
<input type="checkbox" class="cat_input" name="subcategory1a" />
<input type="checkbox" class="cat_input" name="subcategory1a" />
<input type="checkbox" class="cat_input" name="subcategory1a" />
<input type="checkbox" class="cat_input" name="subcategory1a" />
<input type="checkbox" class="cat_input" name="subcategory1a" />
<input type="checkbox" class="cat_input" name="subcategory1a" />
<input type="checkbox" class="cat_input" name="subcategory1a" />
the code for first input will be
<label>
<input type="checkbox" class="cat_input" name="subcategory1a" value="1" id="checkbox1"/>
<span>1</span>
</label>

Only one checkbox checked at a time in javascript

I have 3 checkbox, for which I want only 1 checkbox to be checked at a time. below is my fiddle for the html
JS fiddle
I want this to be worked in IE8 also kindly suggest how to do
How about this - fiddle:
<input type="checkbox" class="chk" />
<input type="checkbox" class="chk" />
<input type="checkbox" class="chk" />
<input type="checkbox" class="chk" />
$('input.chk').on('change', function() {
$('input.chk').not(this).prop('checked', false);
});
Edit:
for second part of your question to un-check other checkboxes when selecting parent checkbox see this fiddle - (as per chat) :
if (!cb.checked) {
$('#trchkOptions input[type=checkbox]').attr('checked', false);
}
function selectOnlyThis(id) {
for (var i = 1;i <= 4; i++)
{
document.getElementById(i).checked = false;
}
document.getElementById(id).checked = true;
}
<input type="checkbox" id="1" value="Value1" onclick="selectOnlyThis(this.id)" /> Option 1
<input type="checkbox" id="2" value="Value1" onclick="selectOnlyThis(this.id)" /> Option 2
<input type="checkbox" id="3" value="Value1" onclick="selectOnlyThis(this.id)" /> Option 3
<input type="checkbox" id="4" value="Value1" onclick="selectOnlyThis(this.id)" /> Option 4
It should help you

jquery check and uncheck all with action

I have more checkbox input that call function "boxclick" when the user click on this:
<input id="1box" type="checkbox" name="selected[]" onclick="boxclick(this,'1')">
<input id="2box" type="checkbox" name="selected[]" onclick="boxclick(this,'2')">
<input id="3box" type="checkbox" name="selected[]" onclick="boxclick(this,'3')">
<input id="4box" type="checkbox" name="selected[]" onclick="boxclick(this,'4')">
For check/uncheck all i use simple jquery script:
<input type="checkbox" onclick="$('input[name*=\'selected\']').attr('checked', this.checked);" checked="checked">
My problem is when i check/uncheck all the function "boxclick" not run.
// == a checkbox has been clicked ==
function boxclick(box,category) {
if (box.checked) {
show(category);
} else {
hide(category);
}
}
I think you can do:
HTML
<input id="1box" type="checkbox" name="selected[]">
<input id="2box" type="checkbox" name="selected[]">
<input id="3box" type="checkbox" name="selected[]">
<input id="4box" type="checkbox" name="selected[]">
jQuery
If you want to check/uncheck all checkbox:
var checkboxes = $('input[type=checkbox][name^=selected]');
checkboxes.on('click', function() {
checkboxes.prop('checked', this.checked);
});
If you want to make select any one at a time:
var checkboxes = $('input[type=checkbox][name^=selected]');
checkboxes.on('click', function() {
checkboxes.prop('checked', false);
this.checked = !this.checked;
});​
DEMO
Setting attribute of checkboxes to checked does not automatically fake a click event for you! Because you put those boxclick function calls within some "onclick" handlers, you must trigger a fake click event in order for your javascript to think that it clicked all the boxes. To trigger fake click event use $('#whatever').trigger('click'), for instance:
$('input[name*=\'selected\']').trigger('click');
If you want check/uncheck all functionality, you must say "ok, master checkbox, please listen for whenever I am checked or unchecked. When that happens, please set checked attribute of my slave boxes (your other boxes on the page) to match the master's current checked attribute." Like this:
function checkAllorUncheckAll(event){
var chiefCheckbx = event.currentTarget;
var myBoxes = $('input[name*=\'selected\']');
myBoxes.prop( "checked", $(chiefCheckbx).prop("checked") ).trigger('click');
}
$('#masterCheckBox').on('change',checkAllorUncheckAll);
I guess
$('input[name*=\'selected\']').attr('checked',
this.checked).trigger('click');
should do the trick here
Demo
http://jsfiddle.net/H37cb/
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js" /></script>
<script type="text/javascript">
$(document).ready(function(){
$('input[name="all"],input[name="title"]').bind('click', function(){
var status = $(this).is(':checked');
$('input[type="checkbox"]', $(this).parent('li')).attr('checked', status);
});
});
</script>
<div id="wrapper">
<li style="margin-top: 20px">
<input type="checkbox" name="all" id="all" /> <label for='all'>All</label>
<ul>
<li><input type="checkbox" name="title" id="title_1" /> <label for="title_1"><strong>Title 01</strong></label>
<ul>
<li><input type="checkbox" name="selected[]" id="box_1" value="1" /> <label for="box_1">Sub Title 01</label></li>
<li><input type="checkbox" name="selected[]" id="box_2" value="2" /> <label for="box_2">Sub Title 02</label></li>
<li><input type="checkbox" name="selected[]" id="box_3" value="3" /> <label for="box_3">Sub Title 03</label></li>
<li><input type="checkbox" name="selected[]" id="box_4" value="4" /> <label for="box_4">Sub Title 04</label></li>
</ul>
</li>
</ul>
<ul>
<li><input type="checkbox" name="title" id="title_2" /> <label for="title_2"><strong>Title 02</strong></label>
<ul>
<li><input type="checkbox" name="selected[]" id="box_5" value="5" /> <label for="box_5">Sub Title 05</label></li>
<li><input type="checkbox" name="selected[]" id="box_6" value="6" /> <label for="box_6">Sub Title 06</label></li>
<li><input type="checkbox" name="selected[]" id="box_7" value="7" /> <label for="box_7">Sub Title 07</label></li>
</ul>
</li>
</ul>
</li>
</div>

Categories

Resources