user3338496
user3338496

Reputation: 7

create array of values from a group of <select>

this should be easy but i'm struggling. New to jquery I want to create an array that is the values of selected values from a series of dropdown menus. I can get it to read the first dropdown menu value only but want to have an array of the second third fourth etc

my html is

  <select name="select" id="select">
  <option value="1">one</option>
  <option value="2" selected>two</option>
  </select>
  <select name="select" id="select">
  <option value="1" selected>one</option>
  <option value="2">two</option>
  </select>
  <select name="select" id="select">
  <option value="1">one</option>
  <option value="2" selected>two</option>
  </select>
  <select name="select" id="select">
  <option value="1" selected>one</option>
  <option value="2">two</option>
  </select>

and script here

$(document).ready(function(){  
    var string = $( "#select" ).map(function() {  
        return this.value;
    }).get().join();

    $("#display").text(string); 
});

I suppose i need to know how to get the id of <select> to be recognized as an array (in PHP it is done by adding [] onto the name of the <select> menu...

Upvotes: 0

Views: 83

Answers (1)

Cameron Little
Cameron Little

Reputation: 3711

Working example: http://jsfiddle.net/4tvxw/1/

HTML

<select name="select1" class="select">
    <option value="1">one</option>
    <option value="2" selected>two</option>
</select>
<select name="select2" class="select">
    <option value="1" selected>one</option>
    <option value="2">two</option>
</select>
<select name="select3" class="select">
    <option value="1">one</option>
    <option value="2" selected>two</option>
</select>
<select name="select4" class="select">
    <option value="1" selected>one</option>
    <option value="2">two</option>
</select>
<div id="display"></div>

Javascript

$(document).ready(function(){  
    var str = $( ".select" ).map(function() {  
        return this.value;
    }).get().join();

    $("#display").text(str); 
});

You are using the same id for multiple elements. Id's are usually reserved for unique elements in the DOM. I just switched id to class to get it working. I'd also recommend using unique name's for each form item; it'll make getting specific form data easier in the future.

Upvotes: 1

Related Questions