Clear text field value in JQuery

2019-01-23 10:38发布

I understand this is an easy question but for some reason this just isn't working for me. I have a function that is triggered everytime a drop down menu is changed. Here is the relevant code that is suppose to grab the current value of the text field, if a value exists, clear it that is contained within the .change function:

var doc_val_check = $('#doc_title').attr("value");
    if (doc_val_check.length > 0) {
        doc_val_check == "";
    }

I feel like I am missing something very simple.

14条回答
贼婆χ
2楼-- · 2019-01-23 10:52

    First Name: <input type="text" autocomplete="off" name="input1"/>
    <br/>
    Last Name: <input type="text" autocomplete="off" name="input2"/>
    <br/>
    <input type="submit" value="Submit" />
</form>

查看更多
女痞
3楼-- · 2019-01-23 10:54

You are comparing doc_val_check with an empty string. You want to assign the empty string to doc_val_check

so it should be this:

doc_val_check = "";

查看更多
欢心
4楼-- · 2019-01-23 10:55

you can clear it by using this line

$('#TextBoxID').val("");
查看更多
Rolldiameter
5楼-- · 2019-01-23 10:59
doc_val_check == "";   // == is equality check operator

should be

doc_val_check = "";    // = is assign operator. you need to set empty value

                       // so you need =

You can write you full code like this:

var doc_val_check = $.trim( $('#doc_title').val() ); // take value of text 
                                                     // field using .val()
    if (doc_val_check.length) {
        doc_val_check = ""; // this will not update your text field
    }

To update you text field with a "" you need to try

$('#doc_title').attr('value', doc_val_check); 
// or 
$('doc_title').val(doc_val_check);

But I think you don't need above process.


In short, just one line

$('#doc_title').val("");

Note

.val() use to set/ get value in text field. With parameter it acts as setter and without parameter acts as getter.

Read more about .val()

查看更多
欢心
6楼-- · 2019-01-23 11:00

If you are using jQuery, then you can use this:

// var doc_val_check = $('#doc_title').val(); - No need of this!
if ($('#doc_title').val().length > 0) {
    $('#doc_title').val("");
}
查看更多
老娘就宠你
7楼-- · 2019-01-23 11:02

Use jQuery.prototype.val to get/set field values:

var value = $('#doc_title').val();    // get value
$('#doc_title').val('');    // clear value
查看更多
登录 后发表回答