How do I programmatically set the value of a selection box element using JavaScript?

I have the following HTML < Select > elements:

<select id="leaveCode" name="leaveCode">
  <option value="10">Annual Leave</option>
  <option value="11">Medical Leave</option>
  <option value="14">Long Service</option>
  <option value="17">Leave Without Pay</option>
</select>

Using JavaScript functions with the leaveCode number as the parameter, how do I choose the appropriate option in the list?

#1 building

I compared different methods:

Compare how to use JS or jQuery to set the select value

Code:

$(function() {
    var oldT = new Date().getTime();
     var element = document.getElementById('myId');
    element.value = 4;
    console.error(new Date().getTime() - oldT);


    oldT = new Date().getTime();
    $("#myId option").filter(function() {
        return $(this).attr('value') == 4;
    }).attr('selected', true);
    console.error(new Date().getTime() - oldT);


    oldT = new Date().getTime();
    $("#myId").val("4");
    console.error(new Date().getTime() - oldT);


});

Output of select with ~ 4000 elements:

1 milliseconds

58 milliseconds

612 milliseconds

Use Firefox 10. Note: the only reason I did this test was because jQuery performed poorly on our list, with about 2000 entries (long text between options). There is a delay of about 2 seconds after val()

Also note: I set values based on actual values rather than text values

#2 building

If you use PHP, you can try the following:

$value = '11';
$first = '';
$second = '';
$third = '';
$fourth = '';

switch($value) {
            case '10' :
                $first = 'selected';
            break;
            case '11' :
                $second = 'selected';
            break;
            case '14' :
                $third = 'selected';
            break;
            case '17' :
                $fourth = 'selected';
            break;
        }

echo'
<select id="leaveCode" name="leaveCode">
  <option value="10" '. $first .'>Annual Leave</option>
  <option value="11" '. $second .'>Medical Leave</option>
  <option value="14" '. $third .'>Long Service</option>
  <option value="17" '. $fourth .'>Leave Without Pay</option>
</select>';

#3 building

I tried the above solution based on JavaScript / jQuery, for example:

$("#leaveCode").val("14");

and

var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;

In the AngularJS application, there are necessary < Select > elements.

None of them worked because AngularJS form validation was not triggered. Although the correct option is selected (and displayed as a table), the input is still invalid (the ng pristine and ng invalid classes still exist).

To force AngularJS validation, please call jQuery after selecting an option. change() :

$("#leaveCode").val("14").change();

and

var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
$(leaveCode).change();

#4 building

You are most likely to want to:

$("._statusDDL").val('2');

Or

$('select').prop('selectedIndex', 3); 

#5 building

If you are using jQuery, you can also do the following:

$('#leaveCode').val('14');

This selects < option > with a value of 14.

Using pure Javascript, you can also use the following two methods Document method To achieve:

  • Use document.querySelector , you can select an element based on the CSS selector:

    document.querySelector('#leaveCode').value = '14'
  • Use a more mature approach document.getElementById() , as the function name implies, lets you select an element based on its id:

    document.getElementById('leaveCode').value = '14'

You can run the following code snippet to see these methods and the actual jQuery functions used:

const jQueryFunction = () => { $('#leaveCode').val('14'); } const querySelectorFunction = () => { document.querySelector('#leaveCode').value = '14' } const getElementByIdFunction = () => { document.getElementById('leaveCode').value='14' }
input { display:block; margin: 10px; padding: 10px }
<select id="leaveCode" name="leaveCode"> <option value="10">Annual Leave</option> <option value="11">Medical Leave</option> <option value="14">Long Service</option> <option value="17">Leave Without Pay</option> </select> <input type="button" value="$('#leaveCode').val('14');" onclick="jQueryFunction()" /> <input type="button" value="document.querySelector('#leaveCode').value = '14'" onclick="querySelectorFunction()" /> <input type="button" value="document.getElementById('leaveCode').value = '14'" onclick="getElementByIdFunction()" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Keywords: JQuery Javascript AngularJS Firefox

Added by bugcoder on Sat, 22 Feb 2020 10:08:26 +0200