简体   繁体   中英

Change the text of the radio button dynamically

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');
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM