sy89
sy89

Reputation: 193

form action to toggle a function?

<form action="" method="get" >
    <input type="radio" name="gender" id="male_sub">male<br>
    <input type="radio" name="gender" id="female_sub">female<br>
    <input type="submit" value="Let's Start!" id="start"><br>
<form>

I have the following radio form and when I hit submit, I would like it to toggle some function in my js script. However, if I do something like:

document.getElementById("start").addEventListener('click',function ()...

Nothing works. I think I need something for the action tag, but I can only find examples that link to other websites/pages, which isn't what I want. Is toggling a function possible to do using the forms?

Thanks!

Upvotes: 1

Views: 649

Answers (2)

ElasticCode
ElasticCode

Reputation: 7867

You can define the submit function on form tag using onsubmit, Also this solution is accurate if you have multiple form tags on the same page.

function submitForm(form, event) {
  event.preventDefault();
  var val;
  var radios = form.elements['gender'];

  // loop through list of radio buttons
  for (var i = 0, len = radios.length; i < len; i++) {
    if (radios[i].checked) { // radio checked?
      val = radios[i].value; // if so, hold its value in val
      alert(val);
      break; // and break out of for loop
    }
  }
  alert("nothing selected");
  return false;
}
<form onsubmit="return submitForm(this,event)">
  <label><input type="radio" name="gender" id="male_sub" value="male">male</label><br>
  <label><input type="radio" name="gender" id="female_sub" value="female">female</label><br>
  <input type="submit" value="Let's Start!" id="start"><br>
</form>

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370729

You're on the right track:

document.getElementById("start").addEventListener('click', function(e) {
  e.preventDefault();
  console.log('start!!');
  const selected = document.querySelector('input[name="gender"]:checked');
  console.log('you selected: ' + (selected ? selected.nextSibling.textContent : 'null'));
  // your code here
});
<form>
    <input type="radio" name="gender" id="male_sub">male<br>
    <input type="radio" name="gender" id="female_sub">female<br>
    <input type="submit" value="Let's Start!" id="start"><br>
<form>

You don't need an action or a method attribute. Make sure to use e.preventDefault() to prevent the form from submitting (redirecting the page) if you want to handle the form's values yourself.

Upvotes: 2

Related Questions