Question

I've seen so many posts and examples of people using a DDL placeholder like this... @Html.DropDownList("lstUsers",(SelectList)ViewBag.UsersList, "--Select User--")

or

@Html.DropDownListFor(u => u.RoleID, Model.RoleList, "Select", new { @id="hi"})

I mean yea these work, but I want the placeholder to disappear after the ddl index changed, and all these do is place dummy text for the 1st index which can then be selected again. I haven't been able to find an answer for the life of me. I've tried jquery

$("#tb2").attr("placeholder", "--Please Select--"

which works for a textbox, but not a DropDown. I'm using dynamically generated ddl's

Thanks!

Was it helpful?

Solution

That's not how the select element works. That "placeholder" is actually a full-fledged option in the select list. It's value is usually set to an empty string so that if it's still selected on POST, an empty string is posted and will caused an error if the field is expected to have a value. It doesn't just disappear automatically on it's own.

A textbox is entirely different. When placeholder text is placed inside a textbox, it is literally overwritten by user input, hence why it goes away. In HTML5 textboxes now have an actual placeholder attribute, which will show and hide a bit of text based on the focus of the input. The select element has no equivalent, though.

You could potentially do what you want with some additional JavaScript. You would just watch for a change event on the select and if it has a value (not the "placeholder"), then you could remove the first item from the select (which should be the placeholder):

$('#mySelect').on('change', function () {
    if ($(this).val() != '') {
        var firstChild = $(this).children().eq(0);
        if (firstChild.prop('value') == '') firstChild.remove();
    }
});

(I'm using jQuery here because doing the same in straight JavaScript would be much more arduous and since you're using ASP.NET MVC, it's a safe bet you're also using jQuery)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top