简体   繁体   中英

How to get multiple drop-down box value using J-Query

I have generated drop-down box using loop. Now I want to get all value using J-Query for pass these value for insertion through Ajax.

My HTML CODE is:

<select name="travel[]" id="travel[]"  >
     <option   value="1">Car</option>
<select>
<select name="travel[]" id="travel[]"  >
     <option   value="2">Train</option>
<select>
<select name="travel[]" id="travel[]"  >
     <option   value="3">Bus</option>
<select>

After click on Save button, how to collect all values of travel?

I don't understand why you define three <select> elements with an index-based name, each containing a single <option> . You do know that a <select> element is exactly that - it gives the user a selection ?

With your current markup, the user doesn't get a choice about their selection - rather, travel[] will always be an array containing: 1,2,3 .

You'd be better to modify your markup as follows:

<select name="travel" id="select_travel">
     <option value="1">Car</option>
     <option value="2">Train</option>
     <option value="3">Bus</option>
<select>

Now you can easily access the value using:

$('#select_travel').val();

You can do this:

var data = $('select[name="travel[]"]').map(function () {
    return $(this).val();
}).get();

console.log(data);    // ["1", "2", "3"] 

This will return you an array with the value for all the dropdowns.

Fiddle demo

why you are making name and id both as array type... i think one will enough if you really want to use array type.... then make id as unique for all...

  <select name="travel[]" id="abc">
  </select>

  <select name="travel[]" id="def">
  </select>

  <select name="travel[]" id="xyz">
  </select>

now you can access dropdown list easily..

   $("#abc").val();
   $("#def").val();
   $("#xyz").val();

or else you can define uniq class for them if you really want array type id and name

   <select name="travel[]" id="travel[]" class="abc">
  </select>

  <select name="travel[]" id="travel[]" class="xyz">
  </select>

and try like this...

   $(".abc").val();
   $(".xyz").val();

hope it may help you

you should try js like-

var selectOption=$('#select_travel').val()
var Id=selectOption.getAttribute('id');
var name=selectOption.getgetAttribute('id');

now you can take output on button click

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