chris chris - 4 months ago 6x
jQuery Question

jQuery select option code efficiency

I have a select dropdown that I want to prepopulate with values from a separate hidden input field.

Example: a person comes to a form with a set hidden input value - if that value matches a value in the dropdown, that option is selected.

The code below works great, but I'm curious if it possible to make it shorter/more efficient? Like with variables? So I don't have to repeat for each option? That would come in handy in the case of a large dropdown like for States that has 50 options with values. I'm still learning...thanks! I hope my question is clear.

$(document).ready(function () {
"use strict";
if ($("input[name='Job Title']").val() === "Job 1") {
$("#job_title option[value='Job 1']").prop("selected", true);
else if ($("input[name='Job Title']").val() === "Job 2") {
$("#job_title option[value='Job 2']").prop("selected", true);
else if ($("input[name='Job Title']").val() === "Job 3") {
$("#job_title option[value='Job 3']").prop("selected", true);
else if ($("input[name='Job Title']").val() === "Job 4") {
$("#job_title option[value='Job 4']").prop("selected", true);

CODEPEN: codepen

 $("#job_title option[value='" + $("input[name='Job Title']").val() + "']")
 .prop("selected", true);