Disable checkbox array when radio button is not checked - javascript

Im trying to disable a checkbox array when the corresponding radio button is not checked. My code disables only the first element of the checkbox array and NOT the rest of the array. I might be doing something wrong but I cant seem to figure it out.
Any help would do.
Javascript :
<script>
function radioDisable(){
if(document.getElementById('rdGrp').checked){
document.getElementById('txtUserID[]').disabled=false;
}else{
document.getElementById('txtUserID[]').disabled=true;
}
}
</script>
html :
<td>
<input type="radio" name="rdAll" id="rdAll" value="all" onchange="radioDisable()"> All Users
<br>
<input type="radio" name="rdAll" id="rdGrp" value="group" onchange="radioDisable()"> Groups
<br>
<input type="checkbox" name="txtUserID[]" id="txtUserID[]" value="SysAd"> System Admin |
<input type="checkbox" name="txtUserID[]" id="txtUserID[]" value="faculty"> Faculty |
<input type="checkbox" name="txtUserID[]" id="txtUserID[]" value="student"> Student |
<input type="checkbox" name="txtUserID[]" id="txtUserID[]" value="registrar"> Registrar |
<input type="checkbox" name="txtUserID[]" id="txtUserID[]" value="adviser"> Adviser |
<input type="checkbox" name="txtUserID[]" id="txtUserID[]" value="clerk"> Clerk |
<input type="checkbox" name="txtUserID[]" id="txtUserID[]" value="management"> Management
</td>

My code disables only the first element of the checkbox array and NOT the rest of the array.
That because id should be unique in same document, if there's multiple elements with same id just the first one will be selected, you could use name instead.
Use getElementsByName() to get all the checkboxes and loop through them to disable/enable every one :
function radioDisable(){
var checkboxes = document.getElementsByName('txtUserID[]');
var disabled = !document.getElementById('rdGrp').checked;
for(var i=0;i<checkboxes.length;i++){
checkboxes[i].disabled = disabled;
}
}
Hope this helps.

you've assigned all your inputs the same id "txtUserID[]", which is not allowed. If you would consider using jQuery you could simply assign a class to the inputs (you are allowed to use the same class mulitiple times, not id). It could look something like:
<input type="checkbox" class="myClass">
In javascript/jquery
$(".myClass").disabled = true

Use getElementsByName
function radioDisable(){
var chkBoxes[] = document.getElementsByName('txtUserID[]');
for (var i = 0; i < chkBoxes.length; i++) {
if(document.getElementById('rdGrp').checked){
chkBoxes[i].disabled=false;
}
else{
chkBoxes[i].disabled=true;
}
}
}

remove ID from checkboxes and add class="txtUserID". then update your function like below
function radioDisable(){
if(this.checked){
var allChkBox = document.getElementsByName('txtUserID[]');
for(var i =0, len = allChkBox.length; i < len; i++) {
allChkBox[i].disabled = this.checked;
}
}
}

Each element needs to have a unique id in HTML so you should not have the same id on all your checkbox elements. getElementById will only return one element because it expects the id to be unique, only the first checkbox will be disabled.
I would suggest that you give all these checkboxes a class:
<input type="checkbox" name="txtUserID[]" class="example" value="SysAd">
Then use getElementsByClassName
var disableUser = !document.getElementById('rdGrp').checked;
var x = document.getElementsByClassName("example");
for (var i = 0; i < x.length; i++) {
x[i].disabled = disableUser;
}
Unique: Two elements cannot have the same id as one another.

If you remove the duplicated id's, then you can use this...
function disableCheckboxes(){
var chklist = document.getElementsByName('txtUserID[]');
var chk = !document.getElementById('rdGrp').checked;
for(var i=0;i<chklist.length;i++){
chklist[i].disabled=chk;
}
}

you do a common mistake. Your "inputs" do have the same "id". This is not right, an id should always be unique. If you want to access an element in Javascript you use:
var uniqueElemem = document.getElementById("txtUserID"); // returns only 1 element.
If you want to access a group of elements you use:
// returns an array of all elements which have the class "txtUserGroup".
var groupElem = document.getElementsByClassName("txtUserGroup");
So you have to change your HTML to something like this:
<input type="checkbox" name="txtUserID[]" class="txtUserGroup" value="SysAd"> System Admin |
<input type="checkbox" name="txtUserID[]" class="txtUserGroup" value="faculty"> Faculty |
<input type="checkbox" name="txtUserID[]" class="txtUserGroup" value="student"> Student |
<input type="checkbox" name="txtUserID[]" class="txtUserGroup" value="registrar"> Registrar |
<input type="checkbox" name="txtUserID[]" class="txtUserGroup" value="adviser"> Adviser |
<input type="checkbox" name="txtUserID[]" class="txtUserGroup" value="clerk"> Clerk |
<input type="checkbox" name="txtUserID[]" class="txtUserGroup" value="management"> Management
Now you need to change your Javascript to this:
function disableButtons(){
// get all elements with the groupClass
var groupElem = document.getElementsByClassName("txtUserGroup");
//is radio checked?
if(!document.getElementById('rdGrp').checked){
// Check if the array exists or has at least 1 element
if (typeof groupElem !== 'undefined' && groupElem.length > 0) {
//iterate through all elements which you want to be disabled
for (var index = 0; index < groupElem.length; ++index) {
// disable all elements with given class.
groupElem[index].disabled=true;
}
}
}
}
PS.: You don't need to use Classes, there is a similar way with:
var groupElem = document.getElementsByName("txtUserID[]");
Hope this helps.
Regards, Megajin

Related

How to push values to input type hidden when clicked on radio button using jQuery?

I am getting values from one variable in array format so by using for loop it will iterate and when click on input type radio button each value with comma separated push to hidden field
I tried this but nothing gets inserted. How can I push those values to the hidden field?
var id = ["1", "2"]; // getting this value from another varaible in array format
for (var i = 0; i < id.length; i++) {
$("input[name=radion_btn" + id[i] + "]").change(function() {
$(".selected_val").push(id[i]); //values like 1,2 want to push in hidden field when click on radio button
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" name="selected_val[]" value="" class="selected_val" />
<input type="radio" name="radion_btn1" value="" />
<input type="radio" name="radion_btn2" value="" />
As per your code. for(var i = 0; i < id.length; i++) { run two times and whenever your event occur. At that time i value come 2 and id[2] comes undefined. Below code should work.
var id = ["1", "2"]; // getting this value from another varaible in array format
arrayData = [];
for (var i = 0; i < id.length; i++) {
$("input[name=radion_btn" + id[i] + "]").change(function() {
console.log($(this).val());
arrayData.push($(this).val()); //values like 1,2 want to push in hidden field when click on radio button
$('.selected_val').val(arrayData.join());
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="value" name="selected_val[]" value="" class="selected_val" />
<input type="radio" name="radion_btn1" value="1" />
<input type="radio" name="radion_btn2" value="2" />
You can simulate a push by adding the hidden input's value before the new value
var id = ["1", "2"]; // getting this value from another varaible in array format
for (var i = 0; i < id.length; i++) {
$(".selected_val").val("");
$("input[name=radion_btn" + id[i] + "]").change(function() {
$(".selected_val").val((i == 0 ? "" : ",") + $(".selected_val").val() + id[i]);
});
}
Here's an example of one approach that might help. See comments in snippet below.
let obj = {}; // create an empty object to store the clicked values
$(".radio").change(function() { // when a radio button is clicked
obj[this.id] = $(this).val(); // store it in the object
$(".selected_val").val(JSON.stringify(obj)); // and add the object to hidden field as string
console.log($(".selected_val").val()); // spit it out to the console
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" name="selected_val[]" value="" class="selected_val" />
<input type="radio" class="radio" name="radion_btn1" id="1" value="1" />1
<input type="radio" class="radio" name="radion_btn2" id="2" value="2" />2
<input type="radio" class="radio" name="radion_btn3" id="3" value="3" />3
You'll notice I added a common class for all radio buttons. This is what I'm attaching the event handler to. I also added the IDs to the radio button elements as well.
This may or may not work best for your scenario, but hopefully gets you started in the right direction.
Update
If you'd rather store the values in an array, just change it to an array:
let arr = [];
$(".radio").change(function() {
arr.push($(this).val());
$(".selected_val").val(JSON.stringify(arr));
}
Of course, that won't associate the ID with the value like with an object.

jquery checkbox with limit dinamis

I have following html:
<input type="checkbox" id="perlengkapans" data-stok="[1]" onchange="ambil($(this))"> name item 1
<input type="checkbox" id="perlengkapans" data-stok="[4]" onchange="ambil($(this))"> name item 2
<input type="checkbox" id="perlengkapans" data-stok="[0]" onchange="ambil($(this))"> name item 3
jquery :
function ambil(x){
var limit = x.data('stok')
var cnt = $('#perlengkapans:checked').length
if (cnt>limit){
x.prop('checked', '')
alert('you can maximum '+ limit)
}
}
I want to show a message as "you can maximum <variable_limit_value>", if the stock has reached the limit.
But it is not showing the message. Please help.
Change Input attribute - onchange="ambil((this))"
And your function to -
function ambil(x) {
limit = $(x).data('stok')
cnt = $('#perlengkapans:checked').length
if (cnt > parseInt(limit,10) ) {
$(x).prop('checked', '')
alert('you can maximum ' + limit)
}
}
Not sure, what you are achieving with you code.
But, depending upon your code, following are corrections:
1) In HTML DOM, there should be only one id for one element. In short id is a unique property. In your case, there were three elements with same id. Need to fix it.
2) Change id property to name and access the same. There can be multiple elements with same name.
Corrected Code:
<input type="checkbox" name="perlengkapans" data-stok="[1]" onchange="ambil($(this))"> name item 1
<input type="checkbox" name="perlengkapans" data-stok="[4]" onchange="ambil($(this))"> name item 2
<input type="checkbox" name="perlengkapans" data-stok="[0]" onchange="ambil($(this))"> name item 3
<script>
function ambil(x){
var limit = x.data('stok')
var cnt = $('[name=perlengkapans]:checked').length; // observe what is changed here.
if (cnt>limit){
x.prop('checked', '')
alert('you can maximum '+ limit)}}
</script>
First of all, IDs should not be repeated and the logic seems to be wrong. Try something like below.
<input type="checkbox" id="perlengkapans1" name="perlengkapans" data-stok="1" value="name item 1" />
<input type="checkbox" id="perlengkapans2" name="perlengkapans" data-stok="4" value="name item 2" />
<input type="checkbox" id="perlengkapans3" name="perlengkapans" data-stok="0" value="name item 3" />
In js file add this
$("input[name='perlengkapans']").on("change", function(){
if($("input[name='perlengkapans']":checked").length > $(this).data('stok')) {
// Display Alert
}
});
});

how to set another field value in same row

Given a grid with 5 columns and an array of the IDs in column 2 how do you set the boolean value of column 1 to true for the IDs in the array? There are 25 rows and 5 of the rows are in the array.
var ProductIDArray = [2,5,9,12,16];
var i;
for (i = 0; i < ProductIDArray.length; i++) {
document.getElementById("chk").checked = true;
}
First mistake: you can't/shouldn't have duplicate IDs on the page. Either use classes, or make those IDs unique for each element.
Second mistake: you need to check different element each time in the loop.
Based on this:
Column 1 is a checkbox column. Only the ones in the array should have the checkbox checked. The other rows shouldn't have column 1 checked.
Let's try to fix it. Assuming that your checkbox IDs are chk_N where N is the number that matches the product ID (chk_1, chk_2, etc...), the code should look like this:
var ProductIDArray = [2,5,9,12,16];
var i;
for (i = 0; i < ProductIDArray.length; i++) {
document.getElementById("chk_" + ProductIDArray[i]).checked = true;
}
Here's an example:
var ProductIDArray = [2, 5, 9, 12, 16];
var i;
for (i = 0; i < ProductIDArray.length; i++) {
document.getElementById("chk_" + ProductIDArray[i]).checked = true;
}
<input type="checkbox" id="chk_11" />11<br>
<input type="checkbox" id="chk_2" />2<br>
<input type="checkbox" id="chk_33" />33<br>
<input type="checkbox" id="chk_45" />45<br>
<input type="checkbox" id="chk_65" />65<br>
<input type="checkbox" id="chk_5" />5<br>
<input type="checkbox" id="chk_16" />16<br>
<input type="checkbox" id="chk_9" />9<br>
<input type="checkbox" id="chk_12" />12<br>
...

Looping through checkboxes with javascript

I have a number of checkboxes which I am wanting to check if they are checked (1) or not checked (0). I want to place the results in an array so that I can send them to the server to saved in a table. I have tried the below code:
<input class="publish" id="chkBox1" type="checkbox" checked>
<input class="publish" id="chkBox2" type="checkbox" checked>
<input class="publish" id="chkBox3" type="checkbox" checked>
<input class="publish" id="chkBox4" type="checkbox" checked>
<input class="publish" id="chkBox5" type="checkbox" checked>
<script>
$('#save-btn').click(function(evt){
evt.preventDefault();
var numberOfChBox = $('.publish').length;
var checkArray = new Array();
for(i = 1; i <= numberOfChBox; i++) {
if($('#chkBox' + i).is(':checked')) {
checkArray[i] = 1;
} else {
checkArray[i] = 0;
}
}
alert(checkArray);
});
</script>
but the alert outputs this:
,1,0,1,0,1,1
The values are correct except the first index in undefined. There are only a total of 5 checkboxes and yet the array is 6 indexes long. Why is this?
Try this efficient way bruvo :) http://jsfiddle.net/v4dxu/ with proper end tag in html: http://jsfiddle.net/L4p5r/
Pretty good link: https://learn.jquery.com/javascript-101/arrays/
Also in your html end your tag /> i.e.
<input class="publish" id="chkBox4" type="checkbox" checked>
rest should help :)
Code
var checkArray = new Array();
$('input[type=checkbox]').each(function () {
this.checked ? checkArray.push("1") : checkArray.push("0");
});
alert(checkArray);
As mentioned in the answers above the problem is with the index(i). But if you want to simplify the code further, How about the following code?
var checkArray = [];
$('input.publish').each(function () {
checkArray.push($(this).is(':checked'));
});
alert(checkArray);
Take into account that the first element you write is checkArray[1], as i starts with 1, instead of checkArray[0].
Replace checkArray[i] with checkArray[i-1] inside the for bucle

Jquery only registers one id

I have three checkboxes that looks like this:
<input id="image_tagging" class="1" type="checkbox" value="1" checked="checked" name="data[image_tagging]">
now i wanted to create some ajax (which is working fine) however only the first checkbox has the event:
here is my Jquery function:
$('#image_tagging').click(function(){
var value = 0;
var websiteID = $(this).attr('class');
if($(this).attr('checked')){
value = 4;
}else{
value = -4;
}
alert('works! '+'id = '+websiteID+" value = "+value );
});
So my question is. why is this click function only happening for one of my checkboxes? (if it matters it is only the first checkbox that is working)
ids must be unique on an html page. Instead use a class in the markup and a class selector in jQuery.
HTML
<input class="image_tagging 1" type="checkbox" value="1" checked="checked" name="data[image_tagging]">
Javascript
$('.image_tagging').click(function(){
var value = 0;
var websiteID = $(this).attr('class');
if($(this).attr('checked')){
value = 4;
}else{
value = -4;
}
alert('works! '+'id = '+websiteID+" value = "+value );
});
IDs have to be unique change the id to class instead
id="image_tagging"
to
class="image_tagging"
then
$('.image_tagging').click(function(){
in html
<input class="image_tagging" type="checkbox" value="1" checked="checked" name="data[image_tagging]">
in js
$('.image_tagging').click(function(){
// your code
});
id must be unique, use class instead or try this...
$('input[type="checkbox"]').click(function(){
var value = 0;
var websiteID = $(this).attr('class');
if($(this).attr('checked')){
value = 4;
}else{
value = -4;
}
alert('works! '+'id = '+websiteID+" value = "+value );
});
no need to change any HTML code you wrote already...
ID should be unique in your DOM structure. Use class instead of ID for such things.
<input id="image_tagging" class="img_tagging 1" type="checkbox" value="1" checked="checked" name="data[image_tagging]">
And then instead of #image_tagging use .image_tagging for binding click event
$('.image_tagging').click(function(){

Categories

Resources