Uncheck checkbox when I check another one - javascript

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>

Related

Remove specific characters from string jquery [duplicate]

This question already has answers here:
jQuery: Add values of checkboxes to input text field
(4 answers)
Closed 4 years ago.
OK, So although it seems normal substring or replaces solution answer it is quite complex for me.
I have 3 checkboxes
A,B,C
and one text box
Now, when user select any checkbox the value of checkbox appends into textbox i.e. Fist he selects A -> textbox will be appended by A
Then if selects B -> textbox value will be A, B and so on.
i have done it already.
Now the problem is for unchecking.
If the value of textbox is A,B,C i.e. the selected checkboxes are A,B,C and if user deselects the B then the value should be A,C and then again deselects the c then the value should be A.
I have tried multiple ways but don't work for all conditions, sometimes it becomes A, C or A, B
Any solution?
Thank you in advance :)
You can simply recreate the list on change of a box
let els = [...document.getElementsByClassName('check')];
els.forEach(e => e.addEventListener('change', () => {
document.getElementById('foo').value = els.filter(x => x.checked).map(x => x.value).join();
}))
.flex {
display: flex;
flex-direction: column;
}
<div class="flex">
<input id="foo" />
<label><input type="checkbox" class="check" value="A"/>A</label>
<label><input type="checkbox" class="check" value="B"/>B</label>
<label><input type="checkbox" class="check" value="C"/>C</label>
</div>
Try this:
1) On each checkbox click/unclick get the value of all checked checkboxes. (for example ['A', 'B'])
2) Generate the new string with join the values . ['A', 'B'].join(',') // returns 'A,B'
3) Set the textbox with the new string
If you need code you can submit your current code.
Here's what I came up with, without knowing how you're tracking what's checked or not, it's a data driven approach.
var checked = [];
function updateValue() {
$('#selected').val(checked.toString());
}
$('[type=checkbox]').click(function(e) {
var value = e.target.value;
if(e.target.checked) {
checked.push(value);
} else {
checked.splice(checked.indexOf(value), 1);
}
updateValue();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="A">A<br>
<input type="checkbox" value="B">B<br>
<input type="checkbox" value="C">C<br>
<input type="text" id="selected">
$(function() {
const valArray = []; // our value array here what gonna show in textarea
/**
- on change check if checkbox checked or not
- if checked push value of checkbox to array
if not search in our array "valArray" and get it's index then remove it
- change textarea value with the new array "valArray"
*/
$('.checkboxes input').on('change', function(e) {
const $thisVal = $(this).val(),
isChecked = $(this).is(':checked');
if (isChecked) {
valArray.push($thisVal);
} else {
const searchOnThisVal = valArray.find(item => $thisVal === item),
getTheIdx = valArray.indexOf(searchOnThisVal);
valArray.splice(getTheIdx, 1);
}
$('.textarea').empty();
$('.textarea').text(valArray);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkboxes">
<label>
<input type="checkbox" value="a">
the checkbox A.
</label>
<label>
<input type="checkbox" value="b">
the checkbox B.
</label>
<label>
<input type="checkbox" value="c">
the checkbox C.
</label>
</div>
<textarea class="textarea" placeholder="your choice..."></textarea>
this should work in your case using jQuery API

How to get the value of checkboxes in the order they are selected?

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>

How find empty input value in jquery

I have two checkboxes the one checkbox value is 1 and the second one is 0.
One checkbox is for enabling and other for disabling. Now I want to identify when a user clicks on Disable checkbox How I will get Disable checkbox value and if a user clicks on Enable box then how I will get Enable Checkbox value
<input type="radio" name="forgot_pass" class="forgot_pass_enable" value="1" checked>
<input type="radio" name="forgot_pass" class="forgot_pass_disable" value="0">
I have tried This code but it's not working for me any help
$("body").on('change', '.forgot_pass_enable', function(event)
{
event.preventDefault();
/* Act on the event */
if($('.forgot_pass_enable').val().length > 0)
{
var status = 1;
console.log(status);
}
if($('.forgot_pass_disable').val().length > 0)
{
var status = 0;
console.log(statusasdad);
}
});
Neither of the elements you've shown are checkboxes - they are radio inputs.
To get the selected value apply the same class to both elements, then hook the change event to that class. Then you can simply read the value from it, like this:
$("body").on('change', '.forgot_pass', function(e) {
e.preventDefault();
var status = this.value;
console.log(this.value === '1' ? 'enabled' : 'disabled', status);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="radio" name="forgot_pass" class="forgot_pass" value="1" checked="checked">
<input type="radio" name="forgot_pass" class="forgot_pass" value="0">
If you did want to use a checkbox for this, which would be more applicable for an enable/disable switch, then the method is the same except you look for the checked property instead:
$("body").on('change', '.forgot_pass', function(e) {
e.preventDefault();
var status = this.checked ? '1' : '0'
console.log(status);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="checkbox" name="forgot_pass" class="forgot_pass" value="1" checked="checked">

Javascript - If no radio buttons are selected, check the first one

I'm a beginner in JavaScript. I have several radio buttons on my dynamic page and I want to create a script to make the following:
HTML:
<input type="radio" id="elemainfoto">
<input type="radio" id="elemainfoto">
<input type="radio" id="elemainfoto">
JavaScript:
var radio = '#elemainfoto',
if(radd.value == 0) {
radd.checked the first radio element,
} else {
keep the way it is,
}
If none of the radio elements are marked, mark the first compulsory.
I your expectation is that the first item get selected by default, then you should use HTML and not javascript for that and please note that you should not use two HTML elements with the same id in your case you should either replace by a class and/or add unique Ids for elements.
<input type="radio" class="elemainfoto" id="item1" checked>
<input type="radio" class="elemainfoto" id="item2">
<input type="radio" class="elemainfoto" id="item3>
Updated the answer based on RobG comment.
Something like this in pure JS (I changed ids to classes id should be unique):
var radio = document.querySelectorAll('.elemainfoto'),
checked = false;
for (var i = 0; i < radio.length; i++) {
if (radio[i].checked) {
checked = true;
break;
}
}
if (!checked) {
radio[0].checked = true;
}
else {
alert('something is checked')
}
A little shorter with jQuery:
var $radio = $('.elemainfoto');
if (!$radio.filter(':checked').length) {
$radio[0].checked = true;
}
else {
alert('something is checked')
}
using 'id' attribute in html with the same value more than once is invalid, you should use "name" for an input.
HTML:
<input type="radio" name="elementinfoto" value="1" />
<input type="radio" name="elementinfoto" value="2" />
<input type="radio" name="elementinfoto" value="3" />
JavaScript:
var radio = document.getElementsByName('elementinfoto'); // get all radio buttons
var isChecked = 0; // default is 0
for(var i=0; i<radio.length;i++) { // go over all the radio buttons with name 'elementinfoto'
if(radio[i].checked) isChecked = 1; // if one of them is checked - tell me
}
if(isChecked == 0) // if the default value stayed the same, check the first radio button
radio[0].checked = "checked";
example: http://jsfiddle.net/yxm4N/2/
A radio button group is formed by giving radio buttons the same name. An ID is optional and usually not necessary. If an ID is provided, each should have a different value. And the buttons should have a value so that there's a point to their existence.
To have one button selected by default, simply set the chosen button's checked attribute:
<form id="foo">
<input type="radio" name="elemainfoto" valu="0" checked>0<br>
<input type="radio" name="elemainfoto" valu="1">1<br>
<input type="radio" name="elemainfoto" valu="2">2<br>
<input type="reset">
</form>
Now if no other button is selected, or the form is reset, one button will be selected. Note that if you do not set a button as the default selected, then once a user checks a button, the only way to deselect it is to select a different radio button in the same group, or use a reset button (if provided).
If you want to set the default checked button in script, there are a couple of options. One is:
var buttons = document.getElementsByName('elemainfoto');
buttons[0].defaultChecked = true;
If you really want to check if one is selected, add a button like the following to the form:
<input type="button" value="Check buttons" onclick="checkButtons(this);">
Then the checkButtons function can be:
function checkButtons(el) {
var buttons;
var form = el && el.form;
if (form) {
buttons = form.elemainfoto;
for (var i=0, iLen=buttons.length; i<iLen; i++) {
// If a button is checked, return its value
if (buttons[i].checked) {
return buttons[i].value;
}
}
}
// Otherwise, try to check the first one and return undefined
buttons && buttons[0].checked;
}
you need to know how to use radio element. Id is unique in html page. you should assign same name for each radio element.
<input type="radio" name="elemainfoto" id="first" value="1" />
element 1
<input type="radio" name="elemainfoto" id="second" value="2" />
element 2
<input type="radio" name="elemainfotor" id="thrid" value="3" />
element 3
if you want to check the first radio button as default, set it in input tag attribute.
<input type="radio" name="elemainfoto" id="first" value="1" checked="true"/>
element 1
or you can do it with javascript also,
$("input:radio[name=elemainfoto]:first").attr('checked', true);
you can perform action for each radio button click, to know which item is checked
$(function(){
$('input[type="radio"]').click(function(){
if ($(this).is(':checked'))
{
alert($(this).val());
}
});
});
if you want to perform a separate action for each radio button, try this below code
$(function () {
$('input[type="radio"]').click(function () {
if ($(this).is(':checked')) {
if ($(this).val() == '1') alert('first radio element is checked');
if ($(this).val() == '2') alert('second radio element is checked');
if ($(this).val() == '3') alert('third radio element is checked');
}
});
});
SEE THIS FIDDLE DEMO
Instead of selecting the first one, I prefered to use null
const radio = document.querySelectorAll('.timescale');
let timescale;
if (radio.checked) {
timescale = $('input[name=timescale_radio_buttons]:checked').val()
} else timescale = null;
You can write it like this with less code
HTML
<input type="radio" name="elementinfoto" value="1" />
<input type="radio" name="elementinfoto" value="2" />
<input type="radio" name="elementinfoto" value="3" />
JavaScript
const fields = document.getElementsByName('elementinfoto');
const value = fields.filter(el => el.checked).shift()?.value || null;
if(!value) {
fields.shift().checked = true;
}
You can replace the function shift() by [0] to get the first element if you prefer

make checkbox behave like radio buttons with javascript

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

Categories

Resources