how to select singel and multiple checkbox with radiobutton - javascript

i'm stuck with this problem. i have 2 radiobutton and few checkbox. what i want to do is if radiobutton1 chacked, it only allow check 1 checkbox, then if radiobutton2 chacked, it will allow all checkbox to be checked.
i've been tried some script, but not any of them work.
this is my code for sample.
HTML
<input type="radio" id="radio1" name="radiobtn1" />
<input type="radio" id="radio1" name="radiobtn2" />
<input type="checkbox" name="cb" value="1" onclick="test(this)" />
<input type="checkbox" name="cb" value="2" onclick="test(this)"/>
<input type="checkbox" name="cb" value="3" onclick="test(this)"/>
<input type="checkbox" name="cb" value="4" onclick="test(this)"/>
<input type="checkbox" name="cb" value="5" onclick="test(this)"/>
script for select only 1 checkbox
function test(id){
var cb = document.getElementsByName("cb");
Array.prototype.forEach.call(cb,function(el){
el.checked = false;
});
id.checked = true;
}
my script
$(function test(id){
$("#radio1, #radio2").change(function(){
if($("#radio1").is(":checked")){
var cb = document.getElementsByName("cb");
Array.prototype.forEach.call(cb,function(el){
el.checked = false;
});
id.checked = true;
}
else if($("#radio2").is(":checked")){
}
});
});
thank you for your help.

it's like your question has been solved.
next time try to find it first.
but you can try this script.
var $form = $('#form1');
var $checkboxes = $('input[type=checkbox]');
var $selectionType = $('input[type=radio]');
var $output = $('#output');
// Used to determine if the Multi radio is selected
var isMulti = false;
// Listen to change event on the radio buttons and set isMulti
$selectionType.on('change', function( e ) {
// Check the value of what radio button was clicked
isMulti = $( e.target ).val() === 'Multi';
// Clear all selected checkboxes if user clicked "single"
if( !isMulti ) {
$checkboxes.each( function( idx, item ) {
$( item ).prop( 'checked', false );
});
}
});
// Listen to clicks on checkboxes
$checkboxes.on('change', function( e ) {
// Store what was just clicked
var $this = $( e.target );
// If Multi is not selected, then remove the check from all checkboxes except
// the one that the user actually clicked on
if( !isMulti ) {
$checkboxes.each( function( idx, item ) {
var $item = $( item );
if( $item.attr('id') === $this.attr('id') ) {
return true;
}
$item.prop('checked', false );
});
}
});
http://jsfiddle.net/grammar/pdx8gccu/2/

Related

how to add class to parent label of the checked radio buttons on the page, once refreshed

Each radio button is inside a label in my html markup. I cannot change the markup. I used the following JavaScript code to add event listener. But when I refresh the page, the radio buttons are still checked but the parent element doesn't have that class anymore because the event listener will again add the class to the parent label when I click it again. How to select all the checked radio button's parents once the page reloads to add the class again.
let form = document.querySelector( "form" );
form.addEventListener( "click", ( evt ) => {
let trg = evt.target,
trg_par = trg.parentElement;
if ( trg.type === "radio" && trg_par && trg_par.tagName.toLowerCase() === "label" ) {
let prior = form.querySelector( 'label.checked input[name="' + trg.name + '"]' );
if ( prior ) {
prior.parentElement.classList.remove( "checked" );
}
trg_par.classList.add( "checked" );
}
}, false );
As you have not shared your complete code, I have replicated the HTML in my way.
You can open the commented code in your application.
tags can be modified as per your HTML
<!DOCTYPE html>
<html>
<body>
<label>
Radio 1: <input type="radio" name="rdo" value="1" class="rdo"/>
</label>
<label>
Radio 2: <input type="radio" name="rdo" checked="checked" value="2" class="rdo"/>
</label>
<script>
radio = document.getElementsByTagName("input");
for (var trv = 0; trv < radio.length; trv++) {
if (radio[trv].checked) {
let trg = radio[trv],
trg_par = trg.parentElement;
if (trg.type === "radio" && trg_par && trg_par.tagName.toLowerCase() === "label") {
console.log(trg);
/*let prior = form.querySelector( 'label.checked input[name="' + trg.name + '"]' );
if ( prior ) {
prior.parentElement.classList.remove( "checked" );
}*/
trg_par.classList.add("checked");
}
}
}
</script>
</body>
</html>

Get dynamically value from checkbox jQuery

I need help with get value from checkbox with jQuery.
$( document ).ready( function() {
var value_array = [];
$( document ).on( 'change', '.radio-group input', function(e) {
var $this = $( this ),
value = $this.val();
value_array.push( value );
console.log( $.unique( value_array ) );
$( '#out' ).html( $.unique( value_array ).join() )
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radio-group">
<label>
<input type="checkbox" name="cat_1" value="90" />
Category 1
</label>
<label>
<input type="checkbox" name="cat_2" value="43" />
Category 2
</label>
</div>
<div id="out">
</div>
If category 1 checked, getting value (correct).
If category 2 checked, getting value (correct).
If category 1 un-checked, getting value again (false, i don't want
it).
If category 2 un-checked, getting value again (false, i don't want
it).
I want like this:
If category 1 un-checked, remove the value from output array.
If category 2 un-checked, remove the value from output array.
Check if checkbox is checked, add value into array if it is, remove if it's not.
$(document).ready(function() {
var value_array = [];
$(document).on('change', '.radio-group input', function(e) {
var $this = $(this),
value = $this.val();
if ($this.prop('checked')) value_array.push(value);
else value_array.splice(value_array.indexOf(value), 1);
console.log($.unique(value_array));
$('#out').html($.unique(value_array).join())
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radio-group">
<label>
<input type="checkbox" name="cat_1" value="90" />
Category 1
</label>
<label>
<input type="checkbox" name="cat_2" value="43" />
Category 2
</label>
</div>
<div id="out">
</div>
You don't have to declare an array to begin with (which will pollute your namespace anyway). You can simply select for all the checkboxes, use .filter() to keep those that are checked, and the use .map() to return their values, all done within the callback of the onchange event listener:
// Get values of checked checkboxes
var value_array = $('.radio-group input').filter(':checked').map(function() {
return this.value;
}).get();
console.log(value_array);
Note: Remember to chain .get() at the end of .map(), because it will return a jQuery object/collection and you have to convert it into an array.
See proof-of-concept example below:
$(document).ready(function() {
$(document).on('change', '.radio-group input', function(e) {
var $this = $(this),
value = $this.val();
// Get values of checked checkboxes
var value_array = $('.radio-group input').filter(':checked').map(function() {
return this.value;
}).get();
console.log(value_array);
$('#out').html(value_array.join())
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radio-group">
<label>
<input type="checkbox" name="cat_1" value="90" />
Category 1
</label>
<label>
<input type="checkbox" name="cat_2" value="43" />
Category 2
</label>
</div>
<div id="out">
</div>
You can just fetch an array of all checked values at once:
$( document ).ready( function() {
var value_array = [];
$( document ).on( 'change', '.radio-group input', function(e) {
value_array = $('.radio-group input:checked').map(function() {
return $(this).val();
}).get();
console.log( $.unique( value_array ) );
$( '#out' ).html( $.unique( value_array ).join() )
});
});
JSFiddle
First, you should understand that the "this" value refers to the object that owns the code. In your case, the "this" in
$( document ).on( 'change', '.radio-group input', function(e)
refers to the "document" itself and not the ".radio-group input". Instead you should do the following so that the "this" refers to your checkbox.
var arr = [];
$(".radio-group input").change(function(){
var val = $(this).val();
//push the value into the array if the checkbox is checked
if($(this).prop("checked")==true)
{
arr.push(val);
}
//otherwise, remove the value from the array
else{
//fetch the index of the value in the array
var index = arr.indexOf(val);
//remove that value from the index
arr.splice(index,1);
}
});

Select one checkbox and disable others

I am trying to select one checkbox and disable all others. The problem is I am figure out how to do the reverse. Uncheck and enable all checkboxes.
Html:
This is a dynamic list of checkboxes
<input type="checkbox" id="mycheckbox1"/>
<input type="checkbox" id="mycheckbox2"/>
<input type="checkbox" id="mycheckbox3"/>
I have tried this:
var checkboxlist = $("input:checkbox");
$('.checkbox').on("change", function () {
var itemId = $(this).attr("id");
$.each(checkboxlist, function (index, value) {
var id = $(value).attr("id");
if (!(itemId === id)) {
$(value).attr("disabled", "true");
}
});
})
Much simpler to use not() inside event handler to target all the others.
Use the checked state of current checkbox to determine disabled state
$(':checkbox').change(function(){
// "this" is current checkbox
$(':checkbox').not(this).prop('disabled', this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="mycheckbox1"/>
<input type="checkbox" id="mycheckbox2"/>
<input type="checkbox" id="mycheckbox3"/>
Sounds like for what you are trying to achieve a radio button list may be more appropriate.
<input type="radio" name="myRadio" value="myRadio1"/>
<input type="radio" name="myRadio" value="myRadio2"/>
<input type="radio" name="myRadio" value="myRadio3"/>
var checkboxlist = $("input:checkbox");
$('.checkbox').on("change", function () {
var itemId = $(this).attr("id");
if ($(this).is(':checked')) {
$.each(checkboxlist, function (index, value) {
var id = $(value).attr("id");
if (!(itemId === id)) {
$(value).attr("disabled", "true");
}
});
} else {
$.each(checkboxlist, function (index, value) {
var id = $(value).attr("id");
if (!(itemId === id)) {
$(value).attr("disabled", "false");
}
});
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

How do i set the checkbox item checked after refresh?

I have a dropdowncheckbox and the hiddenfield value.The hidden field values are 1,3,4,5.So I want to set dropdowncheckbox to be checked after postback in jquery for related hiddenfield values.How do I do that?
$(document).ready(function() {
var Statushdn = document.getElementById('<%= hdnSubCategoryId.ClientID%>').value;
var str_array = Statushdn.split(',');
var summar;
$.each($('#ContentPlaceHolder1_ddcbProductStockSubCategory_dv input[type=checkbox]:not(:checked)'), function() {
summar = $(this).val();
for (var i = 0; i < str_array.length; i++) {
if (str_array[i] == summar)
$(this).attr('checked', 'checked');
}
});
});
You can use localstorage to keep the values from checkboxes like:
$(':checkbox').on('change', function () {
//set the check value of checkbox
localStorage.setItem(this.id, this.checked);
});
$(':checkbox').each(function () {
//retrieve the checked value from the checkboxes and 'convert' it to bool
var status = localStorage.getItem(this.id) === "false" ? false : true;
$(this).prop("checked", status);
});
<input type="checkbox" id="chk1" />
<input type="checkbox" id="chk2" />
<input type="checkbox" id="chk3" />
<input type="checkbox" id="chk4" />
fiddle
References:
Window.localStorage

unselecting radio input selection

In a part of my application where i check for duplicate radio input selection and revert if its already selected to early selection.
Here is my html code ..
<input type="radio" name="A" checked="checked" onclick="return check();" />
<input type="radio" name="A" onclick="return check();" />
<br />
<input type="radio" name="B" onclick="return check();" />
<input type="radio" name="B" checked="checked" onclick="return check();" />
Here is the javascript code
function check() {
//logic to check for duplicate selection
alert('Its already selected');
return false;
}
And here is the demo
The above code works fine. The issue is when the input isn't initially checked. In such condition the radio input selection doesn't revert to unchecked.
NOTE: when in checked state, returning false shows and alert and sets the check box to initial checked state. But when initially in non checked state this doesn't work.
In DOM ready, check if any radio button is checked or not. If any radio button is checked, increase the counter by one. In onclick of the radio button, check if the counter value is 1. if yes, return false, else increase counter by 1.
try this code,
html
<input type="radio" name="A" checked="checked" />
<input type="radio" name="A" />
<br />
<input type="radio" name="B" />
<input type="radio" name="B" />
JS
var counterA = 0;
var counterB = 0;
$(document).ready(function () {
if ($("input:radio[name=A]").is(":checked") == true) counterA++;
if ($("input:radio[name='B']").is(":checked") == true) counterB++;
});
$('input:radio[name=A]').click(function () {
if (counterA == 1) {
alert('already checked');
return false;
} else {
counterA++;
}
});
$('input:radio[name=B]').click(function () {
if (counterB == 1) {
alert('already checked');
return false;
} else {
counterB++;
}
});
SEE THIS DEMO
iJay wants to ask several questions and privides the same answers for each question. Each answer can only be choosen once. If a user clicks the same answer the second time a error-message should be shown.
// get all elements
var elements = document.querySelectorAll('input[type="radio"]');
/**
* check if radio with own name is already selected
* if so return false
*/
function check(){
var selected_name = this.name,
selected_value = this.value,
is_valid = true;
// compare with all other elements
for(var j = 0; j < len; j++) {
var el = elements[j];
// does the elemenet have the same name AND is already selected?
if(el.name != selected_name && el.value == selected_value && el.checked){
// if so, selection is not valid anymore
alert('Oups..! You can not select this answer a second time :( Choose another one!')
// check current group for previous selection
is_valid = false;
break;
}
};
return is_valid;
}
/**
* bind your elements to the check-routine
*/
for(var i = 0, len = elements.length; i < len; i++) {
elements[i].onmousedown = check;
}
Here is a DEMO
Use $yourRadio.prop('checked', false); to uncheck the specific radio.
Use like this:
function check() {
//logic to check for duplicate selection
var checked = true ? false : true;
$(this).prop('checked', checked);
return false;
}
1) add class attribute to same type of checkbox elements(which are having same name)
ex: class = "partyA"
2)
var sourceIdsArr = new Array();
function check() {
$('.partyA').each(function() {
var sourceId = $(this).val();
if(sourceIdsArr.indexOf(sourceId) != -1){
sourceIdsArr.push(sourceId );
}
else{
alert('Its already selected');
return false;
}
});
}
Here is your code..
function check() {
//logic to check for duplicate selection
var selectflag=0;
var radiovalue=document.getElementsByName("B");
for(var i=0;i<radiovalue.length;i++)
{
// alert(radiovalue[i].checked);
if(radiovalue[i].checked==true)
{
selectflag=1;
break;
}
}
if(selectflag==1)
{
alert('Its already selected');
return false;
}
return true;
}
Trigger your event on MouseDown. It will work fine.
I think this is something you are looking for :
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<input type="radio" name="A" checked="checked" onclick="return check(this);"/>
<input type="radio" name="A" onclick="return check(this);"/>
<script>
$( document ).ready(function() {
this.currentradio = $("input[name='A']:checked")[0];
});
function check(t) {
var newradio= $("input[name='A']:checked")[0];
if (newradio===document.currentradio){
alert('already selected');
return false
}else{
document.currentradio = $("input[name='A']:checked")[0];
}
}
</script>
</body>
<html>

Categories