99

There can be many options in a SELECT dropdown.

<select id="sel">
    <option value="car">1</option>
    <option value="bike">2</option>
    <option value="cycle">3</option>
    ...
</select>

I'm creating a Update Profile page where a user's profile is retrieved from the database and a form is shown with those values. When it comes to SELECTdropdown, there are many options. So, its tedious test all values

if (value == '1')
    echo "<option selected value='car'>1</option>";`

So, I want to have the corresponding option selected from its value. Like when I do something like sel.value = 'bike' using JavaScript the option 2 should be selected.

2
  • 3
    Are you sure value="car" and the text is 1, and not the other way around? Is the <select> code static, or dynamically created from something like a database? Commented Sep 4, 2012 at 14:28
  • You want to select this with the serverside? Why no serverside tag? Commented Sep 4, 2012 at 14:30

5 Answers 5

149

You can select the value using javascript:

document.getElementById('sel').value = 'bike';

DEMO

Sign up to request clarification or add additional context in comments.

5 Comments

Remember: you may use sel.value = 'bike' instead of document.getElementById('sel').value
@EduardoXavier, if you first run 'var sel = document.getElementById('sel');', then yes, you can. Otherwise, no, you can't. If the element only has id, the only way is to get the element first. However, if it has the name attribute and it is inside a form, you can use formelement.sel.value. w3.org/TR/html5/forms.html#the-form-element and w3.org/TR/html5/forms.html#dom-form-nameditem
@DenilsonSá This question is about the use of the "id". What you said about form and names is rigth but you're completly wrong when you say I can't access an element in the way I proposed. Let us do some practice then, have a look at here jsfiddle.net/tub6f0Lg :P cheers!
@EduardoXavier: I stand corrected, you are right! Thanks for pointing it out! :) w3.org/TR/html5/browsers.html#named-access-on-the-window-object However, although handy, relying on IDs being available as global variables because of window object may lead to messy and unreadable code. Consider another developer (maybe even yourself after a while) reading the code.
40

If you are using jQuery:

$('#sel').val('bike');

Comments

14

try out this....

JSFIDDEL DEMO

using javascript

​document.getElementById('sel').value = 'car';​​​​​​​​​​

using jQuery

$('#sel').val('car');

Comments

0
document.getElementById('drpSelectSourceLibrary').value = 'Seven';

1 Comment

Answer needs supporting information Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
0

Not defined option values

Setting the <select> value directly by value property can also set non-defined option values.

Since the idea of a select is to pass a value from a predefined set of "allowed" option values – setting a non-existent option value may lead to errors.

To prevent this, we should also check whether the option value exists.

// add a prototype method
HTMLSelectElement.prototype.setSelectValue = function (value) {
  return setSelectValue(this, value)
};


// check whether the option value or label exists
function setSelectValue(selectEl, value) {
  let hasValue = false
  const options = [...selectEl.options]
  let hasOptionValue = options.find(option => option.value === value);
  let hasOptionLabel = !hasOptionValue ? options.find(option => option.label === value) : null;
  
  if (hasOptionValue || hasOptionLabel) {
    if(hasOptionValue){
      selectEl.value = value;
    }
    else if(hasOptionLabel){
      selectEl.value = hasOptionLabel.value;
    }
    hasValue = true;
  }
  return hasValue;
}




// demo example
const select = document.getElementById('select')

let btns = document.querySelectorAll('button')
btns.forEach(btn=>{
  btn.addEventListener('click', e=>{
    result.textContent = '';
    let value = e.currentTarget.dataset.val;
    //let hasValue = setSelectValue(select, value);   
    let hasValue = select.setSelectValue(value)   
    if(!hasValue){
      result.textContent = `value does not exist – fallback: »${select.value}«`
    }
  })
})
<select  id="select">
  <option value="1">1</option>
  <option value="2" selected>2</option>
  <option value="3">3</option>
  <option value="valuecasesensitive" >ValueCaseSensitive</option>
  <option >Only Label</option>
</select>
<p>
  <button type="button" data-val="1">1</button>
  <button type="button" data-val="2">2</button>
  <button type="button" data-val="3">3</button>
  <button type="button" data-val="ValueCaseSensitive">ValueCaseSensitive</button>
  <button type="button" data-val="Only Label">Only Label</button>
  <button type="button" data-val="Non-existent">Non-existent</button>
</p>

<p id="result" style="color:red"></p>

The above example also adds more tolerance in case the value and label are different and the input value to find might be the label text.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.