cantaffordavan
cantaffordavan

Reputation: 1447

Jquery form - Change hidden value to option id

Ah im racking my brain trying to figure this out. New to Jquery... as you will probably be able to tell soon...

Trying to use the option id to set the value of a hidden input, but hours in and hundreds of google searches with no solution.

I have figured out how to pull the value of the selected option using the selector ID but I want to get the ID of the option, so I can set that unique ID as the value of the hidden input.

<form>
<select name="amount" id="item_number1">
    <option value="1" id="11">one</option>
    <option value="2" id="22">two</option>
    <option value="3" id="33">three</option>
</select>
<input type="button" value="Set Value" onclick="$('#item_number2').val( $('#item_number1').val() )"/>
<input id="item_number2" type="text" />

Ps: the hidden input isnt in this form, In this form I am using a text input field so I can visualize if my method is working.

Upvotes: 2

Views: 981

Answers (2)

Sampson
Sampson

Reputation: 268344

You can get the id of the selected option like this:

<script>
$(function(){
  var sItem = document.getElementById("item_number1");
  $("#transfer").on("click", function(){
    $("#item_number2").val( sItem[sItem.selectedIndex].id );
  });
});
</script>
<input type="button" id="transfer" value="Transfer ID" />
<select name="amount" id="item_number1">
  <option value="1" id="11">one</option>
  <option value="2" id="22">two</option>
  <option value="3" id="33">three</option>
</select>
<input type="text" id="item_number2" />

Note, you are not suppose to start your id values with a number - this may cause problems for you down the road. Best to adhere to the rules when it comes to stuff like this.

Demo: http://jsbin.com/ucujex/edit#javascript,html,live

Upvotes: 1

dtbarne
dtbarne

Reputation: 8200

You can update your button's onclick to:

$("#item_number2").val($("#item_number1 option:selected").attr("id"));

A nice improvement would be to have it automatically change when you change the option in the select (you wouldn't need the button).

$("#item_number1").change(function() {
    $("#item_number2").val($("option:selected", this).attr("id"));
});

Upvotes: 1

Related Questions