Use jQuery to Change a Select Field to Different Value with the Text

At my job one of things I am working on allows the end-user to select a point on a map this changes the select fields on the page to be rebuilt and reflects the selected map point.

The issue that came up was that the map link uses string. While the ODATA service to popluate a select field uses an integer for the option taga value. But, the text in the option tag matches the link.

So, this code will show you how change the option tag of a select box if you only have the text value.

The Select Field

The filed thing needed is to build a select field. In this example we only need the text and not the value of the select options.


<label>Location</label>
<select id="alphabet">
  <option></option>
  <option>Alpha</option>
  <option>Beta</option>
  <option>Gamma</option>
  <option>Delta</option>
</select>

Javascript Function

The function below used jQuery’s $.each() to loop over all the option tag values for the select field and find the exact match. Once found we change the field option the one we are looking for and then use return false;to break out of the loop.


function changeLetter( L ) {
  $( "#alphabet option" ).each(
    function () {
      if ( L === $( this ).val() ) {
        $( "#alphabet" ).val( L ).change(); 
          return false;
        }
      }
    );
  }

Full Sample


<html>
  <head>
    https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js
	
      $( document ).ready(
        function() {
          $( "button" ).on(
            {
              "click" : function () {
                changeLetter( "Gamma" );
              }
            }
          );
        }
      );

      function changeLetter( L ) {
        $( "#alphabet option" ).each(
          function () {
            if ( L === $( this ).val() ) {
              $( "#alphabet" ).val( L ).change();

              return false;
            }
          }
        );
      }
    
  </head>
  <body>
    <label> Location </label>
    <select id="alphabet">
      <option></option>
      <option>Alpha</option>
      <option>Beta</option>
      <option>Gamma</option>
      <option>Delta</option>
    </select>

    <button id="changeToGamama">Change Select Option to Gamma</button>
  </body>
</html>