Change the text of the radio button dynamically - javascript

I have a scenario of having a series of radio buttons with a name of the payment method. I need to change that text on load of the page. For Example.
<label class="radio-inline">
<div class="iradio_square-blue">
<input type="radio" name="paymentmethod" value="Paypal">
<ins></ins>
</div>
Paypal India
</label>
In the above code sample I need to change the "Paypal India" to "Paypal Global" via javascript We do not have id to the radio button only way to target is via value of the radio button which in the case above is paypal.
Can anyone help me out here.
Thanks in advance.

You will need to look at the childNodes
const label = document.querySelector("[name=paymentmethod][value=Paypal]")
.closest("label");
[...label.childNodes].forEach(node => {
let text = node.textContent;
if (text && text.includes("India")) {
node.textContent = text.replace("India", "Global");
}
});
<label class="radio-inline">
<div class="iradio_square-blue">
<input type="radio" name="paymentmethod" value="Paypal">
<ins></ins>
</div>
Paypal India
</label>

Here for your reference. I think it will be helpful.
document.addEventListener("DOMContentLoaded", function(event) {
const labels = document.getElementsByClassName('radio-inline');
if (labels.length) {
let label = labels[0];
label.innerHTML = label.innerHTML.replace(/Paypal India/, 'Paypal Global');
}
});

Related

without an event for a radiobutton or checkbox, how can I set it true or false programmatically

I have a page with radiobuttons and checkboxes; the form has previously been filled out by the user. I need to bring the form back up for them to edit the EXISTING data, which means I have to programmatically check checkboxes and check radio buttons.
If I HAD an event, I could easily change the corresponding control with srcElement, but there is no event in this case. I haven't been able to find a way with document.getElementById('XXX'). ??? to work in any way.
Using Angular 4 if that helps.
Thoughts?
Thanks in advance, :-)
Use data binding. Then you can set the changed value and the checkbox and radio buttons will check/select automatically.
Here is an example:
<label>
<input id="sendCatalogId"
type="checkbox"
[(ngModel)]="sendCatalog"
name="sendCatalog" >
Send me your catalog
</label>
And a radio button:
<label class="radio-inline">
<input type="radio" id="addressType1Id" value="home"
[(ngModel)]="addressType"
name="addressType">Home
</label>
<label class="radio-inline">
<input type="radio" id="addressType1Id" value="work"
[(ngModel)]="addressType"
name="addressType">Work
</label>
<label class="radio-inline">
<input type="radio" id="addressType1Id" value="other"
[(ngModel)]="addressType"
name="addressType">Other
</label>
This in the component class:
...
export class CustomerComponent {
sendCatalog = false;
addressType = "home";
constructor() {
sendCatalog = true;
addressType = "work";
}
}

How to display a radio button selected using a variable?

I have a variable that contains a radio button value. I check some conditions, and based on this value the radio button will be selected.
if(cheque_date == system_date) {
cheque_value='Current';
}
else {
cheque_value='PDC';
}
cheque_value = $('input[name=cheque_type]:checked').val();
Radio button:
<label class="radio">
<input type="radio" name="cheque_type" value="Current" />Current
</label>
<label class="radio">
<input type="radio" name="cheque_type" value="PDC" />PDC
</label>
Is this right?
You can check radio button based on value like following.
if(cheque_date == system_date) {
cheque_value='Current';
}
else {
cheque_value='PDC';
}
$('input[name=cheque_type][value="'+cheque_value+'"]').prop('checked', true);
You need some modifications in your code:
1) Add ids to your checkboxes. In HTML, id attribute is unique, so selecting elements with id is much more faster than by classes or tags.
2) Get id in a variable and use that runtime variable in jQuery.
Final code:
<label class="radio">
<input type="radio" name="cheque_type" value="Current" value="Current"/>Current</label>
<label class="radio">
<input type="radio" name="cheque_type" value="PDC" value="PDC" />PDC</label>
AND jQuery code:
var cheque_id = (cheque_date == system_date) ? 'Current' : 'PDC';
cheque_value = $('#'+cheque_type+':checked').val();
Can you try the code below ?
if(cheque_date == system_date)
cheque_value = 'Current';
} else {
cheque_value = 'PDC';
}
$("input[name='cheque_type'][value='"+cheque_value+"']").prop("checked",true);
var inputValue = $("input[name='cheque_type']:checked").val();
Hope this helps.
Edit: triggering not solves the value issue and I improved my answer and you can see demo of solution on link JSFiddle Demo

Show / Hide contents base on radio button selection

I am trying to toggle a content DIV base on the selection of radio buttons.
HTML for radio button.
<div class="row-fluid">
<label class="radio">
<input type="radio" name="account" id="yes" value="yes" checked>
Yes, I have an existing account
</label>
<label class="radio">
<input type="radio" name="account" id="no" value="no">
No, I don't have an account
</label>
</div>
Content DIV
<div id="account_contents">
<p>This is account contents.......</p>
</div>
This is how I tried it in jquery.
$('#no').bind('change',function(){
$('#account_contents').fadeToggle(!$(this).is(':checked'));
$('#account_contents').find("input").val("");
$('#account_contents').find('select option:first').prop('selected',true);
});
But it doesn't work for me correctly. Here I want to show this content DIV only if user don't have an account.
Can anybody tell me how to fix this problem?
seems you need .on('change') for radio buttons not just for one of them
$('input[type="radio"][name="account"]').on('change',function(){
var ThisIt = $(this);
if(ThisIt.val() == "yes"){
// when user select yes
$('#account_contents').fadeOut();
}else{
// when user select no
$('#account_contents').fadeIn();
$('#account_contents').find("input").val("");
$('#account_contents').find('select option:first').prop('selected',true);
}
});
Working Example
$(document).ready(function(){
$('.radio input[type="radio"]').on("click", function(){
if($('.radio input[type="radio"]:checked').val() === "yes"){
$("#account_contents").slideDown("slow");
}else{
$("#account_contents").slideUp("slow");
}
});
});
I'm not sure if I got you right, but this fiddle toggles #account_contents depending on which button you click:
This was how i tweaked the script:
$('#no').bind('change',function(){
$('#account_contents').fadeToggle(!$(this).is(':checked'));
$('#account_contents').find("input").val("");
$('#account_contents').find('select option:first').prop('selected',true);
});
$("#yes").bind("change", function() {
$('#account_contents').fadeOut();
});

Javascript how to change radio button label text?

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;

How to get the selected radio button label text using jQuery

I have a radio button like this on page
<div id="someId">
<label class="radio-inline">
<input name="x" type="radio" onchange="GetSelectedVal();">Yes</label>
<label class="radio-inline">
<input name="x" type="radio" onchange="GetSelectedVal();">No</label>
</div>
On page load I don't want to set any selection so not using checked property. In my JavaScript function, how can I get the value Yes or No based on the user selection at runtime?
function GetSelectedVal() {
console.log($('#someId input:radio.........);
}
I have seen similar questions but unable to find solution of this issue.
Remove onchange inline handler from HTML. Use on to bind events.
:checked will select the checked radio button. closest will select the parent label and text() will get the label associated with the radio button. e.g. Yes
$('[name="x"]').on('change', function () {
alert($('[name="x"]:checked').closest('label').text());
});
DEMO
You can simple pass this in onchange="GetSelectedVal(); like onchange="GetSelectedVal(this);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="someId">
<label class="radio-inline"><input name="x" type="radio" onchange="GetSelectedVal(this);">Yes</label>
<label class="radio-inline"><input name="x" type="radio" onchange="GetSelectedVal(this);">No</label>
</div>
<script>
function GetSelectedVal(ele) {
alert($(ele).closest('label').text());
}
</script>
I would do it a bit different than the accepted answer.
Instead of having events on multiple radio buttons, you can have one on the containing div. Also let just the checked radio trigger the change:
$('#someId').on('change', 'input[name="x"]:checked', function () {
var label = $(this).siblings('span').text();
console.log(label);
});
When I have text next to other elements I prefer wrapping the text in span's:
<div id="someId">
<label class="radio-inline"><input name="x" type="radio"><span>Yes</span></label>
<label class="radio-inline"><input name="x" type="radio"><span>No</span></label>
</div>
A demo: jsfiddle.net/qcxgwe66/

Categories