Home > Software design >  Get selected option html when using parent form (not document) using vanilla javascript
Get selected option html when using parent form (not document) using vanilla javascript

Time:03-18

I have an HMTL form, that it's repeated multiple times on a webpage, in order to prevent to target every specific field name, of every form, i'm doing a general-use javascript script that detects where was triggered and obtain the values of the fields (of that specific form traversing from it) in order to send it to another server using ajax call. The problem is that I can't find a way to obtain a selected item of a select dropdown list.

Since it's a general-use script I can't use ID value.

function sendForm(reference){
  const form = reference.closest('form');
  var elements = form.getElementsByTagName("input");
  var name = elements.namedItem('name').value;
  var mail = encodeURIComponent(elements.namedItem('email').value);
  // Here I don't know how to get the selected item from the option group)
  var program = elements.namedItem('program').value;  // (it doesn't work);
  console.log(name)
  console.log(mail)
  /*
    Ajax Stuff that is already solved  and not needed to show the point
  */
}
<form id="my-form" data-origin="form-1" action="">
  <input placeholder="Name*" type="text"  name="name" id="name" required>
  <input type="email"  placeholder="Email*" name="email" id="mail" required>
  <select  name="program" required>
    <option name="programa" value="">- Select -</option>           
    <option value="LCP">First choice</option>
    <option value="LSP">Seccond choice</option>
    <option value="LAE">Third choice</option>
    <option value="LD">Fourth choice</option>
   </select>
  <button type="button" onclick="sendForm(this)" >Send</button>
</form>

CodePudding user response:

var programa = document.getElementById('program').value; should work, as long as the <select> only allows one option to be selected.

CodePudding user response:

If you look at the MDN documentation for the HTMLSelectElement, you can see that the value property will be the value of the selected option (or the first selected option in case of a <select multiple> element). So in your code, you could have done:

var programa = elementos.namedItem('program').value;

As a side note, the HTMLFormElement also has an elements property (read more about it here) which returns a collection of all the form controls in the form. So you don't have to use getElementsByTagName on the form.

  • Related