Removing a "default" <option> in a select box

Here is my select box:

<select id="category">
   <option value="">Pick a choice!</option>
   <option value="">choice1</option>
   <option value="">choice2</option>
   <option value="">choice3</option>
   <option value="">choice4</option>
</select>

I want the Pick a choice! option to be removed when the user click on the select box. If the user click anywhere else, the Pick a choice! option come back. I don't want the user to be able to pick the Pick a choice! option. What should I do?


Without some PHP or JavaScript to remove the option dynamically you do have another very simple option that I use regularly, this is the disabled="disabled" option. The option will remain but the user won't be able to actually select it.

The failure with this is if someone just submits a form without choosing anything the empty value will submit in the form, but this is where your validation handling comes into play.

Your code for the "Pick a choice!" option will look something like this:

<option disabled="disabled">Pick a choice!</option>

I hope it helps.


CSS Only Sol'n


So, I know this post is quite old now, but a css only solution wasn't offered... Much more efficient way of accomplishing this. Notice the first <option> doesn't have a value attribute; this allows it to effectively placehold.

#category:focus option:first-of-type {
    display: none;
}
<select id="category">
   <option>Pick a choice!</option>
   <option value="choice1">choice1</option>
   <option value="choice2">choice2</option>
   <option value="choice3">choice3</option>
   <option value="choice3">choice4</option>
</select>

Here is some workaround. Don't know wether this is suite your requirement.

<html>
<head>
<title>Untitled Document</title>
<script>
function doremove()
{

    var obj=document.getElementById("category");
    obj.remove(0);  
}

function addOpt()
{
var obj=document.getElementById("category");
var option=document.createElement("option");
option.text="Pick a choice!";
option.value = 0;
obj.add(option,1);
obj.value = 0;
}
</script>
</head>

<body>
<select id="category" onfocus="doremove();" onblur="addOpt();">
   <option value="0">Pick a choice!</option>
   <option value="">choice1</option>
   <option value="">choice2</option>
   <option value="">choice3</option>
   <option value="">choice4</option>
</select>
<input type="text" />
</body>
</html>
链接地址: http://www.djcxy.com/p/70604.html

上一篇: Python具有多个参数括号

下一篇: 在选择框中删除“默认”<选项>