-3

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>
Vebbie
  • 1,669
  • 2
  • 12
  • 18
blueDroid
  • 231
  • 1
  • 3
  • 10

1 Answers1

0

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';
daddygames
  • 1,880
  • 1
  • 11
  • 18
  • The problem is that the html is written as such I cannot modified. Your code works fine with the span, it does change the text and keep the radio button which is fine. But without the span, it changes the text but deletes the radio button – blueDroid Feb 04 '19 at 21:12
  • @blueDroid I have updated the answer so that if you cannot change the HTML at all, you can still get the text to change. This is one work-around. – daddygames Feb 05 '19 at 14:28
  • Great answer!!! Really appreciated!!! – blueDroid Feb 05 '19 at 15:14