davecove
davecove

Reputation: 1071

How do I clear a text EditorFor

I have an element on a Razor page like this:

<td>
    <div class="col-md-12">
        @Html.EditorFor(model => model.FreeTextName, new { htmlAttributes = new { @class = "form-control" } })
    </div>
</td>

When the page first renders it has hint text in it like 'Enter name to search for here'

I would like for this text to disappear when the user clicks into the field so I wrote a little script like this:

<script type="text/javascript">
    $('#FreeTextSwitchId').focusin(
        $('#FreeTextName').val("")
        )
</script>

But now my page renders with the hint test gone. I know it is the script doing it because if I do something like this: $('#FreeTextName').val("test") then 'test' shows up instead of the hint text.

What am I doing wrong here?

Upvotes: 0

Views: 3120

Answers (4)

Syed Muhammad Zeeshan
Syed Muhammad Zeeshan

Reputation: 1045

Use your @Html.EditorFor() like that:

@Html.EditorFor(model => model.FreeTextName, new { @class = "form-control" })

Now you have given a class in your @Html.EditorFor() i.e .form-control. Use your class in your script. Do the script like that:

<script type="text/javascript">

    $('.form-control').on('blur click', function(){ 
        $(this).val("");
    });

</script>

Moreover you can also use placeholder="Your Hint" attribute in your @Html.EditorFor() i.e:

@Html.EditorFor(model => model.FreeTextName, new { @class = "form-control", placeholder="Enter name to search for here" })

It is an html input type="textbox" attribute that automatically adds default text to textbox as default hint so that the user can understand what should be given in this textbox. For this you don't need to use any script.

Hope this helps.

Upvotes: 2

davecove
davecove

Reputation: 1071

I actually decided to go with the top answer in MVC4 input field placeholder since I was using MVC4:

Upvotes: 0

Travis Pettry
Travis Pettry

Reputation: 1352

You should add a placeholder into the input. Here's an example: http://jsfiddle.net/naeqgnd3/

<input placeholder="'Enter name to search for here" />

The text will disappear when the user types in the input.

Upvotes: 0

lem2802
lem2802

Reputation: 1162

are you trying to do a watermark??? you can use the "placeholder" attribute in HTML5

 <input placeholder="example text" type="text" />

Upvotes: 0

Related Questions