How do I update the label for a radio input element in JavaScript (or jQuery)? For example, change the text from 'Swift' to 'Python'
<label for="language">
<input type="radio" id="language" name="language" value="main">Swift
</label>
How do I update the label for a radio input element in JavaScript (or jQuery)? For example, change the text from 'Swift' to 'Python'
<label for="language">
<input type="radio" id="language" name="language" value="main">Swift
</label>
If you re-arrange the HTML, you can target the label and change the text.
HTML
<input type="radio" id="language" name="language" value="main">
<label for="language">Swift</label>
JQuery JS
$('label[for="language"]').text('Python');
Standard JS
var find = document.querySelectorAll('label[for="language"]');
if (find.length>0) {
find[0].innerText = 'Python';
}
If you cannot or do not want to re-arrange the HTML, maybe wrap the text with a <span>
element and target that.
HTML with Span
<label for="language">
<input type="radio" id="language" name="language" value="main"><span>Swift</span>
</label>
JQuery JS for HTML with Span
$('label[for="language"] span').text('Python');
Standard JS for HTML with Span
var find = document.querySelectorAll('label[for="language"] span');
if (find.length>0) {
find[0].innerText = 'Python';
}
If you cannot edit the HTML at all, then you may want to copy the radio button so it can be placed back into the element once you decide what text to display next to it.
HTML
<label for="language">
<input type="radio" id="language" name="language" value="main">Swift
</label>
JQuery JS
var find = $('label[for="language"]');
var html = find.html();
var regex = /(<([^>]+)>)/ig;
var radioButton = html.match(regex)[0];
find.html(radioButton + 'Python');
Standard JS
var find = document.querySelectorAll('label[for="language"]');
var html = find[0].innerHTML;
var regex = /(<([^>]+)>)/ig;
var radioButton = html.match(regex)[0];
find[0].innerHTML = radioButton + 'Python';