How do you access the value for input or select outside of form tags

I'm trying to use a select element that is located outside of the form tags. HTML5 allows <select form="myform" name="myselect">

All the following examples work if I move the select in between the form tags, but that would defeat the purpose of the 'form=' attribute.

I also do not want to use an id= in the select field as I will have multiple forms on the same page.

Thanks.

$('#mybutton').click(function () {
  alert("1: " + $('#myform select[name="myselect"]').val());
  
  myform = $('#myform');
  alert("2: " + myform.find('select[name="myselect"]').val());  

  alert("3: " + $('#myform select').val());
  
  myform = $('#myform');
  alert("4: " + myform.find('select').val());

  // works
  alert("5: " + $('select[form="myform"][name="myselect"]').val());

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="banner-message">
  <form id="myform">
    <input type="hidden" name="myhidden" value="2" />
    <input id="mybutton" type="button" name="Go" value="Go" />
 
  </form>
   
  <select form="myform" name="myselect">
    <option value="1">one</option>
    <option value="2">two</option>
    <option value="3">three</option>
  </select>  
</div>

2 answers

  • answered 2018-07-12 07:51 alexP

    You can't select your Dropdown with:

    $('#myform select[name="myselect"]').val();
    

    because there is no child element with the name myselect in the element with the ID myform in DOM.

    You'll have to use

    $('select[name="myselect"]').val();
    

  • answered 2018-07-12 07:51 Dananjaya Ariyasena

    You can use class :

    $('#mybutton').click(function () {
      
      $( ".sel" ).each(function ( index ) {
         alert( index + " number of select box value : " + $( this ).val() );
      });
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="banner-message">
      <form id="myform">
        <input type="hidden" name="myhidden" value="2" />
        <input id="mybutton" type="button" name="Go" value="Go" />
     
      </form>
       
      <select class="sel" form="myform" name="myselect">
        <option value="1">one</option>
        <option value="2">two</option>
        <option value="3">three</option>
      </select>  
    </div>

    Now you can have multiple selections with the same class and iterate them.