Anderson Gama
Anderson Gama

Reputation: 77

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("");
    }
});

Upvotes: 0

Views: 79

Answers (2)

Tony M
Tony M

Reputation: 741

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.

Upvotes: 1

Pavlo Zhukov
Pavlo Zhukov

Reputation: 3337

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

Upvotes: 2

Related Questions