0

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.

1 Answer 1

8

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".

Sign up to request clarification or add additional context in comments.

3 Comments

Although, if you're really itching to use vanilla JavaScript to set the value: $("#Field").get(0).value = ""; -- but that's a little silly.
@andytuba Not sure if that comment came before or after one of my edits, but I do include that. But I definitely agree. It's really unnecessary to do that. It's either stick with all vanilla or all jQuery
I put it in just before your edit. I was entertained when I saw the notification that "This answer has been edited" and up popped the same code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.