user1592380
user1592380

Reputation: 36317

Build an array of ids of all select boxes

I'm trying to convert a bunch of select boxes to be editable using the fantastic jQuery plugin: https://github.com/indrimuska/jquery-editable-select.

The first step is to get the ids of all select boxes. From http://jsfiddle.net/49rk6ph7/69/ I have tried this but I'm not getting:

[s1,s2]

How can I get this working?

var test = [];
test = $("select").each(function() {
  test.push($(this).attr('id'))
});

console.log(test);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="select-editable">
  <select id="s1" onchange="this.nextElementSibling.value=this.value">
    <option value=""></option>
    <option value="115x175 mm">115x175 mm</option>
    <option value="120x160 mm">120x160 mm</option>
    <option value="120x287 mm">120x287 mm</option>
  </select>
  <input type="text" name="format" value="" />
</div>

<div class="select-editable">
  <select id="s2" onchange="this.nextElementSibling.value=this.value">
    <option value=""></option>
    <option value="115x175 mm">115x175 mm</option>
    <option value="120x160 mm">120x160 mm</option>
    <option value="120x287 mm">120x287 mm</option>
  </select>
  <input type="text" name="format" value="" />
</div>

Upvotes: 2

Views: 57

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337646

The issue with your code is because you're assigning test to the result of each(), which is a jQuery object, not the array you originally define. Simply remove test = from that statement.

Note that you can also make the logic more succinct by using map() instead of an each() loop and by removing the outdated on* attributes with unobtrusive JS event handlers. Something like this:

var test = $("select").map(function() {
  return this.id
}).get();

console.log(test);

$('#s1, #s2').change(function() {
  $(this).next().val($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="select-editable">
  <select id="s1">
    <option value=""></option>
    <option value="115x175 mm">115x175 mm</option>
    <option value="120x160 mm">120x160 mm</option>
    <option value="120x287 mm">120x287 mm</option>
  </select>
  <input type="text" name="format" value="" />
</div>

<div class="select-editable">
  <select id="s2">
    <option value=""></option>
    <option value="115x175 mm">115x175 mm</option>
    <option value="120x160 mm">120x160 mm</option>
    <option value="120x287 mm">120x287 mm</option>
  </select>
  <input type="text" name="format" value="" />
</div>

Upvotes: 3

Sebastian Simon
Sebastian Simon

Reputation: 19515

Remove test = before your jQuery call. You’re overwriting your original test array.

This is all you need:

var test =  [];

$("select").each(function() {
    test.push($(this).attr("id"));
});

console.log(test);

Upvotes: 5

Related Questions