简体   繁体   中英

How do I add a blank <option> element to a <option> list?

Situation:

I have an option list like

<select class="database-column-name" name="caseid">
     <option value="1">1</option> 
     <option value="2">1</option> 
     <option value="3">1</option> 
</select>

and by default there is no option selected, but when you select an option you can't go back to selecting none again! This messes up the user experience of my page because I need the user to be able to selected no option at all.

Question:

Is there a hack to get around this?

Is as simple as this

<select class="database-column-name" name="caseid">
<option value=" ">--Select--</option> 
     <option value="1">1</option> 
     <option value="2">1</option> 
     <option value="3">1</option> 
</select>
$("select.database-column-name option").prop("selected", false);

您可能有一个“清除选择”按钮,或者某些东西触发了此代码。

The preceding answer is a really good choice. The only recommendation that I would add to it is to make the value for the first item a "0"(zero), which allows your post-processing code to look for a specific value to ensure "no selection". Granted, you can look for " ", but that's easy to confuse with "".

<select class="database-column-name" name="caseid">
<option value="0">--Select--</option> 
<option value="1">1</option> 
<option value="2">1</option> 
<option value="3">1</option> 

If you want to have an actual blank show, rather than a phrase like "--Select--" then simply replace the "--Select--" text with a space.

<html>
<body>
<select class="database-column-name" name="caseid">
<option value="0"> </option>
<option value="1">option 1</option>
<option value="2">option 2</option>
<option value="3">option 3</option>
</select>

The "value" portion is not displayed and is present to simplify code-based analysis of the selected option. In this case, a value of "0" would mean that no option has been selected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM