sanyogita sanyogita - 4 months ago 10
Javascript Question

Get an list of datas and store in array in jquery

I have a struture of html like below,This is what there will be list of option

<div class='col-sm-4'>
<div id='selectiondata' class="panel panel-default">
<div class="panel-body">
<h2 class='headerText'>Selections</h2>
<p style="font-size: 14px;">Select only that apply to you.</p>
<ul>
<li id="item1" data-cat="fruits">Banana</li>
<li id="item2" data-cat="fruits">Pineapple</li>
<li id="item3" data-cat="fruits">Oragne</li>
<li id="item4" data-cat="fruits">MAngo</li>
<li id="item5" data-cat="Vegetables">Beans</li>
<li id="item6" data-cat="fruits">jackfruit</li>
<li id="item7" data-cat="Vegetables">carrot</li>
</ul>
</div>
</div>
</div>


From above div when user clicks it moves to adjacent div,this has a sturcture like below.

<div id="categories" class="panel-default">
<div class="panel-body">
<div class="alert alert-info hidden endMsg">Your data categorized. Once done, click the next button to continue.</div>
<h2 class='headerText'>Categories</h2>
<ul>
<li id="cat-fruits">
<span>fruits</span>
<ul>
<li id="item5" data-cat="fruits">MAngo</li>
<li id="item1" data-cat="fruits">Banana</li>
<li id="item3" data-cat="fruits">Oragne</li>
<li class="no-expenses" style="display: none;">No items selected</li>
</ul>
</li>
<li id="cat-Vegetables">
<span>Vegetables</span>
<ul>
<li id="item4" data-cat="Vegetables">Beans</li>
<li class="no-expenses" style="display: none;">No items selected</li>
</ul>
</li>
<li id="cat-dolls">
<span>dolls</span>
<ul>
<li class="no-expenses">No items selected</li>
</ul>
</li>
<li id="cat-medical">
<span>Medical</span>
<ul>
<li class="no-expenses">No items selected</li>
</ul>
</li>
</ul>
</div>
</div>


jquery function to fetch array of data

function saveData() {
userData = [];
$('#categories ul li ul li.selected').each(function(index, element) {
if ($.inArray($(this).text(), userData) < 0) {
userData.push($(this).html());
}
});


I want to fetch datas like

[MAngo,banana,Oragne,beans]


Here i will be having two divs,one div shows list of selection as shown in below figure, when user click on particular elemnet, that elemnet will be moved to next adjacent div(categories).I want to get this datas.

----------- ----------
|Banana | | MAngo |
|Pineapple | | Banana |
|Oragne | | Oragne |
|MAngo | | Beans |
|Beans | |_________|
|jackfruit |
|carrot |
-----------


The above jquery used is not fetching any data from html, How could i acheive this. Please help me.

Answer

Would it be easier to add each item to the array when that item is clicked (and doesn't exist yet in the array)?

var arr = [];
$("#categories [id^=item]").click(function() {
   if(arr.indexOf($(this).html())<0) arr.push($(this).html());
})
console.log(arr);
Comments