FlyingCat
FlyingCat

Reputation: 14250

Prevent user from picking the default value in a dropdown menu

I am trying to prevent the user from picking the default dropdown menu option. Is there any way to add text instead of value in the dropdown menu option? My code:

<select name='test'>
<option value='default' selected='selected'>Please select the value</option>
<option value='value1'>value1</option>
<option value='value2'>value2</option>
</select>

I don't want the user to pick 'Please select the value' option. Is there better way to to this?

Upvotes: 3

Views: 8103

Answers (5)

VishVyavhare
VishVyavhare

Reputation: 1

When Using Html Helper,make value field of Select that is default value as empty

 @Html.DropDownListFor(Model => Model.Value, new List<SelectListItem>() { new SelectListItem { Text = "Select", Value = "" }, new SelectListItem { Text = "Value1", Value = "Value1" }, new SelectListItem { Text = "Value2", Value = "Value2" } }, new { @required = "required"})

Upvotes: 0

user1211577
user1211577

Reputation:

You can do

<option value='' disabled='disabled' selected='selected'>Please select the value</option>

I assume you're using some client-side validation to make sure that this option isn't selected on submit too? This will mean they can't select it once clicked off, but you'll need to validate it.

Something like

<script LANGUAGE="JavaScript">
<!-- 
    function ValidateForm(form){ 
    ErrorText= ""; 
    if ( form.test.selectedIndex == 0 ) {
         alert ( "Please select a value" ); 
         return false; 
    } 
    if (ErrorText= "") { 
        form.submit()
    } 
} 
-->
</script>

Then on your submit button

<input type="button" name="SubmitButton" value="Submit" onClick="ValidateForm(this.form)"> 

Upvotes: 3

No Results Found
No Results Found

Reputation: 102735

Client side code (javascript/HTML) is OK for this, but it's only half the battle.

Since you don't want the user to actually select this "default value", this is what I would do:

<option value=''>Please select the value</option>

Leve the value as an empty string. Then in your server side code, check if the value posted was empty or not. There's no point in populating an arbitrary default value if you aren't going to use it.

By default, the first <option> will be selected according to standard browser behavior, so you don't really need theselected attribute. You do need the value='' though or the browser can post the text content of the <option>.

Upvotes: 3

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114347

You can use JavaScript to check for the selected value when the user submits the form. If the value="default", warn the user.

Upvotes: 1

David Rasuli
David Rasuli

Reputation: 832

    <select name='test'>
<option value='default' selected='selected' enabled='false'>Please select the value</option>
<option value='value1'>value1</option>
<option value='value2'>value2</option>
</select>

Upvotes: 0

Related Questions