Amirol Ahmad
Amirol Ahmad

Reputation: 542

Select onchange and custom text field value

i've select option below

<select id="order_package_id" class="form-control" name="order[package_id]">
  <option value="1">KJ01</option>
  <option value="2">KJ02</option>
  <option value="3">KJ03</option>
  <option value="4">KJ04</option>
  <option value="5">KJ DELUXE</option>
  <option value="6">KJO6</option>
</select>

and one text field with default value in hidden

<input id="order_discount_id" class="form-control" type="hidden" value="2" name="order[discount_id]">

My question is I want to make when select value is == 6, then the text field will change to value="3"

I've try with the jquery below but no luck

$('#order_package_id').change(function() {
  if($(this).val() == 6) {
    $('#order_discount_id').val() == 3;
  }
});

Upvotes: 1

Views: 692

Answers (2)

Ram
Ram

Reputation: 144739

You should pass the value to the .val() method. Without passing a value, .val() as a getter returns the current value of the element. So what happens is you get the value and compare it against 3 using == operator. The code effectively doesn't do anything.

$('#order_discount_id').val(3);

For assignment the = operator should be used, but you can't use a value on the left side of assignment.

Edit: If the value should be 2 when the select's value is not 6, you should add a else block to your code. Another option is using conditional (ternary) operator:

$('#order_package_id').change(function() {
    $('#order_discount_id').val( this.value == 6 ? "3" : "2" );
});

Upvotes: 1

T J
T J

Reputation: 43166

To set the value, pass it to val() method:

$('#order_package_id').change(function() {
  if($(this).val() == 6) {
    $('#order_discount_id').val(3);
  }
});

Upvotes: 1

Related Questions