How to get all the selected checkboxes after they got unchecked - javascript

Let's start from the beginning...
I have checkboxes in the table and they have unique VALUES.
For example:
<input type="checkbox" value="2">
<input type="checkbox" value="3">
I want to have an array which will add and remove all the checkboxes in the list depending if they were checked or unchecked by the user (only click event) because in some point I'm resetting all of the checkboxes and I only want to save values when user clicks on it.
I have tried this so far but my code is not doing what I need, because this is giving me a double values when user checks and unchecks twice or more...
var selected = new Array();
$('tr td input:checked').each(function() {
selected.push($(this).attr('value'));
console.log(selected);
});
Do I need to use change event to track user behavior?

You have to update array on checked changed of the checkboxex, Assign common class to checkbox to make select simply and selectively.
HTML
<input type="checkbox" value="2" class="chk" />
<input type="checkbox" value="3" class="chk" />
Javascript
var selected;
$('.chk').change(function(){
selected = new Array();
$('tr td input:checked').each(function() {
selected.push($(this).attr('value'));
console.log(selected);
});

You can use the click() handler for this
var selected = new Array();
$(':checkbox').click(function(){
selected.splice(0, selected.length); // emptying last array so to avoid multiple values
$('tr td input:checked').each(function() {
selected.push($(this).attr('value'));
console.log(selected);
});
});

You can do like this also, this will remove elements from array by unchecking checkboxes..
var selected = new Array();
$('input:checkbox').change(function() {
if(this.checked)
selected.push($(this).attr('value'));
else
selected.splice(selected.indexOf(this.value),1);
console.log(selected);
});
Fiddle

I'm sure there is a better way to do this but here's some code a threw together real quick that should work for you.
<html>
<head>
<script>
var chkArray = [];
function addCheckBox() {
var chk1 = document.getElementById('1').checked;
var chk2 = document.getElementById('2').checked;
var chk3 = document.getElementById('3').checked;
var chk4 = document.getElementById('4').checked;
if(chk1 == true && chkArray.indexOf(1) == -1) {
chkArray.push(1);
alert('Added 1');
}else if(chk2 == true && chkArray.indexOf(2) == -1) {
chkArray.push(2);
alert('Added 2');
}else if(chk3 == true && chkArray.indexOf(3) == -1) {
chkArray.push(3);
alert('Added 3');
}else if(chk4 == true && chkArray.indexOf(4) == -1) {
chkArray.push(4);
alert('Added 4');
}
}
</script>
</head>
<body onClick="addCheckBox();">
<input type="checkbox" value="2" id="1">
<input type="checkbox" value="3" id="2">
<input type="checkbox" value="4" id="3">
<input type="checkbox" value="5" id="4">
</body>
</html>

You could try this:
HTML:
<input type="checkbox" name="test[]" value="1"/>
<input type="checkbox" name="test[]" value="2"/>
<input type="checkbox" name="test[]" value="3"/>
JS:
var recorder = [];
$('input[type="checkbox"]').change(function(){
var checkboxs = document.getElementsByName("test[]");
recorder=new Array();
for(var i=0;i<checkboxs.length;i++){
if(checkboxs[i].checked){
recorder.push(checkboxs[i].value);
}
}
console.log(recorder);
});
And JSfiddle DEMO
Hope this is helpful for you.

Related

How to Make an Element Appear and Disappear via Radio Button [duplicate]

I'm looking for a generalized solution for this.
Consider 2 radio type inputs with the same name. When submitted, the one that is checked determines the value that gets sent with the form:
<input type="radio" name="myRadios" onchange="handleChange1();" value="1" />
<input type="radio" name="myRadios" onchange="handleChange2();" value="2" />
The change event does not fire when a radio button is de-selected. So if the radio with value="1" is already selected and the user selects the second, handleChange1() does not run. This presents a problem (for me anyway) in that there is no event where I can catch this de-selection.
What I would like is a workaround for the onChange event for the checkbox group value or alternatively, an onCheck event that detects not only when a radio button is checked but also when it is unchecked.
I'm sure some of you have run into this problem before. What are some workarounds (or ideally what is the right way to handle this)? I just want to catch the change event, access the previously checked radio as well as the newly checked radio.
P.S.
onClick seems like a better (cross-browser) event to indicate when a radio button is checked but it still does not solve the unchecked problem.
I suppose it makes sense why onChange for a checkbox type does work in a case like this since it changes the value that it submits when you check or un-check it. I wish the radio buttons behaved more like a SELECT element's onChange but what can you do...
var rad = document.myForm.myRadios;
var prev = null;
for (var i = 0; i < rad.length; i++) {
rad[i].addEventListener('change', function() {
(prev) ? console.log(prev.value): null;
if (this !== prev) {
prev = this;
}
console.log(this.value)
});
}
<form name="myForm">
<input type="radio" name="myRadios" value="1" />
<input type="radio" name="myRadios" value="2" />
</form>
Here's a JSFiddle demo: https://jsfiddle.net/crp6em1z/
I would make two changes:
<input type="radio" name="myRadios" onclick="handleClick(this);" value="1" />
<input type="radio" name="myRadios" onclick="handleClick(this);" value="2" />
Use the onclick handler instead of onchange - you're changing the "checked state" of the radio input, not the value, so there's not a change event happening.
Use a single function, and pass this as a parameter, that will make it easy to check which value is currently selected.
ETA: Along with your handleClick() function, you can track the original / old value of the radio in a page-scoped variable. That is:
var currentValue = 0;
function handleClick(myRadio) {
alert('Old value: ' + currentValue);
alert('New value: ' + myRadio.value);
currentValue = myRadio.value;
}
var currentValue = 0;
function handleClick(myRadio) {
alert('Old value: ' + currentValue);
alert('New value: ' + myRadio.value);
currentValue = myRadio.value;
}
<input type="radio" name="myRadios" onclick="handleClick(this);" value="1" />
<input type="radio" name="myRadios" onclick="handleClick(this);" value="2" />
As you can see from this example: http://jsfiddle.net/UTwGS/
HTML:
<label><input type="radio" value="1" name="my-radio">Radio One</label>
<label><input type="radio" value="2" name="my-radio">Radio One</label>
jQuery:
$('input[type="radio"]').on('click change', function(e) {
console.log(e.type);
});
both the click and change events are fired when selecting a radio button option (at least in some browsers).
I should also point out that in my example the click event is still fired when you use tab and the keyboard to select an option.
So, my point is that even though the change event is fired is some browsers, the click event should supply the coverage you need.
You can add the following JS script
<script>
function myfunction(event) {
alert('Checked radio with ID = ' + event.target.id);
}
document.querySelectorAll("input[name='myRadios']").forEach((input) => {
input.addEventListener('change', myfunction);
});
</script>
What about using the change event of Jquery?
$(function() {
$('input:radio[name="myRadios"]').change(function() {
if ($(this).val() == '1') {
alert("You selected the first option and deselected the second one");
} else {
alert("You selected the second option and deselected the first one");
}
});
});
jsfiddle: http://jsfiddle.net/f8233x20/
Easiest and power full way
read only radio inputs using getAttribute
document.addEventListener('input',(e)=>{
if(e.target.getAttribute('name')=="myRadios")
console.log(e.target.value)
})
<input type="radio" name="myRadios" value="1" /> 1
<input type="radio" name="myRadios" value="2" /> 2
Store the previous checked radio in a variable:
http://jsfiddle.net/dsbonev/C5S4B/
HTML
<input type="radio" name="myRadios" value="1" /> 1
<input type="radio" name="myRadios" value="2" /> 2
<input type="radio" name="myRadios" value="3" /> 3
<input type="radio" name="myRadios" value="4" /> 4
<input type="radio" name="myRadios" value="5" /> 5
JS
var changeHandler = (function initChangeHandler() {
var previousCheckedRadio = null;
var result = function (event) {
var currentCheckedRadio = event.target;
var name = currentCheckedRadio.name;
if (name !== 'myRadios') return;
//using radio elements previousCheckedRadio and currentCheckedRadio
//storing radio element for using in future 'change' event handler
previousCheckedRadio = currentCheckedRadio;
};
return result;
})();
document.addEventListener('change', changeHandler, false);
JS EXAMPLE CODE
var changeHandler = (function initChangeHandler() {
var previousCheckedRadio = null;
function logInfo(info) {
if (!console || !console.log) return;
console.log(info);
}
function logPrevious(element) {
if (!element) return;
var message = element.value + ' was unchecked';
logInfo(message);
}
function logCurrent(element) {
if (!element) return;
var message = element.value + ' is checked';
logInfo(message);
}
var result = function (event) {
var currentCheckedRadio = event.target;
var name = currentCheckedRadio.name;
if (name !== 'myRadios') return;
logPrevious(previousCheckedRadio);
logCurrent(currentCheckedRadio);
previousCheckedRadio = currentCheckedRadio;
};
return result;
})();
document.addEventListener('change', changeHandler, false);
I don't think there is any way other then storing the previous state.
Here is the solution with jQuery
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
var lastSelected;
$(function () {
//if you have any radio selected by default
lastSelected = $('[name="myRadios"]:checked').val();
});
$(document).on('click', '[name="myRadios"]', function () {
if (lastSelected != $(this).val() && typeof lastSelected != "undefined") {
alert("radio box with value " + $('[name="myRadios"][value="' + lastSelected + '"]').val() + " was deselected");
}
lastSelected = $(this).val();
});
</script>
<input type="radio" name="myRadios" value="1" />
<input type="radio" name="myRadios" value="2" />
<input type="radio" name="myRadios" value="3" />
<input type="radio" name="myRadios" value="4" />
<input type="radio" name="myRadios" value="5" />
After thinking about it a bit more, I decided to get rid of the variable and add/remove class. Here is what I got: http://jsfiddle.net/BeQh3/2/
I realize this is an old issue, but this snippet of code works for me. Perhaps someone in the future will find it useful:
<h2>Testing radio functionality</h2>
<script type="text/javascript">var radioArray=[null];</script>
<input name="juju" value="button1" type="radio" onclick="radioChange('juju','button1',radioArray);" />Button 1
<input name="juju" value="button2" type="radio" onclick="radioChange('juju','button2',radioArray);" />Button 2
<input name="juju" value="button3" type="radio" onclick="radioChange('juju','button3',radioArray);" />Button 3
<br />
<script type="text/javascript">
function radioChange(radioSet,radioButton,radioArray)
{
//if(radioArray instanceof Array) {alert('Array Passed');}
var oldButton=radioArray[0];
if(radioArray[0] == null)
{
alert('Old button was not defined');
radioArray[0]=radioButton;
}
else
{
alert('Old button was set to ' + oldButton);
radioArray[0]=radioButton;
}
alert('New button is set to ' + radioArray[0]);
}
</script>
As you can see here:
http://www.w3schools.com/jsref/event_onchange.asp
The onchange attribute is not supported for radio buttons.
The first SO question linked by you gives you the answer: Use the onclick event instead and check the radio button state inside of the function it triggers.
Yes there is no change event for currently selected radio button. But problem is when each radio button is taken as a separate element. Instead a radio group should be considered a single element like select. So change event is triggered for that group. If it is a select element we never worry about each option in it, but take only the selected option. We store the current value in a variable which will become the previous value, when a new option is selected. Similarly you have to use a separate variable for storing value of checked radio button.
If you want to identify the previous radio button, you have to loop on mousedown event.
var radios = document.getElementsByName("myRadios");
var val;
for(var i = 0; i < radios.length; i++){
if(radios[i].checked){
val = radios[i].value;
}
}
see this : http://jsfiddle.net/diode/tywx6/2/
This is just off the top of my head, but you could do an onClick event for each radio button, give them all different IDs, and then make a for loop in the event to go through each radio button in the group and find which is was checked by looking at the 'checked' attribute. The id of the checked one would be stored as a variable, but you might want to use a temp variable first to make sure that the value of that variable changed, since the click event would fire whether or not a new radio button was checked.
<input type="radio" name="brd" onclick="javascript:brd();" value="IN">
<input type="radio" name="brd" onclick="javascript:brd();" value="EX">`
<script type="text/javascript">
function brd() {alert($('[name="brd"]:checked').val());}
</script>
If you want to avoid inline script, you can simply listen for a click event on the radio. This can be achieved with plain Javascript by listening to a click event on
for (var radioCounter = 0 ; radioCounter < document.getElementsByName('myRadios').length; radioCounter++) {
document.getElementsByName('myRadios')[radioCounter].onclick = function() {
//VALUE OF THE CLICKED RADIO ELEMENT
console.log('this : ',this.value);
}
}
this works for me
<input ID="TIPO_INST-0" Name="TIPO_INST" Type="Radio" value="UNAM" onchange="convenio_unam();">UNAM
<script type="text/javascript">
function convenio_unam(){
if(this.document.getElementById('TIPO_INST-0').checked){
$("#convenio_unam").hide();
}else{
$("#convenio_unam").show();
}
}
</script>
This is the easiest and most efficient function to use just add as many buttons as you want to the checked = false and make the onclick event of each radio buttoncall this function. Designate a unique number to each radio
button
function AdjustRadios(which)
{
if(which==1)
document.getElementById("rdpPrivate").checked=false;
else if(which==2)
document.getElementById("rdbPublic").checked=false;
}
For some reason, the best answer does not works for me.
I improved best answer by use
var overlayType_radio = document.querySelectorAll('input[type=radio][name="radio_overlaytype"]');
Original best answer use:
var rad = document.myForm.myRadios;
The others keep the same, finally it works for me.
var overlayType_radio = document.querySelectorAll('input[type=radio][name="radio_overlaytype"]');
console.log('overlayType_radio', overlayType_radio)
var prev = null;
for (var i = 0; i < overlayType_radio.length; i++) {
overlayType_radio[i].addEventListener('change', function() {
(prev) ? console.log('radio prev value',prev.value): null;
if (this !== prev) {
prev = this;
}
console.log('radio now value ', this.value)
});
}
html is:
<div id='overlay-div'>
<fieldset>
<legend> Overlay Type </legend>
<p>
<label>
<input class='with-gap' id='overlayType_image' value='overlayType_image' name='radio_overlaytype' type='radio' checked/>
<span>Image</span>
</label>
</p>
<p>
<label>
<input class='with-gap' id='overlayType_tiled_image' value='overlayType_tiled_image' name='radio_overlaytype' type='radio' disabled/>
<span> Tiled Image</span>
</p>
<p>
<label>
<input class='with-gap' id='overlayType_coordinated_tile' value='overlayType_coordinated_tile' name='radio_overlaytype' type='radio' disabled/>
<span> Coordinated Tile</span>
</p>
<p>
<label>
<input class='with-gap' id='overlayType_none' value='overlayType_none' name='radio_overlaytype' type='radio'/>
<span> None </span>
</p>
</fieldset>
</div>
var overlayType_radio = document.querySelectorAll('input[type=radio][name="radio_overlaytype"]');
console.log('overlayType_radio', overlayType_radio)
var prev = null;
for (var i = 0; i < overlayType_radio.length; i++) {
overlayType_radio[i].addEventListener('change', function() {
(prev) ? console.log('radio prev value',prev.value): null;
if (this !== prev) {
prev = this;
}
console.log('radio now value ', this.value)
});
}
<div id='overlay-div'>
<fieldset>
<legend> Overlay Type </legend>
<p>
<label>
<input class='with-gap' id='overlayType_image' value='overlayType_image' name='radio_overlaytype' type='radio' checked/>
<span>Image</span>
</label>
</p>
<p>
<label>
<input class='with-gap' id='overlayType_tiled_image' value='overlayType_tiled_image' name='radio_overlaytype' type='radio' />
<span> Tiled Image</span>
</p>
<p>
<label>
<input class='with-gap' id='overlayType_coordinated_tile' value='overlayType_coordinated_tile' name='radio_overlaytype' type='radio' />
<span> Coordinated Tile</span>
</p>
<p>
<label>
<input class='with-gap' id='overlayType_none' value='overlayType_none' name='radio_overlaytype' type='radio'/>
<span> None </span>
</p>
</fieldset>
</div>
jsfiddle click here
https://jsfiddle.net/hoogw/jetmkn02/1/
Tl;dr
'focusout' is dispatched before the 'change' event - example:
const radioName = 'radio';
// Add radios
document.body.innerHTML = `
<style>
input + label {
margin-left: 1rem;
}
</style>
<form action="#" name="example-form">
<fieldset>
${Array(5).fill(null, 0, 5).map((_, i) => {
const offsetId = i + 1;
const id = `radio-${offsetId}`;
return `<label for="${id}">Radio ${offsetId}</label>
<input type="radio" name="${radioName}" id="${id}" value="${offsetId}" />`;
}).join('\n')}
</fieldset>
</form>
`;
const {log} = console,
form = document.forms['example-form'];
form.addEventListener('submit', e => e.preventDefault());
form.addEventListener('change', e => {
const {target} = e;
if (target.matches(`[type="radio"][name="${radioName}"]`)) {
log(`[${e.type}]: "${target.id}" selected; Value: ${target.value}`);
}
});
form.addEventListener('focusout', e => {
const {target} = e,
soonToBePrevValue = target && target.form ?
target.form.elements[radioName].value : null;
if (!target.matches(`[type="radio"][name="${radioName}"]`) || !soonToBePrevValue) {
return;
}
// value, for '[name="radio"]', contained in form, will change after 'focusout' event
// has completed it's bubbling stage.
log(`[${e.type}]: previously selected radio value: ` +
`${soonToBePrevValue}`);
// log("Soon to be \"previous\" radio: ", target);
});
jsfiddle
<script>
function radioClick(radio){
alert()
}
</script>
<label>Cash on delivery</label>
<input type="radio" onclick="radioClick('A')" name="payment_method" class="form-group">
<br>
<label>Debit/Credit card, GPay, Paytm etc..</label>
<input type="radio" onclick="radioClick('B')" name="payment_method" class="form-group">

Can't change opacity with javascript function (html radio buttons) [duplicate]

I'm looking for a generalized solution for this.
Consider 2 radio type inputs with the same name. When submitted, the one that is checked determines the value that gets sent with the form:
<input type="radio" name="myRadios" onchange="handleChange1();" value="1" />
<input type="radio" name="myRadios" onchange="handleChange2();" value="2" />
The change event does not fire when a radio button is de-selected. So if the radio with value="1" is already selected and the user selects the second, handleChange1() does not run. This presents a problem (for me anyway) in that there is no event where I can catch this de-selection.
What I would like is a workaround for the onChange event for the checkbox group value or alternatively, an onCheck event that detects not only when a radio button is checked but also when it is unchecked.
I'm sure some of you have run into this problem before. What are some workarounds (or ideally what is the right way to handle this)? I just want to catch the change event, access the previously checked radio as well as the newly checked radio.
P.S.
onClick seems like a better (cross-browser) event to indicate when a radio button is checked but it still does not solve the unchecked problem.
I suppose it makes sense why onChange for a checkbox type does work in a case like this since it changes the value that it submits when you check or un-check it. I wish the radio buttons behaved more like a SELECT element's onChange but what can you do...
var rad = document.myForm.myRadios;
var prev = null;
for (var i = 0; i < rad.length; i++) {
rad[i].addEventListener('change', function() {
(prev) ? console.log(prev.value): null;
if (this !== prev) {
prev = this;
}
console.log(this.value)
});
}
<form name="myForm">
<input type="radio" name="myRadios" value="1" />
<input type="radio" name="myRadios" value="2" />
</form>
Here's a JSFiddle demo: https://jsfiddle.net/crp6em1z/
I would make two changes:
<input type="radio" name="myRadios" onclick="handleClick(this);" value="1" />
<input type="radio" name="myRadios" onclick="handleClick(this);" value="2" />
Use the onclick handler instead of onchange - you're changing the "checked state" of the radio input, not the value, so there's not a change event happening.
Use a single function, and pass this as a parameter, that will make it easy to check which value is currently selected.
ETA: Along with your handleClick() function, you can track the original / old value of the radio in a page-scoped variable. That is:
var currentValue = 0;
function handleClick(myRadio) {
alert('Old value: ' + currentValue);
alert('New value: ' + myRadio.value);
currentValue = myRadio.value;
}
var currentValue = 0;
function handleClick(myRadio) {
alert('Old value: ' + currentValue);
alert('New value: ' + myRadio.value);
currentValue = myRadio.value;
}
<input type="radio" name="myRadios" onclick="handleClick(this);" value="1" />
<input type="radio" name="myRadios" onclick="handleClick(this);" value="2" />
As you can see from this example: http://jsfiddle.net/UTwGS/
HTML:
<label><input type="radio" value="1" name="my-radio">Radio One</label>
<label><input type="radio" value="2" name="my-radio">Radio One</label>
jQuery:
$('input[type="radio"]').on('click change', function(e) {
console.log(e.type);
});
both the click and change events are fired when selecting a radio button option (at least in some browsers).
I should also point out that in my example the click event is still fired when you use tab and the keyboard to select an option.
So, my point is that even though the change event is fired is some browsers, the click event should supply the coverage you need.
You can add the following JS script
<script>
function myfunction(event) {
alert('Checked radio with ID = ' + event.target.id);
}
document.querySelectorAll("input[name='myRadios']").forEach((input) => {
input.addEventListener('change', myfunction);
});
</script>
What about using the change event of Jquery?
$(function() {
$('input:radio[name="myRadios"]').change(function() {
if ($(this).val() == '1') {
alert("You selected the first option and deselected the second one");
} else {
alert("You selected the second option and deselected the first one");
}
});
});
jsfiddle: http://jsfiddle.net/f8233x20/
Easiest and power full way
read only radio inputs using getAttribute
document.addEventListener('input',(e)=>{
if(e.target.getAttribute('name')=="myRadios")
console.log(e.target.value)
})
<input type="radio" name="myRadios" value="1" /> 1
<input type="radio" name="myRadios" value="2" /> 2
Store the previous checked radio in a variable:
http://jsfiddle.net/dsbonev/C5S4B/
HTML
<input type="radio" name="myRadios" value="1" /> 1
<input type="radio" name="myRadios" value="2" /> 2
<input type="radio" name="myRadios" value="3" /> 3
<input type="radio" name="myRadios" value="4" /> 4
<input type="radio" name="myRadios" value="5" /> 5
JS
var changeHandler = (function initChangeHandler() {
var previousCheckedRadio = null;
var result = function (event) {
var currentCheckedRadio = event.target;
var name = currentCheckedRadio.name;
if (name !== 'myRadios') return;
//using radio elements previousCheckedRadio and currentCheckedRadio
//storing radio element for using in future 'change' event handler
previousCheckedRadio = currentCheckedRadio;
};
return result;
})();
document.addEventListener('change', changeHandler, false);
JS EXAMPLE CODE
var changeHandler = (function initChangeHandler() {
var previousCheckedRadio = null;
function logInfo(info) {
if (!console || !console.log) return;
console.log(info);
}
function logPrevious(element) {
if (!element) return;
var message = element.value + ' was unchecked';
logInfo(message);
}
function logCurrent(element) {
if (!element) return;
var message = element.value + ' is checked';
logInfo(message);
}
var result = function (event) {
var currentCheckedRadio = event.target;
var name = currentCheckedRadio.name;
if (name !== 'myRadios') return;
logPrevious(previousCheckedRadio);
logCurrent(currentCheckedRadio);
previousCheckedRadio = currentCheckedRadio;
};
return result;
})();
document.addEventListener('change', changeHandler, false);
I don't think there is any way other then storing the previous state.
Here is the solution with jQuery
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
var lastSelected;
$(function () {
//if you have any radio selected by default
lastSelected = $('[name="myRadios"]:checked').val();
});
$(document).on('click', '[name="myRadios"]', function () {
if (lastSelected != $(this).val() && typeof lastSelected != "undefined") {
alert("radio box with value " + $('[name="myRadios"][value="' + lastSelected + '"]').val() + " was deselected");
}
lastSelected = $(this).val();
});
</script>
<input type="radio" name="myRadios" value="1" />
<input type="radio" name="myRadios" value="2" />
<input type="radio" name="myRadios" value="3" />
<input type="radio" name="myRadios" value="4" />
<input type="radio" name="myRadios" value="5" />
After thinking about it a bit more, I decided to get rid of the variable and add/remove class. Here is what I got: http://jsfiddle.net/BeQh3/2/
I realize this is an old issue, but this snippet of code works for me. Perhaps someone in the future will find it useful:
<h2>Testing radio functionality</h2>
<script type="text/javascript">var radioArray=[null];</script>
<input name="juju" value="button1" type="radio" onclick="radioChange('juju','button1',radioArray);" />Button 1
<input name="juju" value="button2" type="radio" onclick="radioChange('juju','button2',radioArray);" />Button 2
<input name="juju" value="button3" type="radio" onclick="radioChange('juju','button3',radioArray);" />Button 3
<br />
<script type="text/javascript">
function radioChange(radioSet,radioButton,radioArray)
{
//if(radioArray instanceof Array) {alert('Array Passed');}
var oldButton=radioArray[0];
if(radioArray[0] == null)
{
alert('Old button was not defined');
radioArray[0]=radioButton;
}
else
{
alert('Old button was set to ' + oldButton);
radioArray[0]=radioButton;
}
alert('New button is set to ' + radioArray[0]);
}
</script>
As you can see here:
http://www.w3schools.com/jsref/event_onchange.asp
The onchange attribute is not supported for radio buttons.
The first SO question linked by you gives you the answer: Use the onclick event instead and check the radio button state inside of the function it triggers.
Yes there is no change event for currently selected radio button. But problem is when each radio button is taken as a separate element. Instead a radio group should be considered a single element like select. So change event is triggered for that group. If it is a select element we never worry about each option in it, but take only the selected option. We store the current value in a variable which will become the previous value, when a new option is selected. Similarly you have to use a separate variable for storing value of checked radio button.
If you want to identify the previous radio button, you have to loop on mousedown event.
var radios = document.getElementsByName("myRadios");
var val;
for(var i = 0; i < radios.length; i++){
if(radios[i].checked){
val = radios[i].value;
}
}
see this : http://jsfiddle.net/diode/tywx6/2/
This is just off the top of my head, but you could do an onClick event for each radio button, give them all different IDs, and then make a for loop in the event to go through each radio button in the group and find which is was checked by looking at the 'checked' attribute. The id of the checked one would be stored as a variable, but you might want to use a temp variable first to make sure that the value of that variable changed, since the click event would fire whether or not a new radio button was checked.
<input type="radio" name="brd" onclick="javascript:brd();" value="IN">
<input type="radio" name="brd" onclick="javascript:brd();" value="EX">`
<script type="text/javascript">
function brd() {alert($('[name="brd"]:checked').val());}
</script>
If you want to avoid inline script, you can simply listen for a click event on the radio. This can be achieved with plain Javascript by listening to a click event on
for (var radioCounter = 0 ; radioCounter < document.getElementsByName('myRadios').length; radioCounter++) {
document.getElementsByName('myRadios')[radioCounter].onclick = function() {
//VALUE OF THE CLICKED RADIO ELEMENT
console.log('this : ',this.value);
}
}
this works for me
<input ID="TIPO_INST-0" Name="TIPO_INST" Type="Radio" value="UNAM" onchange="convenio_unam();">UNAM
<script type="text/javascript">
function convenio_unam(){
if(this.document.getElementById('TIPO_INST-0').checked){
$("#convenio_unam").hide();
}else{
$("#convenio_unam").show();
}
}
</script>
This is the easiest and most efficient function to use just add as many buttons as you want to the checked = false and make the onclick event of each radio buttoncall this function. Designate a unique number to each radio
button
function AdjustRadios(which)
{
if(which==1)
document.getElementById("rdpPrivate").checked=false;
else if(which==2)
document.getElementById("rdbPublic").checked=false;
}
For some reason, the best answer does not works for me.
I improved best answer by use
var overlayType_radio = document.querySelectorAll('input[type=radio][name="radio_overlaytype"]');
Original best answer use:
var rad = document.myForm.myRadios;
The others keep the same, finally it works for me.
var overlayType_radio = document.querySelectorAll('input[type=radio][name="radio_overlaytype"]');
console.log('overlayType_radio', overlayType_radio)
var prev = null;
for (var i = 0; i < overlayType_radio.length; i++) {
overlayType_radio[i].addEventListener('change', function() {
(prev) ? console.log('radio prev value',prev.value): null;
if (this !== prev) {
prev = this;
}
console.log('radio now value ', this.value)
});
}
html is:
<div id='overlay-div'>
<fieldset>
<legend> Overlay Type </legend>
<p>
<label>
<input class='with-gap' id='overlayType_image' value='overlayType_image' name='radio_overlaytype' type='radio' checked/>
<span>Image</span>
</label>
</p>
<p>
<label>
<input class='with-gap' id='overlayType_tiled_image' value='overlayType_tiled_image' name='radio_overlaytype' type='radio' disabled/>
<span> Tiled Image</span>
</p>
<p>
<label>
<input class='with-gap' id='overlayType_coordinated_tile' value='overlayType_coordinated_tile' name='radio_overlaytype' type='radio' disabled/>
<span> Coordinated Tile</span>
</p>
<p>
<label>
<input class='with-gap' id='overlayType_none' value='overlayType_none' name='radio_overlaytype' type='radio'/>
<span> None </span>
</p>
</fieldset>
</div>
var overlayType_radio = document.querySelectorAll('input[type=radio][name="radio_overlaytype"]');
console.log('overlayType_radio', overlayType_radio)
var prev = null;
for (var i = 0; i < overlayType_radio.length; i++) {
overlayType_radio[i].addEventListener('change', function() {
(prev) ? console.log('radio prev value',prev.value): null;
if (this !== prev) {
prev = this;
}
console.log('radio now value ', this.value)
});
}
<div id='overlay-div'>
<fieldset>
<legend> Overlay Type </legend>
<p>
<label>
<input class='with-gap' id='overlayType_image' value='overlayType_image' name='radio_overlaytype' type='radio' checked/>
<span>Image</span>
</label>
</p>
<p>
<label>
<input class='with-gap' id='overlayType_tiled_image' value='overlayType_tiled_image' name='radio_overlaytype' type='radio' />
<span> Tiled Image</span>
</p>
<p>
<label>
<input class='with-gap' id='overlayType_coordinated_tile' value='overlayType_coordinated_tile' name='radio_overlaytype' type='radio' />
<span> Coordinated Tile</span>
</p>
<p>
<label>
<input class='with-gap' id='overlayType_none' value='overlayType_none' name='radio_overlaytype' type='radio'/>
<span> None </span>
</p>
</fieldset>
</div>
jsfiddle click here
https://jsfiddle.net/hoogw/jetmkn02/1/
Tl;dr
'focusout' is dispatched before the 'change' event - example:
const radioName = 'radio';
// Add radios
document.body.innerHTML = `
<style>
input + label {
margin-left: 1rem;
}
</style>
<form action="#" name="example-form">
<fieldset>
${Array(5).fill(null, 0, 5).map((_, i) => {
const offsetId = i + 1;
const id = `radio-${offsetId}`;
return `<label for="${id}">Radio ${offsetId}</label>
<input type="radio" name="${radioName}" id="${id}" value="${offsetId}" />`;
}).join('\n')}
</fieldset>
</form>
`;
const {log} = console,
form = document.forms['example-form'];
form.addEventListener('submit', e => e.preventDefault());
form.addEventListener('change', e => {
const {target} = e;
if (target.matches(`[type="radio"][name="${radioName}"]`)) {
log(`[${e.type}]: "${target.id}" selected; Value: ${target.value}`);
}
});
form.addEventListener('focusout', e => {
const {target} = e,
soonToBePrevValue = target && target.form ?
target.form.elements[radioName].value : null;
if (!target.matches(`[type="radio"][name="${radioName}"]`) || !soonToBePrevValue) {
return;
}
// value, for '[name="radio"]', contained in form, will change after 'focusout' event
// has completed it's bubbling stage.
log(`[${e.type}]: previously selected radio value: ` +
`${soonToBePrevValue}`);
// log("Soon to be \"previous\" radio: ", target);
});
jsfiddle
<script>
function radioClick(radio){
alert()
}
</script>
<label>Cash on delivery</label>
<input type="radio" onclick="radioClick('A')" name="payment_method" class="form-group">
<br>
<label>Debit/Credit card, GPay, Paytm etc..</label>
<input type="radio" onclick="radioClick('B')" name="payment_method" class="form-group">

Efficient way to enabled or disabled multiple checkboxes with JavaScript than listing all of them?

I was wondering if there was a better way to go about enabled/disabled multiple checkboxes at once.
In the html I have two radio buttons to choose between all hair options and custom hair options, having the default all one disable the checkboxes while the custom one enables them.
This is what I've got so far that works (probably looks dumb, I apologize), but I'd like to know if there's a more efficient way to go about this? I'd like to do it as "small" as possible while still being easily readable/understandable for my own sake.
function checkHaOp(){
if (document.getElementById("hairOptionAll").checked){
document.getElementById("hairAuburn").disabled = true;
document.getElementById("hairBlack").disabled = true;
document.getElementById("hairBlonde").disabled = true;
document.getElementById("hairBrown").disabled = true;
document.getElementById("hairRed").disabled = true;
document.getElementById("hairOther").disabled = true;
}
else if (document.getElementById("hairOptionCustom").checked){
document.getElementById("hairAuburn").disabled = false;
document.getElementById("hairBlack").disabled = false;
document.getElementById("hairBlonde").disabled = false;
document.getElementById("hairBrown").disabled = false;
document.getElementById("hairRed").disabled = false;
document.getElementById("hairOther").disabled = false;
}
}
Preferably using javascript since I don't know jquery.
I'd also appreciate explanations of things since I am still learning.
You can add/use class like said #NiettheDarkAbsol
then something like that.
var inpck = document.getElementsByClassName("input-checkbox");
if (document.getElementById("hairOptionAll").checked) {
for(var i = 0; i < inpck.length; i++) {
inpck[i].disabled = true;
}
}
if (document.getElementById("hairOptionCustom").checked) {
for(var i = 0; i < inpck.length; i++) {
inpck[i].disabled = false;
}
}
Now your turn to refactor this :D
You can use
document.querySelectorAll('[id^=hair]')
It selects all elements that has an id which starts with "hair"
<!DOCTYPE html>
<html>
<body>
<input type="checkbox" id="hairOptionAll">
<input type="checkbox" id="hairAuburn">
<input type="checkbox" id="hairBlack">
<input type="checkbox" id="hairBlonde">
<input type="checkbox" id="hairBrown">
<input type="checkbox" id="hairRed">
<input type="checkbox" id="hairOther">
</body>
<script>
const hairCb = document.querySelectorAll('[id^=hair]');
for (let i=0; i<hairCb.length; i++) {
hairCb[i].disabled = true;
}
</script>
</html>
Here's the optimized solution.
<div class="radio-btns">
All <input type="radio" id="hairOptionAll" name="hairOptionAll"/>
Custom <input type="radio" id="hairOptionCustom" name="hairOptionCustom"/>
</div>
<div class="hairOptions">
hairAuburn <input type="checkbox" id="hairAuburn" />
hairBlack <input type="checkbox" id="hairBlack" />
hairBlonde <input type="checkbox" id="hairBlonde" />
hairBrown <input type="checkbox" id="hairBrown" />
hairRed <input type="checkbox" id="hairRed" />
hairOther <input type="checkbox" id="hairOther" />
</div>
<script type="text/javascript">
const radioBtns = document.querySelector('.radio-btns');
radioBtns.children[0].checked = true;
radioBtns.addEventListener("click", (event) => {
radioBtns.children[0].checked = (event.target.id == 'hairOptionAll') ? true : false;
radioBtns.children[1].checked = (event.target.id == 'hairOptionCustom') ? true : false;
const allOptions = [...event.target.parentElement.nextElementSibling.children];
allOptions.map(option => ( option.checked = (event.target.id == 'hairOptionCustom') ? true : false ) );
});
</script>
Here is a complete working code you. To minimise the code we write to we need to use a class selector not an id - Give the same class to your radio button and then use a forEach loop to go through all the radio button. Add the class to your checkboxes as well.
To get all the checkboxes we can use forEach method.
Once you have all the radio button you need to listen for a change on a particular radio button and then we will check whether the radio button we have selected is checked and its id is all or custom.
To get the id of the actual radio button which was clicked we can use getAttribute method which return the id of checked radio button.
If our condition matches we will disable all the checkboxes or if its else then we enable all the checkboxes using forEach loop on the checkbox classes.
We will pass true or false as an argument to disable checkboxes function to avoid having have two loops
Live Working Example (I have added notes / comment on each line of code for your understanding as well)
//Enable disable checkbox
function disableChekbox(isChecked) {
let getHairOptions = document.querySelectorAll('.hairOptions') //get all checkboxes
getHairOptions.forEach(function(x) {
x.disabled = isChecked
})
}
let getHairRadio = document.querySelectorAll('.hairOptionAll') //get all radio buttons
//For each all radio buttons
getHairRadio.forEach(function(radio) {
//listen to change on radio
radio.addEventListener('change', function(e) {
if (e.target.checked && e.target.getAttribute('id') == 'hairOptionAll') {
//loop through all checkboxes
disableChekbox(true)
} else if (e.target.checked && e.target.getAttribute('id') == 'hairOptionCustom') {
//loop through all checkboxes
disableChekbox(false)
}
})
})
All <input type="radio" id="hairOptionAll" name="hairOptionAll" class="hairOptionAll" />
Custom <input type="radio" id="hairOptionCustom" name="hairOptionAll" class="hairOptionAll" />
<br>
<br>
hairAuburn <input type="checkbox" id="hairAuburn" class="hairOptions" />
hairBlack <input type="checkbox" id="hairBlack" class="hairOptions" />
hairBlonde <input type="checkbox" id="hairBlonde" class="hairOptions" />
hairBrown <input type="checkbox" id="hairBrown" class="hairOptions" />
hairRed <input type="checkbox" id="hairRed" class="hairOptions" />
hairOther <input type="checkbox" id="hairOther" class="hairOptions" />

Repeative values occur in Autocomplete jquery

I am working in ASP.NET Project.My task is to Prevent the repative values occured in Textbox.Textbox is bound with autocomplete and appending text from checkboxlist as like in the below picture
! https://drive.google.com/file/d/0B5OPwgmPG6QpTHBTdVlFaldRaEE/view?usp=sharing
After i appended the content from checkbox list to textbox means it is repeating value,if i typed it inital time it won't.And my task is to show unique values based on the textbox content.
My project files are in the below link..please help me out guys
https://drive.google.com/file/d/0B5OPwgmPG6QpS3NMNElGN2k4RzQ/view?usp=sharing
Based on my answer I gave you in the other thread (https://stackoverflow.com/a/28828842/4569271) I extended my solution to only display unique values:
$(function() {
$('input[type="checkbox"]').change(function() {
// Reset output:
$("#output").html('');
// remeber all unique values in this array:
var tmpArray = new Array();
// Repeat for all checked checkboxes:
var checkboxes = $('input[type="checkbox"]:checked').each(function() {
// Get value from checkbox:
var textToAppend = $(this).val();
// Check if value from checkbox was added already:
if (jQuery.inArray(textToAppend, tmpArray) == -1) {
// add entry to array so it will be not added again:
tmpArray.push(textToAppend);
var existingText = $("#output").html();
// Append seperator (';') if neccessary:
if (existingText != '') {
existingText = existingText + ";";
}
// Print out append value:
$("#output").html(existingText + textToAppend);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Select:</h2>
<input type="checkbox" value="Jan" />Jan
<input type="checkbox" value="Jan" />Jan
<input type="checkbox" value="Jan" />Jan
<input type="checkbox" value="Feb" />Feb
<input type="checkbox" value="Feb" />Feb
<input type="checkbox" value="Feb" />Feb
<input type="checkbox" value="Mar" />Mar
<input type="checkbox" value="Mar" />Mar
<input type="checkbox" value="Mar" />Mar
<h2>Output:</h2>
<div id="output"></div>
Based on your description, I am not sure if this is the solution you were looking for? But maybe it helps.

How to create javascript array based on user input using jQuery

I've dynamically loading check box fields, how can I send those to server based on user selection.
For example I've following doc,
<label>Set1</label>
<input type="checkbox" name="set_199[]" value="Apple" />
<input type="checkbox" name="set_199[]" value="Mango" />
<input type="checkbox" name="set_199[]" value="Grape" />
<label>Set2</label>
<input type="checkbox" name="set_200[]" value="Red" />
<input type="checkbox" name="set_200[]" value="Blue" />
<input type="checkbox" name="set_200[]" value="Orange" />
Suppose if user selected first two values for each of them, then I need to send like
response[0][0]=199; // Id
response[0][1]=['Apple','Mango']; //values
response[1][0]=200
response[1][1]=['Red','Blue'];
I've tried some approaches suggested in existing posts but failed to implement how I want.
You can make some minor changes in the html then use .map()
<label class="set" data-id="199">Set1</label>
<input type="checkbox" name="set_199[]" value="Apple" />
<input type="checkbox" name="set_199[]" value="Mango" />
<input type="checkbox" name="set_199[]" value="Grape" />
<label class="set" data-id="200">Set2</label>
<input type="checkbox" name="set_200[]" value="Red" />
<input type="checkbox" name="set_200[]" value="Blue" />
<input type="checkbox" name="set_200[]" value="Orange" />
then
var array = $('.set').map(function () {
var $this = $(this),
id = $this.data('id'),
array = [id];
array.push($('input[name="set_' + id + '\\[\\]"]').filter(':checked').map(function () {
return this.value;
}).get())
return [array]
}).get()
Demo: Fiddle
Yet another solution:
<lable>Set1</lable>
<input type="checkbox" name="set_199[]" value="Apple" />
<input type="checkbox" name="set_199[]" value="Mango" />
<input type="checkbox" name="set_199[]" value="Grape" />
<input type="button" value="check" class="js-submit">
Js:
$(".js-submit").on("click", function(){
var a = $("input[type='checkbox']:checked");
var values = {};
a.each(function(){
var value = $(this).val();
var name = $(this).attr("name");
if(!values[name]) values[name] = [];
values[name].push(value)
});
console.log(values)
});
Demo
To expand on my comment a little, here's how I'd do this... given that you're sending this as an ajax request, I'd still wrap these elements in a form element, and use that as a starting-point to build the object we'll be sending...
var myForm = document.getElementById('formID').elements,//get all input nodes
data = {},temp;
for (var i=0;i<myForm.length;++i)
{
temp = myForm.item(i).name.replace(/[[]]/g,'');//replace square brackets
if (!data[temp])
data[temp] = [];//create array if key does not exist
if (myForm.item(i).checked)//for checkboxes
data[temp].push(myForm.item(i).value);
}
That's the basic setup. If you want, you can add checks and further tailor this, so you can deal with various types of input fields, but in essence, it'll boil down to this.
You might also want to use Array.prototype.forEach on the myForm.elements NodeList, and use a callback to keep your code nice and clean.
Here's an example of a slightly more usable version of the same code:
btn.addEventListener('click', function()
{
var data = {};
Array.prototype.forEach.call(frm.elements, function(item)
{
var temp;
if (item === btn) return;//don't includ the button element
if (item.type === 'checkbox' && !item.checked ) return;//not checked, ignore
if (item.name.match(/[[]]/))
{
temp = item.name.replace(/[[]]/g, '');
if (!data[temp]) data[temp] = [];//if property does not exist, make an array
data[temp].push(item.value);
return;
}
//normal elements:
data[item.name] = item.value;
});
//ajax request using data variable goes here!
console.log(data);
},false);
And here's the fiddle of it
First of all thanks for all who have given answers to this question. I've derived my own solution for this issue but it is not possible without your help, especially this
var checkBoxArray = {};
$.each($("input[name^='set_'][type='checkbox']:checked"), function(i, item) {
var Id = item.name.replace(/^(set_)|[\[\]]/g, "");
var value = $(item).val();
if(!checkBoxArray[Id])
checkBoxArray[Id] = [];
checkBoxArray[Id].push(value)
});
$.map(checkBoxArray, function(value, index) {
reponse.push([index, value]);
});
Its worked for me, suggest if anything not proper in above code snippet.

Categories