James Ferguson
James Ferguson

Reputation: 71

Update text input from select option chosen

I have a select field which also updates a text field when chosen with the price of that selected option. Any Ideas on why this wont work?

Html:

<label for="material1" class="select">Material:</label>
<select name="material" id="material1" data-native-menu="false" rel="price1">
<option>Select Material</option>
<option value="55 Bolt" rel="125,000.00">55 Bolt</option>
</select>
<label for="net1">Net Price:</label>
<input type="text" name="net" id="net1" rel="price1" value=""  />

JS:

<script type="text/javascript">
$("material1").change(function () {
   $(this).next("input[rel="+$(this).attr("rel")+"]").val($(this).val());
   $('#net1').textinput('refresh');

}).change();
</script>

Upvotes: 0

Views: 883

Answers (2)

elclanrs
elclanrs

Reputation: 94121

Your main problem is here, and mgoeppner has some good suggestions too.

$(this).next("input[rel="+$(this).attr("rel")+"]").val($(this).val());

$(this).val() refers to the value of select which is null. You have to refer to the value of the selected option. Then next() won't work because the input is not next to the select, there's a label in between. You can use closest()

var value = $(this).find('option:selected').val();
$(this).closest("input[rel="+$(this).attr("rel")+"]").val(value);

Upvotes: 1

mgoeppner
mgoeppner

Reputation: 151

It won't work for a few reasons:

  1. $(this).next() will return [] since the next sibling <label> is not an input with the a matching rel attribute. Try using $(this).siblings("input[rel="+$(this).attr("rel")+"]") instead.

  2. There is no textinput() function in the jQuery API. Perhaps you meant text()?

Finally, you don't need to do $(...).change(function()...).change() -- $(...).change(function()...) will suffice .

Upvotes: 1

Related Questions