64YearOldCoder
64YearOldCoder

Reputation: 15

How to pragramatically change a dropdownlist to another field's value

I have a dropdownlist with a list of countries (all countries)

<select id="Country" onchange="country();">
  <option id="3">Japan</option>
  <option id="4">Canada</option>
  <option id="5">France</option>
  <option id="6">Peru</option>
</select>

I have the form in a modal that i want get country value from.

<input id="seachcountry" type="text" class="form-control" name="country">

I have written a JQuery line to get the value from the modal form to the page fields, everything works great but the country select fields are not changing the value.

$("#seachcountry").val($("#modalform").val()).trigger("chang‌e");

thank you for your suggestions!

Upvotes: 0

Views: 43

Answers (3)

Jithin Raj  P R
Jithin Raj P R

Reputation: 6797

This will work for you:

Just inject the value of the <input> to <select>.

I have created a snippet for you.

var Tval = $('#seachcountry').val();

$('#Country').val(Tval);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="Country" onchange="country();">
  <option id="3">Japan</option>
  <option id="4">Canada</option>
  <option id="5">France</option>
  <option id="6">Peru</option>
</select>

<input id="seachcountry" type="text" class="form-control" name="country" value="France">

Upvotes: 1

reconnect
reconnect

Reputation: 336

For changing value in any select you just need send exist value from this select. In your select options have only ids, but not have value attribute. So if you add value equal to id to change value in the your form to "France" need run following:

$("#selectId").val(5)

Instead of 5 you can obtain value from any other field or else.

If you want set your value to input field when changed in select, you need attach listener that will do all work. It will looks like this:

$("#selectId").on("change", function(){
     $("#inputFieldId").val($(this).find(":selected").text());
})

This will set displayed value to select, to set real value just write instead $(this).find(":selected").text() this $(this).val()

Upvotes: 0

Jordan Lipana
Jordan Lipana

Reputation: 447

Try this.

function country() {
    $("#seachcountry").val($(this).val());
}

Upvotes: 0

Related Questions