I can't seem to be able to figure out as to why my array would have a trailing white space. The end result after building my array based on selected li items currently looks like this: 1234 ,0123
how can I get the output to be: 1234,0123
?
Here is the Code in question:
var arr_numbers = [];
window.onload = function() {
$(document).bind('click', function(e) {
var $clicked = $(e.target);
if (!$clicked.hasClass("select")) {
$(this).find('ul li').hide();
}
});
$(".select").click(function () {
$(this).find('ul li').toggle();
});
$(".select ul li").click(function(e) {
if (e.ctrlKey) {
e.stopPropagation();
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
}
else {
$(this).addClass('selected');
}
var c = $(this).parent().find("li.selected").length;
$(this).closest("div").contents().first()
.replaceWith((c > 1) ? "(" + c + ")" : $(this).text());
}
else {
$(this).closest("div").contents().first()
.replaceWith($(this).text());
var id = $(this).closest('[id]').attr('id');
$(this).closest('.select').find("ul li").removeClass('selected');
$(this).addClass('selected');
}
});
}
function get_data_array(element) {
if (element == 'numbers') {
var data_array_numbers = [];
var list = $("#numbers ul").find("li.selected")
$.each(list, function() {
//alert($(this).data('val'));
//alert($(this).text());
data_array_numbers.push($(this).text());
});
alert(data_array_numbers);
}
}
This is the HTML:
Numbers
<div class="select" id="numbers">
<ul>
<li> </li>
<li data-val="1234">1234</li>
<li data-val="5678">5678</li>
<li data-val="0123">0123</li>
</ul>
</div>
<br><br>
Letters
<div class="select" id="letters">
<ul>
<li> </li>
<li>abcd</li>
<li>efgh</li>
<li>ijkl</li>
</ul>
</div>
<br><br>
Fruits
<div class="select" id="fruits">
<ul>
<li> </li>
<li>apples</li>
<li>bananas</li>
<li>oranges</li>
</ul>
</div>
<br><br>
<input type="button" value="test" onclick="get_data_array('numbers')">