I have an array of comma separated string. This will determined whick checkbox should be disabled.
var lbl = "A,C";
Then I want to compare it on the checkboxes in the form. The check boxes values are A,B,C,D.
Based on the string given, the checkbox which value are A and C should be disabled.
This is my current script:
$('#f_sendTo input[type=checkbox]').each(function() {
var arr_cek_txt = $(this).val().split('||'); //This is checkboxes value
var arr_lbl_ext = lbl.split(','); //this is the string = "A,C"
var val_lbl_ext;
$.each(arr_lbl_ext,function(i){
if(arr_cek_txt[1] == arr_lbl_ext[i]){
$(this).prop("disabled", true);
}
});
});
You can do something like:
Loop thru the checkbox using each(). Check the value and if the value is in array, disable the checkbox.
$(document).ready(function() {
var lbl = "A,C";
var arr_lbl_ext = lbl.split(','); /* Init this outside each. So that no need to do this every loop*/
$('#f_sendTo input[type=checkbox]').each(function() {
var arr_cek_txt = $(this).val(); /* Get the value of checkbox */
if (arr_lbl_ext.indexOf(arr_cek_txt) == -1) $(this).prop("disabled", false);
else $(this).prop("disabled", true);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="f_sendTo">
<input type="checkbox" name="cb" value="A"> A <br />
<input type="checkbox" name="cb" value="B"> B <br />
<input type="checkbox" name="cb" value="C"> C <br />
<input type="checkbox" name="cb" value="D"> D <br />
</div>
Related
Hey I have two issues with this following code.
First of all when I check the checkbox number 3 it automatically checks number 2, I only want that if I check it my self (Like when I check checkbox number 2).
The second issue is I can't uncheck a checkbox after checking it.
var cbs = document.getElementsByName("test");
function demo(obj) {
var hzp = cbs[1];
var ht = cbs[2];
for (var i = 0; i < cbs.length; i++) {
if(cbs[i].value == hzp.value || cbs[i].value === ht.value) {
if(cbs[i].value == obj.value) {
if(cbs[i].checked && hzp.checked || ht.checked) {
hzp.checked = true;
ht.checked = true;
}
}
}
cbs[i].checked = false;
}
obj.checked = true;
}
checkbox 1 <input type="checkbox" name="test" id="demo1" value="demo01" onClick="demo(this)">
checkbox 2 <input type="checkbox" name="test" id="demo2" value="demo02" onClick="demo(this)">
checkbox 3 <input type="checkbox" name="test" id="demo3" value="demo03" onClick="demo(this)">
checkbox 4 <input type="checkbox" name="test" id="demo" value="demo04" onClick="demo(this)">
e.target.value==cbs[0].value ?
if clicked input has value of demo01
cbs[3].checked=false
set demo04 checked to false
: e.target.value==cbs[3].value
else if clicked input has value of demo04
? cbs[0].checked=false
set demo01 checked to false
: null
else, nothing...
var cbs = document.getElementsByName("test")
cbs.forEach( test => {test.addEventListener("change", (e) => {
e.target.value==cbs[0].value ? cbs[3].checked=false : e.target.value==cbs[3].value ? cbs[0].checked=false : null
})
})
checkbox 1 <input type="checkbox" name="test" id="demo1" value="demo01" >
checkbox 2 <input type="checkbox" name="test" id="demo2" value="demo02">
checkbox 3 <input type="checkbox" name="test" id="demo3" value="demo03">
checkbox 4 <input type="checkbox" name="test" id="demo" value="demo04">
Look closely - this is not jQuery.
This gets your bigger job simplified - that of making the checkboxes work like radio buttons. Now, you should be able to quite easily add logic to make it do the rest of what you want.
The basic idea is to:
a. Trap when any checkbox is clicked
b. Store the checked checkbox value
c. Cache the checkbox itself (so we can turn it back on)
d. Uncheck ALL checkboxes
e. Re-check the one the user just checked.
f. Update div / variable with the stored value
Now, just add some additional (e.g. storedVal) variables to keep track of additional checkboxes.
const $ = document.querySelector.bind(document);
const $$ = document.querySelectorAll.bind(document);
var storedVal = '';
$$('input').forEach((el) => {
el.addEventListener('click', function(e){
storedVal = e.target.value;
let ckcb = e.target;
uncheckAll();
ckcb.checked = true;
console.log(storedVal);
$('#msg').innerText = storedVal;
});
});
const uncheckAll = () => {
$$('input').forEach((el) => {
el.checked = false;
});
}
#msg{
position:absolute;
top:70px;
right:30px;
font-size:2rem;
padding:10px;
background:wheat;
}
checkbox 1 <input type="checkbox" name="test" id="demo1" value="demo01">
checkbox 2 <input type="checkbox" name="test" id="demo2" value="demo02">
checkbox 3 <input type="checkbox" name="test" id="demo3" value="demo03">
checkbox 4 <input type="checkbox" name="test" id="demo" value="demo04">
<div id="msg"></div>
hope you can help me :)
I have this code to get the value of the checkboxes:
function check() {
var Input = Array.prototype.slice.call(document.querySelectorAll(".checkboxes:checked")).map(function(el) {
return el.value;
}).join(',')
document.getElementById('output2').innerHTML = Input;
return false;
}
I want that the output is in the order I selected the checkboxes. Is there a way to get them in correct order?
You can set the timestamp to them when they are changed (comments inline)
var allCheckboxes = document.querySelectorAll("input[type='checkbox'][data-name]");
//bind the event to set time value on change
[...allCheckboxes].forEach(s => s.addEventListener("change", function(e) {
e.currentTarget.timeval = new Date().getTime();
}));
document.querySelector("button").addEventListener("click", check);
function check() {
var output = [...allCheckboxes]
.filter(s => s.checked) // filter out non-checked
.sort((a, b) => a.timeval - b.timeval) //sort by timeval
.map(s => s.getAttribute("data-name")).join(","); //fetch only data-name for display
document.getElementById('output').innerHTML = output;
}
Check 1 <input type="checkbox" data-name="check1"> <br/> Check 2 <input type="checkbox" data-name="check2"> <br/> Check 3 <input type="checkbox" data-name="check3"> <br/> Check 4 <input type="checkbox" data-name="check4"> <br/> Check 5 <input type="checkbox"
data-name="check5"> <br/>
<button>check</button>
<div id="output"></div>
You can set an array and save the values as they are selected.
You can achive this by giving each chcekbox an event listener.
In the event listener you add an if to validate if the click event was when checked and then add them to your list/array.
Hope this helps :)
var checks = document.querySelectorAll('input[type=checkbox]');
var order = [];
for(var i=0; i<checks.length;i++){
checks[i].addEventListener("click", function(){
if(this.checked)
order.push(this.value);
})
}
<input type="checkbox" value="A">A
<input type="checkbox" value="B">B
<input type="checkbox" value="C">C
<input type="checkbox" value="D">D
<br>
<button onclick="console.log('Order: '+order)">Check order</button>
You can add a data-id attribute to each section. And when you click on one checkbox, change the attribute values of each checkbox to a serial number. To do this, it's easier to use jquery
You could use a Set and add or delete depending of the checked state of the check box.
Set returns the items in insertation order.
var checks = document.querySelectorAll('input[type=checkbox]'),
order = new Set,
i
for (i = 0; i < checks.length; i++) {
checks[i].addEventListener("click", function() {
order[['delete', 'add'][+this.checked]](this.value);
});
}
<input type="checkbox" value="A">A
<input type="checkbox" value="B">B
<input type="checkbox" value="C">C
<input type="checkbox" value="D">D
<br>
<button onclick="console.log('Order: '+[...order])">Check order</button>
I'm trying to add the values of any checked checkbox to an input text field.
Here's my fiddle: http://jsfiddle.net/Lf6ky/
$(document).ready(function() {
$(":checkbox").on('click', function() {
if ($(':checkbox:checked')) {
var fields = $(":checkbox").val();
jQuery.each(fields, function(i, field) {
$('#field_results').val($('#field_results').val() + field.value + " ");
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" id="field_results" /><br>
<input type="checkbox" value="1">1<br>
<input type="checkbox" value="2">2<br>
<input type="checkbox" value="3">3
In this example, I have 3 checkboxes, with the values 1,2,3. If I click on all these checkboxes, then the input field should look like this: 1 2 3
If I uncheck any of these checkboxes, then that corresponding value should disappear in the input field.
How do I do this?
I've stored the collection of check-boxes in a variable $checks, then attach the handler to this collection. Inside the event handler, I take the collection once again and filter (return) only the check-boxes that are checked.
map() returns a jQuery object containing the values of the checked check-boxes, get() converts it to a standard array. Join those values with a space and put 'em in the input.
$(document).ready(function(){
$checks = $(":checkbox");
$checks.on('change', function() {
var string = $checks.filter(":checked").map(function(i,v){
return this.value;
}).get().join(" ");
$('#field_results').val(string);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="field_results"/><br>
<input type="checkbox" value="1">1<br>
<input type="checkbox" value="2">2<br>
<input type="checkbox" value="3">3
On click of a checkbox, loop through the checked inputs, append to a string then assign that to your text box:
$(document).ready(function() {
$("input:checkbox").click(function() {
var output = "";
$("input:checked").each(function() {
output += $(this).val() + " ";
});
$("#field_results").val(output.trim());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" id="field_results" /><br>
<input type="checkbox" value="1">1<br>
<input type="checkbox" value="2">2<br>
<input type="checkbox" value="3">3
First issue is
if($(':checkbox:checked')) {
will always be true since it returns a jQuery object and an object is a truthy value. If you were to use the if, you want to check the length. aka if($(':checkbox:checked').length) {
Secondly
var fields = $(":checkbox").val();
returns only the first element's value and it returns any checkbox, not just the checked ones. You want to loop through $(':checkbox:checked')
One way to attack it is to use an each and an array.
$(":checkbox").on('change', function() {
var total = [];
$(':checkbox:checked').each( function(){ //find the checked checkboxes and loop through them
total.push(this.value); //add the values to the array
});
$('#field_results').val(total.join(" ")); //join the array
});
Problem
if($(':checkbox:checked')) will always be true
var fields = $(":checkbox").val(); Will give first checkbox value
You can try this.
$(document).ready(function() {
$(":checkbox").on('click', function() {
var fields = '';
$(":checkbox").each(function() {
if (this.checked) {
fields += $(this).val() + ' ';
}
});
$('#field_results').val($.trim(fields))
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" id="field_results" />
<br>
<input type="checkbox" value="1">1
<br>
<input type="checkbox" value="2">2
<br>
<input type="checkbox" value="3">3
I have some set of radio button. I am trying to get checked radio button value using java script. But I got the error of uncaught id. I do the following code in html 5. I am not getting the value.
function timeout()
{
if (document.getElementById["RadioButton1"].checked)
{
choice = document.getElementById["RadioButton1"].value;
alert('choice');
}
if (document.getElementById["RadioButton2"].checked)
{
choice = document.getElementById["RadioButton2"].value;
alert('choice');
}
if (document.getElementById["RadioButton3"].checked)
{
choice = document.getElementById["RadioButton3"].value;
alert('choice');
}
if (document.getElementById["RadioButton4"].checked)
{
choice = document.getElementById["RadioButton4"].value;
alert('choice');
}
var c = document.getElementById("label1").value;
}
If you use the same name(in same radio button group) for all radio buttons like this
<input type="radio" id="RadioButton1" name="radio_group" value="1"/>
<input type="radio" id="RadioButton2" name="radio_group" value="2"/>
<input type="radio" id="RadioButton3" name="radio_group" value="3"/>
you can get the selected(checked radio button value ) using jQuery,in one line.
var Val = $("input[name=radio_group]:checked").val();
A set of radio buttons should all have the same name. So get the set, find the checked one and read its value:
function getValue(name) {
var rbs = document.getElementsByName(name);
for (var i=0, iLen=rbs.length, i<iLen; i++) {
if (rbs[i].checked) {
return rbs[i].value;
}
}
}
If the controls are in a form (which the usually are) and you have a reference to the form, you can get the set using:
var rbs = formRef[name];
$(document).ready(function(){
$('#btnsubmit').click(function(){
var result = $('input[type="radio"]:checked');
if (result.length > 0) {
$('#result').html(result.val()+" is Checked");
}else{
$('#result').html(" No radio button is Checked");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female
<input type="submit" id="btnsubmit" value="submit">
<div id="result"></div>
The major problem visible from your code is a syntax error.
document.getElementById is a method and not an object, so you should call it with parens:
// --------------------v--------------v
document.getElementById("RadioButton1").value
This is ans for #yogi comment(
how we can implement same for checkboxes?)
$(document).ready(function(){
$('#btnsubmit').click(function(){
var result = $('input[type="checkbox"]:checked');
if (result.length > 0) {
var resultstring = result.length +"checkboxes checked <br>";
result.each(function(){
resultstring += $(this).val()+" <br>"; //append value to exsiting var
});
$('#result').html(resultstring);
}else{
$('#result').html(" No checkbox is Checked");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="checkbox" name="skill" value="Java"> Java
<input type="checkbox" name="skill" value="Jquery"> Jquery
<input type="checkbox" name="skill" value="PHP"> PHP
<input type="submit" id="btnsubmit" value="submit">
<div id="result"></div>
I need to manipulate the behavior of the check boxes with javascript. They should basically behave like radio buttons (only one selectable at a time, plus unselect any previous selections).
The problem is that I can't use plain radio buttons in first place, because the name attribute for each radio button would be different.
I know its not the ultimate and shiniest solutions to make an apple look like a pear, and w3c wouldn't give me their thumbs for it, but it would be a better solution right now than to change the core php logic of the entire cms structure ;-)
Any help is much appreciated!
HTML :
<label><input type="checkbox" name="cb1" class="chb" /> CheckBox1</label>
<label><input type="checkbox" name="cb2" class="chb" /> CheckBox2</label>
<label><input type="checkbox" name="cb3" class="chb" /> CheckBox3</label>
<label><input type="checkbox" name="cb4" class="chb" /> CheckBox4</label>
jQuery :
$(".chb").change(function() {
$(".chb").prop('checked', false);
$(this).prop('checked', true);
});
if you want user can unchecked selected item :
$(".chb").change(function() {
$(".chb").not(this).prop('checked', false);
});
Demo :
http://jsfiddle.net/44Zfv/724/
There are many ways to do this. This is a clickhandler (plain js) for a div containing a number of checkboxes:
function cbclick(e){
e = e || event;
var cb = e.srcElement || e.target;
if (cb.type !== 'checkbox') {return true;}
var cbxs = document.getElementById('radiocb')
.getElementsByTagName('input'),
i = cbxs.length;
while(i--) {
if (cbxs[i].type
&& cbxs[i].type == 'checkbox'
&& cbxs[i].id !== cb.id) {
cbxs[i].checked = false;
}
}
}
Here's a working example.
This is a better option as it allows unchecking also:
$(".cb").change(function () {
$(".cb").not(this).prop('checked', false);
});
I kept it simple...
<html>
<body>
<script>
function chbx(obj)
{
var that = obj;
if(document.getElementById(that.id).checked == true) {
document.getElementById('id1').checked = false;
document.getElementById('id2').checked = false;
document.getElementById('id3').checked = false;
document.getElementById(that.id).checked = true;
}
}
</script>
<form action="your action" method="post">
<Input id='id1' type='Checkbox' Name ='name1' value ="S" onclick="chbx(this)"><br />
<Input id='id2' type='Checkbox' Name ='name2' value ="S" onclick="chbx(this)"><br />
<Input id='id3' type='Checkbox' Name ='name3' value ="S" onclick="chbx(this)"><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
#DJafari's answer doesn't let unchecking the checkbox. So I've updated it like this:
$(".chb").change(function(e) {
//Getting status before unchecking all
var status = $(this).prop("checked");
$(".chb").prop('checked', false);
$(this).prop('checked', true);
//false means checkbox was checked and became unchecked on change event, so let it stay unchecked
if (status === false) {
$(this).prop('checked', false);
}
});
https://jsfiddle.net/mapetek/nLtb0q1e/4/
Just in case it helps someone else
I was having the same situation where my client needed to have a checkbox behaving like a radio button. But to me it was meaningless to use a checkbox and make it act like radio button and it was very complex for me as I was using so many checkboxes in a GridView Control.
My Solution: So, I styled a radio button look like a checkbox and took the help of grouping of radio buttons.
You could give the group of checkboxes you need to behave like this a common class, then use the class to attach the following event handler:
function clickReset ()
{
var isChecked = false,
clicked = $(this),
set = $('.' + clicked.attr ('class') + ':checked').not (clicked);
if (isChecked = clicked.attr ('checked'))
{
set.attr ('checked', false);
}
return true;
}
$(function ()
{
$('.test').click (clickReset);
});
Note: This is pretty me just shooting from the hip, I've not tested this and it might need tweaking to work.
I would advise that you do look into finding a way of doing this with radio buttons if you can, as radios are the proper tool for the job. Users expect checkboxes to behave like checkboxes, not radios, and if they turn javascript off they can force through input into the server side script that you weren't expecting.
EDIT: Fixed function so that uncheck works properly and added a JS Fiddle link.
http://jsfiddle.net/j53gd/1/
<html>
<body>
<form action="#" method="post">
Radio 1: <input type="radio" name="radioMark" value="radio 1" /><br />
Radio 2: <input type="radio" name="radioMark" value="radio 2" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Ultimately you can use brackets with the name attribute to create an array of radio input like so:
<input type="radio" name="radioMark[]" value="radio1" />Radio 1
<input type="radio" name="radioMark[]" value="radio2" />Radio 2
<input type="radio" name="radioMark[]" value="radio3" />Radio 3
<input type="radio" name="radioMark[]" value="radio4" />Radio 4
What matters to transfer in the end are whats in the value attribute. Your names do not have to be different at all for each radio button. Hope that helps.
In Simple JS.
Enjoy !
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function onChoiceChange(obj) {
// Get Objects
var that=obj,
triggerChoice = document.getElementById(that.id),
domChoice1 = document.getElementById("Choice1"),
domChoice2 = document.getElementById("Choice2");
// Apply
if (triggerChoice.checked && triggerChoice.id === "Choice1")
domChoice2.checked=false;
if (triggerChoice.checked && triggerChoice.id === "Choice2")
domChoice1.checked=false;
// Logout
var log = document.getElementById("message");
log.innerHTML += "<br>"+ (domChoice1.checked ? "1" : "0") + ":" + (domChoice2.checked ? "1" : "0");
// Return !
return that.checked;
}
</script>
</head>
<body>
<h1 id="title">Title</h1>
<label><input type="checkbox" onclick="onChoiceChange(this)" id="Choice1" />Choice #1</label>
<label><input type="checkbox" onclick="onChoiceChange(this)" id="Choice2" />Choice #2</label>
<hr>
<div id="message"></div>
</body>
</html>
try this
<form id="form" action="#">
<input name="checkbox1" type="checkbox" />
<input name="checkbox2" type="checkbox" />
<input name="checkbox3" type="checkbox" />
<input name="checkbox4" type="checkbox" />
<input name="checkbox5" type="checkbox" />
<input name="checkbox6" type="checkbox" />
<input name="checkbox7" type="checkbox" />
<input name="checkbox8" type="checkbox" />
<input name="checkbox9" type="checkbox" />
<input name="checkbox10" type="checkbox" />
<input type="submit" name="submit" value="submit"/>
</form>
and this is the javascript
(function () {
function checkLikeRadio(tag) {
var form = document.getElementById(tag);//selecting the form ID
var checkboxList = form.getElementsByTagName("input");//selecting all checkbox of that form who will behave like radio button
for (var i = 0; i < checkboxList.length; i++) {//loop thorough every checkbox and set there value false.
if (checkboxList[i].type == "checkbox") {
checkboxList[i].checked = false;
}
checkboxList[i].onclick = function () {
checkLikeRadio(tag);//recursively calling the same function again to uncheck all checkbox
checkBoxName(this);// passing the location of selected checkbox to another function.
};
}
}
function checkBoxName(id) {
return id.checked = true;// selecting the selected checkbox and maiking its value true;
}
window.onload = function () {
checkLikeRadio("form");
};
})();
I like D.A.V.O.O.D's Answer to this question, but it relies on classes on the checkbox, which should not be needed.
As checkboxes tend to be related in that they will have the same (field) name, or a name which make them part of an array, then using that to decide which other checkboxes to untick would be a better solution.
$(document)
.on('change','input[type="checkbox"]',function(e){
var $t = $(this);
var $form = $t.closest('form');
var name = $t.attr('name');
var selector = 'input[type="checkbox"]';
var m = (new RegExp('^(.+)\\[([^\\]]+)\\]$')).exec( name );
if( m ){
selector += '[name^="'+m[1]+'["][name$="]"]';
}else{
selector += '[name="'+name+'"]';
}
$(selector, $form).not($t).prop('checked',false);
});
This code on jsFiddle