简体   繁体   中英

How capture the input radio value in javascript?

For example I have the next options in html, define the global name and different id to each input radio:

 <form id="mokepon-form">
  <input type="radio" name="mokepon" id="hipodoge">
  <label for="hipodoge">Hipodoge</label>

  <input type="radio" name="mokepon" id="capipego">
  <label for="capipego">Capipego</label>

  <input type="radio" name="mokepon" id="ratigueya">
  <label for="ratigueya">Ratigueya</label>

  <button type="submit">Seleccionar</button>
</form>

To read the value I read the selector, the global name and the checked attribute and then read the id property, you can use the value property as well.

const chooseMokepon = (e) => { 
  e.preventDefault(); 
  const $selectedMokepon = document.querySelector('input[name=mokepon]:checked');
  const { id: mokeponValue } = $selectedMokepon;
  if (!mokeponValue) return;

  console.log(mokeponValue);
}

$mokeponForm.addEventListener('submit', e => chooseMokepon(e));

You might use this snippet:

 let submitBtn = document.querySelector('button[type="submit"]'); submitBtn.addEventListener('click', function(event){ event.preventDefault(); let selectedOption = document.querySelector('input[type="radio"][name="mokepon"]:checked'); if(selectedOption && selectedOption.value){ console.log('Selected: ' + selectedOption.value); } });
 <form id="mokepon-form"> <input type="radio" name="mokepon" id="hipodoge" value="hipodoge"> <label for="hipodoge">Hipodoge</label> <input type="radio" name="mokepon" id="capipego" value="capipego"> <label for="capipego">Capipego</label> <input type="radio" name="mokepon" id="ratigueya" value="ratigueya"> <label for="ratigueya">Ratigueya</label> <button type="submit">Seleccionar</button> </form>

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