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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With