Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery add a span class into a div

Tags:

html

jquery

ajax

I'm using jQuery in my app. My goal here is to display the validation errors next to the text field, but actually it replaces the div content.

<div class="control-group">
    <label class="control-label">Nom d'équipe</label>
    <div class="controls" id="nom_equipe">
        <input type="text" name="nom_equipe" value="" class="input-xlarge">                 </div>
</div>

So I retrieve the form errors with ajax and this is what i do :

if(data.validate == false)
{
    if(data.nom_equipe != '')
    {
        $("#nom_equipe").append("span").addClass("label label-important").text(data.nom_equipe);
    }
}

But it replaces the whole content of my div id=nom_equipe like this :

<div class="control-group">
    <label class="control-label">Nom d'équipe</label>
    <div class="controls label label-important" id="nom_equipe">Le champ Nom équipe est requis.</div>
</div>

Finally, this is what I wish to have :

<div class="control-group">
<label class="control-label">Nom d'équipe</label>
<div class="controls" id="nom_equipe">
    <input type="text" name="nom_equipe" value="" class="input-xlarge"> 
    <span>The field nom_equipe is required </span>
            </div>

PS : the content into span div comes from the ajax request.

like image 528
TLR Avatar asked Apr 07 '13 12:04

TLR


2 Answers

append("span") will not append a span element, just the text "span". To append a span element you need append('<span>').

Also the class will be added to the main element the way your code is written and the way jQuery works

Concatenating the html string with class and text included requires less function calls and is often less code than calling individual methods to create the element

$("#nom_equipe").append("<span class='label label-important'>"+data.nom_equipe+'</span>');

The main problem with your existing code is that even with the chaining used, the element that text() is being used on is still the original $("#nom_equipe"). text('text string') will replace all html within that element

like image 155
charlietfl Avatar answered Oct 10 '22 16:10

charlietfl


You need to use append() instead of text() if you want to retain the contents you already have.

$("#nom_equipe").append("<span class='label label-important'>" + data.nom_equipe + "</span>");

Append() inserts content, specified by the parameter, to the end of each element in the set of matched elements.

like image 44
Adil Avatar answered Oct 10 '22 17:10

Adil