Janey
Janey

Reputation: 1310

Jquery add text to <label class='error'> dynamically

I'm trying to produce an error message that displays in <label for='withold' class='error'></label> but I can't figure out how to put the data into that label that has the class 'error'. I've tried the following:

if ($("label[for='withold']").hasClass( "error" ) ){
     $(this).text(data);
}

and

$("label[for='withold']").hasClass( ".error" ).text(data);

Any ideas?

EDIT: Data is filled using .ajax success function:

 $.ajax({
    type: "POST",
    url: "page.php",
    data: datastring,
    cache: false,
    dataType: "text",
    success:  function(data)
    {
        if (data.indexOf("Error") > -1) {
              $("label[for='withold']").hasClass( ".error" ).text(data);
        } else {}
       }
        });  // end $.ajax

Upvotes: 0

Views: 182

Answers (3)

martincarlin87
martincarlin87

Reputation: 11042

You could do

$("label[for='withold'].error").text(data);

https://jsfiddle.net/vbbyyvpL/

Upvotes: 0

Cl&#225;udio Barreira
Cl&#225;udio Barreira

Reputation: 459

Do it like this:

$("label.error[for='withold']").text(data);

https://jsfiddle.net/00fo9pq6/1/

Upvotes: 2

Richard Hamilton
Richard Hamilton

Reputation: 26434

Try using filter

$("label[for='withold']").filter( ".error" ).text(data);

Upvotes: 1

Related Questions