dongzhan1570
dongzhan1570
2013-11-18 10:47

如何使用JQuery获取多个下拉框值

已采纳

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. Please Help . Thanks in Advanced.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

4条回答

  • dongren7374 dongren7374 8年前

    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

    点赞 评论 复制链接分享
  • douliaodan2738 douliaodan2738 8年前

    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

    点赞 评论 复制链接分享
  • dqwh1202 dqwh1202 8年前

    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();
    
    点赞 评论 复制链接分享
  • doutang3815 doutang3815 3年前

    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

    点赞 评论 复制链接分享