tags:

views:

70

answers:

3

I have an hidden input field with a value,

   <form>
        <input type="hidden" value="product"/>
        <select class="select" name="select3" id="select3">
          <option>0</option>
          <option>1</option>
          <option>2</option>
        </select>
  </form>

I need to get the value of input field once a button is clicked but I only get the text object why is that?

      var items[]; 
      $('#my-add-button-sides').click(function() {
  $('.select option:selected').each(function() {
  var $this = $(this);
  items.push($this.prev($('input[type=hidden]').val ()          
             ));


});

thanks

A: 

If I understand correctly you just need to get the value of whatever was selected? If so, I don't believe the each() function is necessary. You can simply get the value of the select like so:

$(document).ready(function(){ 

  $('#select3').change(function() { 
      var selValue = $(this).val(); 
      alert(selValue); 
  }); 


});


<form name="someForm"> 

    <input type="hidden" value="product"/> 

    <select class="select" name="select3" id="select3"> 

      <option value="0">0</option> 

      <option value="1">1</option> 

      <option value="2">2</option> 

    </select> 

</form>

Example: http://jsbin.com/ipado

jyoseph
I think he needs a value of a hidden `input` that is before `select` element.
RaYell
Ah, gotcha, I must have misunderstood.
jyoseph
A: 

There are some typos in your code. Check if this will help. I fixed array initialization and prev call.

var items = []; 
$('#my-add-button-sides').click(function() {
    $('.select option:selected').each(function() {
         items.push($(this).parent().prev('input:hidden').val())
     ));
});
RaYell
Why the each when only one option can be selected. Also prev of an option in a select will either be an other option or nothing (if at first option element)
redsquare
That's not true. IF you have more then one select box then this will match all selected options from all of them. Also if you have a multi-select this will return more then one item.
RaYell
The example showed 1 select, and it was not multi choice. The prev was still incorrect.
redsquare
@redsquare: I fixed problem with prev soon after you pointed it out. About `each`: my goal was to make to code as generic as possible. Sorry that you see it as a bad thing.
RaYell
A: 

In your example code, this isn't the select-element, but an option-element. So the hidden input and this aren't siblings, and prev does not match the element you want.

$(this).parent().prev('input:hidden').val()

Jump one level up in the DOM, and you'll find the hidden input.

Magnar