0

I have a select element of the form:

<select id="test" name="test">
<option value="blah">Test1</option>
<option value="blah">Test2</option>
.
<option value="blah">Testn</option>
</select>

I want to display the text "Select a test" as default. I know the way of doing this is to set a new option

<option selected="selected">Select a test</option>

at the top. But I'm looking for some other way where I don't have to use the tag. Is it possible through javascript (jQuery will also do)?

3
  • You can access options array and the prepend your options arreay with the new option Element. Commented Jan 3, 2013 at 16:25
  • Reason for not adding a new option element ? Commented Jan 3, 2013 at 16:35
  • The problem is that the value from this select is sent to multiple php scripts which is coded by someone else. He hasn't added checks for empty or null values and I would have to change a lot of code. Commented Jan 3, 2013 at 16:58

2 Answers 2

1

I've done this with a dummy entry in the past...

HTML

<select id="test" name="test">
    <option value="0">Select an option...</option>
    <option value="blah">Test1</option>
    <option value="blah">Test2</option>
    <option value="blah">Test3</option>
    <option value="blah">Test4</option>
    <option value="blah">Test5</option>
</select>​

Javascript

​$("#test").on("change", function() {
    if ($(this).val() != "0") {
        $("option[value=0]", this).remove();
    }
});​​​​​​

Here's a working example on jsFiddle...

http://jsfiddle.net/97Bqr/

The "Select an option" option is removed as soon as you select something else.

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

Comments

1

Here's a plain js solution:

var selecttest = document.querySelector('#test');
selecttest.insertBefore(new Option('select a test'),selecttest.firstChild);
selecttest.selectedIndex = 0;

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.