jquery checkbox with limit dinamis - javascript

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
}
});
});

Related

Check number of checkboxes depending on input

I have this following checkbox on my page
<div class="col-sm-6">
<label>Product Show</label>
<input type="checkbox" name="edprodShow" value="1" >Shape<br>
<input type="checkbox" name="edprodShow" value="2" >Color<br>
<input type="checkbox" name="edprodShow" value="3" >Design<br>
</div>
I would get values like 1 or 2 or 3(Externally, like in a JSON and i would extract that data). I want to set first check box if 1 and 1st and 2nd if two check box and all three if I get 3.(i.e) Get only shape for 1 and color + shape for 2 and color+shape+design for 3
I have tried many sources and ways but not finding the appropriate output how can I do it ?
Edit :
Code I tried to do
if(split_data[7].toString() === "1"){
$('#edprodShow').prop('checked', true);
}else if(split_data[7].toString() === "2"){
}else if(split_data[7].toString() === "3"){
$('#edprodShow').prop('checked', true);
}
where split_data[7] gives me 1,2 or 3
Try this.
Sample Json from server
var json = { edprodShow: [1,2,4]};
Code
var checker = function(data){
$("[name='edprodShow']").attr('checked', false);
$.each(data.edprodShow, function(i, value){
$("[name='edprodShow'][value='"+ value +"']").attr('checked', true);
}
}
Call the function
checker(json);
I got the solution dear ☺
you can do this by javascript :
$(document).ready(function(){
var $checkboxes = $('#devel-generate-content-form td input[type="checkbox"]');
$checkboxes.change(function(){
var countCheckedCheckboxes = $checkboxes.filter(':checked').length;
// $('#count-checked-checkboxes').text(countCheckedCheckboxes);
$('#edit-count-checked-checkboxes').val(countCheckedCheckboxes);
})
Here you can see Demo

Disable checkbox array when radio button is not checked

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

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

Difficulty inserting variable into jquery attribute identification

I'm trying to us jquery to detect if another text box in the same group is checked. The code below is shows how I'm trying to retrieve the group name when the advanced box is checked and use it to see if the accompanying Basic box is checked. The problem is that "basicTrue" is always assigned "undefined", regardless of the condition of the basic checkbox.
<div id="boxes">
<input style="text-align:center;" type="checkbox" name="group1" value="Basic">
<input style="text-align:center;" type="checkbox" name="group1" value="Advanced">
<input style="text-align:center;" type="checkbox" name="group2" value="Basic">
<input style="text-align:center;" type="checkbox" name="group2" value="Advanced">
</div>
$("#boxes").contents().find(":checkbox").bind('change', function(){
val = this.checked;
var $obj = $(this);
if($obj.val()=="Advanced"){
var group = $obj.attr("name");
var basicTrue = $('input[name=group][value="Basic"]').prop("checked");
if(basicTrue)
{
//Do stuff
}
else
{
$obj.attr('checked', false);
}
}
This code is a proof of concept I used to prove that code formatted this way works, it does return the status of the "Basic" checkbox in "group1".
var basicTrue = $('input[name="group1"][value="Basic"]').prop("checked");
I know the variable "group" is being given the right name: group1 for example. Is there a reason why using this variable in the code wouldn't work?
Those are variables, and they need to be concentenated into the string in the selector, like so:
$('input[name="' + group + '"][value="Basic"]').prop("checked");
A simplified version:
$("#boxes input[type='checkbox']").on('change', function(){
var bT = $('input[name="'+ this.name +'"][value="Basic"]').prop("checked");
if( this.value == "Advanced" && bT) {
//Do stuff
} else {
$(this).prop('checked', false);
}
});

Sync Selected Radio Button between 2 radio button groups - Opposites

I need to do something similar to JQuery Sync Selected Radio Button between 2 radio button groups.
I have 2 radio groups -
<input type="radio" name="radio_A" id="radio_A_1" value="1" />1st
<input type="radio" name="radio_A" id="radio_A_2" value="2" />2nd
<input type="radio" name="radio_B" id="radio_B_1" value="1" />1st
<input type="radio" name="radio_B" id="radio_B_2" value="2" />2nd
When radio_A_1 is checked, I need radio_B_2 synced/checked. The relationships would be-
radio_A_1=>radio_B_2
radio_A_2=>radio_B_1
radio_B_1=>radio_A_2
radio_B_2=>radio_A_1
Using the answer provided #8804502
$('input[name=radio_A]').change(function() {
var index = $(this).index('input[name=radio_A]');
console.log(index);
$('input[name=radio_B]:eq(' + index + ')').attr('checked','checked');
});
I get same=>same, but only when A changes-
radio_A_1=>radio_B_1
radio_A_2=>radio_B_2
So if I copy it, changing it if from A=>B to B=>A-
$('input[name=radio_A]').change(function() {
var index = $(this).index('input[name=radio_A]');
console.log(index);
$('input[name=radio_B]:eq(' + index + ')').attr('checked','checked');
});
$('input[name=radio_B]').change(function() {
var index = $(this).index('input[name=radio_B]');
console.log(index);
$('input[name=radio_A]:eq(' + index + ')').attr('checked','checked');
});
I get same=>same, when either A or B changes -
radio_A_1=>radio_B_1
radio_A_2=>radio_B_2
radio_B_1=>radio_A_1
radio_B_2=>radio_A_2
How can I sync them 1=>2/2=>1, instead of 1=>1/2=>2? And can it be done with 1 block of code, instead of 2?
You need to add some code to take the index of the element just clicked and set it to 0 if it is 1, or 1 if it is 0. The first way that came to mind is as follows:
$('input[name=radio_A]').change(function() {
var index = $(this).index('input[name=radio_A]') === 1 ? 0 : 1;
$('input[name=radio_B]:eq(' + index + ')').attr('checked', 'checked');
});
$('input[name=radio_B]').change(function() {
var index = $(this).index('input[name=radio_B]') === 1 ? 0 : 1;
$('input[name=radio_A]:eq(' + index + ')').attr('checked', 'checked');
});
Demo: http://jsfiddle.net/cTQeJ/1/
Though you could also try:
var index = 1 - $(this).index('input[name=radio_A]');
(Or the following demo uses kind of a fun hack if you like to make your code confusing: http://jsfiddle.net/cTQeJ/)
"And can it be done with 1 block of code, instead of 2?"
If you can modify the html slightly it is pretty easy with a single, short code block. Try a change like this:
<input type="radio" name="radio_A" data-sync="1" value="1" />1st
<input type="radio" name="radio_A" data-sync="2" value="2" />2nd
<input type="radio" name="radio_B" data-sync="2" value="1" />1st
<input type="radio" name="radio_B" data-sync="1" value="2" />2nd
I've added a data-sync attribute to each radio button (and removed the id attribute since it wasn't being used, but obviously you can leave that in if needed). Then you can write a simple function like this:
var $radios = $('input[data-sync]');
$radios.change(function() {
$radios.filter('[data-sync="' + $(this).attr('data-sync') + '"]')
.prop('checked', true);
});​
...that basically says whenever any of the radio buttons is checked, find all other radio buttons with a data-sync attribute of the same value and check them too.
Note that this will work with more than two groups, as shown in this demo: http://jsfiddle.net/cTQeJ/2/

Categories

Resources