D Simm
D Simm

Reputation: 130

Jquery Issue in Appending Text to a label

I was doing validations for input fields using Jquery by just checking if a value is supplied for the fields or not.

In case there is NO value supplied, I just used to Append Text: "Duration:*Required" to the Field's "Label" controls as:

$('label[for="Duration_Value"]').Append(" Duration:* Required");

The problem is that for the very first time, if a user doesn't selects a value for the "Duration" dropdown, error message displays fine.

But, again , without selecting any value, if the Submit button is subsequently clicked, the Error Message: "Duration:* Required" keeps adding at end as seen below:

enter image description here

Which Jquery function shoul be used to change Text / error message displayed so that no matter how many times submit button clicked, Error message don't add up as above ?

Upvotes: 0

Views: 1035

Answers (2)

Sunil
Sunil

Reputation: 929

If value is not specified, then call this

 $('label[for="Duration_Value"]').text(" Duration:* Required");

and if value is specified then clear label text like this

$('label[for="Duration_Value"]').text("");

Upvotes: 0

Tushar
Tushar

Reputation: 87203

Use indexOf to check if the message is already added, if not then only add the message to the label.

if ($('label[for="Duration_Value"]').text().indexOf(" Duration:* Required") === -1) {
    $('label[for="Duration_Value"]').append(" Duration:* Required");
}

Upvotes: 1

Related Questions