Reputation: 23
I have a large section of select tags, where I use jQuery to show the user an overview of his selections. This works perfectly, except for the fact that my code doesn't only show my last selection. So if i change my selection, the previous selections remain in the overview and my new selection gets listed below.
Here I've changed my selection several times, and they all get listed. I only want to show my most recent selection (For each select tag)
Here is my script;
$(document).ready(function () {
$('#SORTERING select').change(function() {
label = $(this).closest("p").prev().find('label').html();
content = $(this).find('option:selected').text();
$('#OutputTXT').append('<p><b>' +label+ ': </b>' +content+ '</p>');
});
});
What do I need to do to fix this problem? Thanks for any help!
Here's the HTML for the select
tag, as requested:
<div id="SORTERING">
<p class="chck">
<input type="checkbox" id="c4" name="cc"/>
<label for="c4"><span></span>Avtale</label>
</p>
<p class="select">
<select id="s4" name="s4">
<option value="blank"></option>
<option value="salgge">DB Salg GE</option>
<option value="salgkin">DB Salg KIN</option>
<option value="salghk">DB Salg HK</option>
<option value="nei">DB Nei</option>
<option value="samf">DB Samfakturering</option>
<option value="eksge">DB Kunder GE</option>
<option value="ekshk">DB Kunder HK</option>
<option value="ekskin">DB Kunder KIN</option>
<option value="del">Slett</option>
<option value="forward">Viderefør</option>
<option value="liste1">HK Nordland</option>
<option value="liste2">Kveldsliste</option>
<option value="addlist">Legg til liste</option>
</select>
</p>
</div>
Upvotes: 2
Views: 57
Reputation: 337560
Instead of using append()
(as this will create a new element on each selection) use html()
as this will over-write the value each time:
$('#OutputTXT').html('<p><b>' + label + ':</b> ' + content + '</p>');
i want it to show one line for each selection instead of replacing it
In this case the logic becomes more complex as you need to check if a p
exists for the chosen select and if so update it, otherwise create it. Something like this:
$('#SORTERING select').change(function() {
label = $(this).closest("p").prev().find('label').html();
content = $(this).find('option:selected').text();
var $p = $('#output_' + this.id);
if (!$p.length)
$p = $('<p id="output_' + this.id + '"></p>').appendTo('#OutputTXT');
$p.html('<b>' + label + ': </b>' + content);
});
Upvotes: 1