简体   繁体   中英

Getting text of checked radio button

how to get text instead of value, when I click on the radio button?

Below code gets Value of the radio button. I want to take texts (Shows or Movies). Thanks in advance.

 function myFunction(contentType) { document.getElementById("myspan").innerHTML = contentType; }
 <label><input type="radio" oninput="myFunction(this.value)" value="1" name="contentType"><span>Shows</span></label> <label><input type="radio" oninput="myFunction(this.value)" value="2" name="contentType" ><span>Movies</span></label> <span id="myspan" class="text-muted" ></span>

Inside your myFunction() do this:

function myFunction(inputRadio) {
  document.getElementById("myspan").innerHTML = inputRadio.nextSibling.innerText;
}

In your HTML change this.value to this , and you are good to go!

<label><input type="radio" oninput="myFunction(this)" value="1" name="contentType"><span>Shows</span></label>
<label><input type="radio" oninput="myFunction(this)" value="2" name="contentType" ><span>Movies</span></label>

<span id="myspan" class="text-muted" ></span>

You'll have to either add a data attribute to your radio button, or manually query the DOM to get the text content of the label related to that radio button.

 function myFunction(input) { document.getElementById("myspan").innerHTML = input.dataset.textValue; }
 <label><input type="radio" oninput="myFunction(this)" value="1" data-text-value="Shows" name="contentType"><span>Shows</span></label> <label><input type="radio" oninput="myFunction(this)" value="2" data-text-value="Movies" name="contentType" ><span>Movies</span></label> <span id="myspan" class="text-muted" ></span>

 function myFunction(contentType) { document.getElementById("myspan").innerHTML = contentType; }
 <label><input type="radio" oninput="myFunction(this.value)" value="shows" name="contentType"><span>Shows</span></label> <label><input type="radio" oninput="myFunction(this.value)" value="movies" name="contentType" ><span>Movies</span></label> <span id="myspan" class="text-muted" ></span>

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