liste de tags avec ajout
by ydelmas
HTML
<form action="http://azrael.sha.univ-poitiers.fr/~ydelmas/2012-m2-php/info-max.php" target="_blank">
<div id="tags">
<span class="tag">
<input name="tags[]" type="text" /><span class="retirer"><img src="http://azrael.sha.univ-poitiers.fr/~ydelmas/2012-m2-js/briques/cross.png" /></span>
</span>
</div>
<div>
<button id="ajoutTag" type="button">ajouter</button>
<button id="delTag" type="button">retirer</button>
</div>
</form>
CSS
input[type=text] { font: 14px Verdana, Geneva, sans-serif; width: 6em; }
#tags input[type=text] {
height: 24px; padding: 2px; vertical-align: middle; margin-right: 0;
background-color: #CCF;
border-width: 2px 0 2px 2px; border-style: solid; border-color: #009; border-radius: 5px 0 0 5px;
}
#tags input[type=text]:focus { background-color: #EEE; }
#tags .retirer {
display: inline-block; height: 24px; padding: 2px; vertical-align: middle; margin-left: 0;
background-color: #FCC;
border-width: 2px 2px 2px 0; border-style: solid; border-color: #009; border-radius: 0 5px 5px 0;
}
JavaScript
/* suppression du dernier tag */
$('#delTag').click(function () {
$('#tags > :not(:first-child):last-child').remove();
});
/* création d'un tag supplémentaire */
$('#ajoutTag').click(function () {
var nouveauTag = $('#tags > :first-child').clone();
nouveauTag.find('input').val('');
nouveauTag.appendTo('#tags');
nouveauTag.find('input').focus();
/* les 3 dernières lignes peuvent s'écrire :
nouveauTag.appendTo('#tags').find('input').val('').focus();
*/
});
/* fonction de suppression d'un tag par sa croix */
function retirerTag() {
if ( $('#tags > *').length == 1) {
$(this).parent().find('input').val('').focus();
} else {
$(this).parent().remove();
}
}
/* initialisations */
// 1) mettre le curseur (focus) dans le dernier tag
$('#tags:last-child input').focus();
// 2) associer les croix à la fonction "retirerTag"
$('#tags').on('click', '.retirer', retirerTag);