Search code examples
javascriptjqueryselectdropdownhtml-select

Change value of selected option


I have dropdown select option countries:

    <select name="country" id="countryId" required="required"
class="countries order-alpha form-control custom-select bg-white border-left-0 border-md">
                                <option value="">Select Country</option>
                                <option value="1"> Afghanistan</option>
                                <option value="2"> Aland Islands</option>
                                <option value="3"> Albania</option>
                                <option value="4"> Algeria</option>
                                <option value="5"> American Samoa</option>

When I select country on change I get value(numeric) send it to server and get States list that parse in States same happen with cities. After fill all fields, formData.serialized and send to server. Server get numeric id of country, state and city But I want send Name of country/state/ city. So before send I should change selected value to selected text(country name). I try change like that:

$("#countryId").change(function () {
 c.countrytxt = $(this).find("option:selected").text(); // get text from option
 var countryId = $("#countryId").val(); // save for send as paramet to server
 document.getElementById('countryId').value = c.countrytxt; // try set county name to value

How could I achieve it?


Solution

  • Please try this instead.

    $("#countryId").change(function () {
      // get text from option
      countrytxt = $(this).find("option:selected").text(); 
      // save for send as paramet to server
      var countryId = $("#countryId").val(); 
      // try set county name to value
      $(this).find("option:selected").attr('value',countrytxt);
     });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <select name="country" id="countryId" required="required"
    class="countries order-alpha form-control custom-select bg-white border-left-0 border-md">
      <option value="">Select Country</option>
      <option value="1"> Afghanistan</option>
      <option value="2"> Aland Islands</option>
      <option value="3"> Albania</option>
      <option value="4"> Algeria</option>
      <option value="5"> American Samoa</option>
    </select>