broguyman
broguyman

Reputation: 1426

Clear text of a Html.TextBoxFor with Javascript or JQuery

I can't seem to figure out how to clear the text from a razor Textbox.

I've tried this:

@Html.TextBoxFor(m => m.Field)


    $(document).ready(function () {
        $(".link").click(function () {                
            $("#Field").value = "";
            return false;
        });    
    });

Didn't work.

Upvotes: 0

Views: 11743

Answers (1)

Ian
Ian

Reputation: 50905

The correct way to SET the value with jQuery is to use val and pass it a value. So to clear it, use this:

$("#Field").val("")

Look at the jQuery API for val:

http://api.jquery.com/val/

If you wanted to use basic Javascript, you use .value = "", but since you are selecting an element with jQuery, you must use jQuery methods, like val.

You have several options though. This is similarly very easy with basic Javascript:

document.getElementById("Field").value = "";

If you still wanted to use jQuery but use value, you need to get the DOM element, like:

$("#Field")[0].value = "";
// or
$("#Field").get(0).value = "";

If you are using jQuery, you might as well stick with val(). The nice thing with this is that calling .val("") will not bomb the program if the element isn't found. If you use any of the other methods I mentioned, they will bomb if the element doesn't exist. So it's up to you what you really want. You can always check to see if $("#Field").length is greater than 0 before using get(0) or [0], but that's kind of overkill.

Another possible problem is that the id of the element may not be "Field". I forget what MVC does to generate the actual HTML, but it's up to you to use something like Firebug or Developer Tools to investigate and see what the id actually is. Then, you may have to replace it for "Field".

Upvotes: 8

Related Questions