简体   繁体   中英

jQuery - Clear input text field that contains a specific text

I have some form fields that get the text "Required" when the user clicks on submit button without filling them, and I'm trying to clear them when the user clicks on the text field that has the text "Required". The problem is that the text field is being cleaned with any kind of text.

Thanks in advance for any further help.

This is an example of what I have:

//Submit button click event
$("#form_button").click(function() 
{
    if(checkEmptyFields())
    {
        alert("OK");
    }
});

//Checks the fields emptiness
function checkEmptyFields()
{   
    if(!$("#text_field1").val())
    {
        $("#text_field1").val("REQUIRED");
    }
}

//Input text click event 
$("#text_field1").click(function()
{
    if($("#text_field1").val("REQUIRED"))
    {
        $("#text_field1").val("");
    }
});

Your need to get field value and compare it with that value:

//Input text click event 
$("#text_field1").click(function()
{
    if($("#text_field1").val() == "REQUIRED")
    {
        $("#text_field1").val("");
    }
});

Your code just rewrite it

Instead of setting the value to required, why don't you set the placeholder attribute instead? Something like this:

 //Input text click event $("#text_field1").click(function() { if($("#text_field1").attr("placeholder") != "Required") { $("#text_field1").attr("placeholder","Required"); } }); 

Something like that will make it easy for users to navigate the field. Once they start typing, the placeholder disappears. Plus the browser will be handling that for you.

Alternatively you can set the required attribute and check for it instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM