Javascript how to change radio button label text? - javascript

I want to change the text of the label which is associated with the radiobutton id="male". I have tried various ways to do it, but i can't make it work. I want to change the text "Male" in the label associated to the radio button.
<input type="radio" name="sex" id="male" value="male">
<label for="male">Male</label>
</input>
<input type="button" value="Submit" onclick = test()>
<script>
function test()
{
var r = document.getElementById("male");
r.nextSibling.data = "adaS";
// r.nextSibling.nodeValue = "adaS"; // have tried all these ways
// r.childNodes[0].value= "adaS";
// r.childNodes[0].innerHTML= "adaS";
// r.parentNode.childNodes[1].innerHTML= "adaS";
}
</script>
please suggest some working way to change the text "Male" in the label.

You can use
var r = document.getElementsByTagName("label")
to select all the label element in your page and then use
r[0].innerHTML ="new text"
to select first label and set the text to "next text" in your test() function

I tried to use ideas from the above to get a working example, and had some problems. So I asked for help in another posting and #KrishCdbry very kindly fixed the problem. The posted question is at javascript - How to dynamically change information displayed by radio button? Below is the working example with Krish's changes
<html>
<form name="myform" onsubmit="OnSubmitForm();">
<input type="radio" id = 'first' name="operation" value="1"
checked> <label for="alsoFirst"> Answer 1 </label>
<input type="radio" id = 'second' name="operation" value="2">
<label for="alsoSecond">Answer 2</label>
<p>
<input type="submit" name="submit" value="save">
</p>
</form>
<script type="text/javascript">
document.addEventListener('readystatechange', function() {
// Seems like a GOOD PRACTICE - keeps me from getting type error I was getting
// https://stackoverflow.com/questions/14207922/javascript-error-null-is-not-an-object
if (document.readyState === "complete") {
init();
}
});
function init() {
console.log ("expect to change -Answer 1- displayed by first button to word junk");
// this works
var label = document.getElementsByTagName('label') [0];
// this does not work
label.innerHTML = 'junk';
}
//http://www.javascript-coder.com/html-form/html-form-action.phtml
function OnSubmitForm()
{
if(document.getElementById('first').checked == true)
{
alert ( "You have selected the first answer" );
}
else
if(document.getElementById('second').checked == true)
{
alert ( "You have selected the SECOND answer" );
}
return false;
}
/*
<input type="radio" name="sex" id="male" value="male">
<label for="male">Male</label>
</input>
var input = document.getElementById('male');
var label = input.getElementsByTagName('label')[0];
label.innerHTML = 'New Text';
*/
//https://stackoverflow.com/questions/32292962/javascript-how-to-change-radio-button-label-text
</script>
</html>

With jQuery, $('label[for=male]').html('New Label');
Plain JS:
var input = document.getElementById('male');
var label = input.getElementsByTagName('label')[0];
label.innerHTML = 'New Text';
Can also chain that together:
var label = document.getElementById('male').getElementsByTagName('label')[0];
label.innerHTML = 'New Text;

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">

javascript - How to dynamically change information displayed by radio button?

(Duplicate?) I've tried several Stackoverflow postings related to this, but I cannot get a javaScript example to work. I'd like to avoid having to use jQuery, for the time being.
I want to create the information shown by radio buttons dynamically, using javascript. In this example, I would want to write a function that displays some other values for these radio buttons 'Answer 1' and 'Answer 2'. For example, I don't actually want 'Answer 1'. Goal is for the user to click on one of the multiple choice answers, then hit submit/save to self-check their own knowledge.
I have already learned, through my more complex project code, that a submit/save button that is hard-coded into the html <form> section does not seem to associate with values displayed by the radio buttons, that I managed to add in using javaScript * It seems to me that changing hardcoded information already displayed by the radio buttons might work.
When user clicks on the submit/'save' button, I don't need to refer to the actual answer information that the radio button is displaying. I only need to know whether , in this case, it's the first or second answer chosen.
<html>
<script type="text/javascript">
function OnSubmitForm()
{
if(document.myform.operation[0].checked == true)
{
alert ( "You have selected the first answer" );
}
else
if(document.myform.operation[1].checked == true)
{
alert ( "You have selected the SECOND answer" );
}
}
</script>
<form name="myform" onsubmit="return OnSubmitForm();">
<input type="radio" name="operation" value="1" checked>Answer 1
<input type="radio" name="operation" value="2">Answer 2
<p>
<input type="submit" name="submit" value="save">
</p>
</form>
</html>
(I don't know if I should include this following example I tried as well)
BTW Here is another of the example I tried - a posting but I cannot get this idea to work . I was trying to get the first radio button to display 'junk' instead of 'Answer1' as originally hard coded. But I have an error from code borrowed from posting, that I cannot resolve.
It's from
Javascript how to change radio button label text?
<html>
<form name="myform" onsubmit="return OnSubmitForm();">
<input type="radio" id = 'first' name="operation" value="1" checked <label for="alsoFirst"> Answer 1
<input type="radio" id = 'second' name="operation" value="2"<label for="alsoSecond">Answer 2
<p>
<input type="submit" name="submit" value="save">
</p>
</form>
<script type="text/javascript">
document.addEventListener('readystatechange', function() {
// Seems like a GOOD PRACTICE - keeps me from getting type error I was getting
// https://stackoverflow.com/questions/14207922/javascript-error-null-is-not-an-object
if (document.readyState === "complete") {
init();
}
});
function init() {
console.log ("expect to change -Answer 1- displayed by first button to word junk");
// this works
var label = document.getElementById('first').getElementsByTagName('alsoFirst') [0];
// this does not work
label.innerHTML = 'junk';
}
//http://www.javascript-coder.com/html-form/html-form-action.phtml
function OnSubmitForm()
{
if(document.myform.operation[0].checked == true)
{
alert ( "You have selected the first answer" );
}
else
if(document.myform.operation[1].checked == true)
{
alert ( "You have selected the SECOND answer" );
}
if (document.uniqueName.checked == true){
alert ( "You have selected the THIRD answer" );
}
}
/*
<input type="radio" name="sex" id="male" value="male">
<label for="male">Male</label>
</input>
var input = document.getElementById('male');
var label = input.getElementsByTagName('label')[0];
label.innerHTML = 'New Text';
*/
//https://stackoverflow.com/questions/32292962/javascript-how-to-change-radio-button-label-text
</script>
</html>
I previously got values from my arrays to display by inserting table rows and concatenating strings. This worked, and went into the table, but did not tie into the submit/save button hardcoded into original <form>. I still plan to have radio answer buttons in a table, but I'm trying to make a more basic example here.
I Have made some modifications for getting label through document.getElementByTagName() and also some changes to OnSubmitForm() function. And just pasted your code with those changes below and demo link at the end.
<html>
<form name="myform" onsubmit="OnSubmitForm();">
<input type="radio" id = 'first' name="operation" value="1"
checked> <label for="alsoFirst"> Answer 1 </label>
<input type="radio" id = 'second' name="operation" value="2">
<label for="alsoSecond">Answer 2</label>
<p>
<input type="submit" name="submit" value="save">
</p>
</form>
<script type="text/javascript">
document.addEventListener('readystatechange', function() {
// Seems like a GOOD PRACTICE - keeps me from getting type error I was getting
// http://stackoverflow.com/questions/14207922/javascript-error-null-is-not-an-object
if (document.readyState === "complete") {
init();
}
});
function init() {
console.log ("expect to change -Answer 1- displayed by first button to word junk");
// this works
var label = document.getElementsByTagName('label') [0];
// this does not work
label.innerHTML = 'junk';
}
//http://www.javascript-coder.com/html-form/html-form-action.phtml
function OnSubmitForm()
{
if(document.getElementById('first').checked == true)
{
alert ( "You have selected the first answer" );
}
else
if(document.getElementById('second').checked == true)
{
alert ( "You have selected the SECOND answer" );
}
return false;
}
/*
<input type="radio" name="sex" id="male" value="male">
<label for="male">Male</label>
</input>
var input = document.getElementById('male');
var label = input.getElementsByTagName('label')[0];
label.innerHTML = 'New Text';
*/
//http://stackoverflow.com/questions/32292962/javascript-how-to-change-radio-button-label-text
</script>
</html>
Demo : https://jsbin.com/sojojiy/27/edit?html,console,output
Hope this helps. Thanks !

How to show jquery dialog with radio buttons when checkbox is checked and post value in textbox

I have 41 checkboxes like this
HTML
<input id="1" type="checkbox" onclick="updatebox()" />
<input id="2" type="checkbox" onclick="updatebox()" />
<input id="3" type="checkbox" onclick="updatebox()" />
<input id="4" type="checkbox" onclick="updatebox()" />
Javascript
<script type="text/javascript">
function updatebox()
{
var textbox = document.getElementById("list");
var values = [];
if(document.getElementById('1').checked) {values.push("1");}
if(document.getElementById('2').checked) {values.push("2");}
if(document.getElementById('3').checked) {values.push("3");}
if(document.getElementById('4').checked) {values.push("4");}
textbox.value = values.join(", ");
}
</script>
When checkbox is checked the value is posted in textbox,
now what i want is when the user clicks the checkbox the jquery dialog popups and the user will have two radio buttons with Male or Female options along with ok button so when the user will click on ok the value should be posted on textbox depending on selection M for male F for female along with number like 1M or 1F, 2M or 2F and so on.
P.S user can select multiple checkboxes.
Thanks You!
Here is something that does what you want. HTML:
<body>
<form id="form">
<input id="1" type="checkbox" /> 1
<input id="2" type="checkbox" /> 2
<input id="3" type="checkbox" /> 3
<input id="4" type="checkbox" /> 4
...
<input id="10" type="checkbox" /> 10
...
<input id="41" type="checkbox" /> 41
<input id="list" />
</form>
<div id="prompt" style="display:none;" title="Gender">
<form>
<input type="radio" name="gender" id="radio" value="male" />
<label for="radio">Male</label>
<input type="radio" name="gender" id="radio2" value="female" />
<label for="radio2">Female</label>
</form>
</div>
</body>
The JavaScript:
$(function() {
var form = document.getElementById("form");
var textbox = document.getElementById("list");
var $prompt = $("#prompt");
// We record what is currently checked, and the user's answers in this `pairs` object.
var pairs = [];
// Listen to `change` events.
$("input[type='checkbox']", form).on('change', function (ev) {
var check = ev.target;
if (check.checked) {
// Checked, so prompt and record.
$prompt.dialog({
modal: true,
buttons: {
"Ok": function() {
var gender = $prompt.find("input[name='gender']:checked")[0];
var letter = {"male":"M", "female":"F"}[gender.value];
pairs[check.id] = '' + check.id + letter;
$( this ).dialog( "close" );
refresh();
}
}
});
}
else {
// Unchecked, so forget it.
delete pairs[check.id];
refresh();
}
function refresh() {
// Generate what we must now display in the textbox and refresh it.
// We walk the list.
var keys = Object.keys(pairs);
var values = [];
for (var i = 0, key; (key = keys[i]); ++i) {
values.push(pairs[key]);
}
textbox.value = values.join(", ");
}
});
});
Here is a jsbin with the code above.
Salient points:
This code adds the event handlers using JavaScript rather than use onclick in the HTML. It is not recommended to associated handlers directly in the HTML.
It listens to the change event rather than click. Some clicks can sometimes not result in a change to an input element.
It uses $.dialog to prompt the user for M, F.
The refresh function is what recomputes the text field.
It keeps a record of what is currently checked rather than requery for all the check boxes when one of them changes.
function updatebox()
{
var textbox = document.getElementById("list");
var values = [];
for (var i = 1; i <= 41; ++i) {
var id = '' + i;
if (document.getElementById(id).checked) {
var gender = prompt('Male (M) or female (F)?');
values.push(gender + id);
}
}
textbox.value = values.join(", ");
}
A few things to note:
I got rid of all that code repetition by simply using a for loop from 1 to 41.
I also fixed the strange indentation you had there.
You may want to use a method of getting user input other than prompt, but it'll work the same way.
(If you're going to keep using prompt, you might also want to add input validation as well to make sure the user didn't input something other than M or F.)

JavaScript read radio button value in IE and FireFox

I have a simple web form that uses JavaScript for building a POST statement. In Chrome, I can use a simple line of code...
var form = document.forms['myForm'];
var env = form.env.value;
The form itself looks like this...
<form name="myForm" action='JavaScript:xmlhttpPost("/path/to/some/pythoncode.py")'>
<input type="radio" name="env" id="env" value="inside">Inside
<input type="radio" name="env" id="env" value="outside" checked="checked">Outside
<input type="radio" name="env" id="env" value="both">Both
<input type="radio" name="env" id="env" value="neither">Neither
I have some text boxes on the form that I can use the same technique to find the value (
var name = form.fname.value
with a
<input type="text" name="fname" id="fname">
However, when I submit the form and build my post, the value for the radio buttons is always undefined. It works fine in Chrome, but nothing in IE or FireFox.
I tried var env = document.getElementById('env').value, but for some reason that always defaults to the first value (inside) no matter what I select. That method also does not return a value when using Chrome.
Is there something I'm missing for reading the checked value of a radio input in FF or IE?
Try this
function getValueFromRadioButton(name) {
//Get all elements with the name
var buttons = document.getElementsByName(name);
for(var i = 0; i < buttons.length; i++) {
//Check if button is checked
var button = buttons[i];
if(button.checked) {
//Return value
return button.value;
}
}
//No radio button is selected.
return null;
}
IDs are unique so you should not use the same ID for multiple items. You can remove the all the radio button IDs if you use this function.
You are using the same ID for multiple Elements, ID is unique for element on the page.
use different IDs.
edit: names can be the same. because then the radio buttons are as a group.
As stated, the IDs should be different to be valid, but you could accomplish this by eliminating the IDs all together and using just the input name:
var form = document.forms['myForm'];
var radios = form.elements["env"];
var env = null;
for(var i=0;i<radios.length;i++) {
if(radios[i].checked == true) {
env = radios[i].value;
}
}
<form name="myForm">
<input type="radio" name="env" value="inside">Inside
<input type="radio" name="env" ivalue="outside" checked="checked">Outside
<input type="radio" name="env" value="both">Both
<input type="radio" name="env" value="neither">Neither
</form>
Short & clear on ES-2015, for use with Babel:
function getValueFromRadioButton( name ){
return [...document.getElementsByName(name)]
.reduce( (rez, btn) => (btn.checked ? btn.value : rez), null)
}
console.log( getValueFromRadioButton('payment') );
<div>
<input type="radio" name="payment" value="offline">
<input type="radio" name="payment" value="online">
<input type="radio" name="payment" value="part" checked>
<input type="radio" name="payment" value="free">
</div>
You can try this:
var form = document.querySelector('form#myForm');
var env_value = form.querySelector('[name="env"]:checked').value;

Categories