Sort div array based on alphabets during appending Jquery - javascript

I am stuck in a place where I have to sort the list of names when moved those list on button click.
sort()
method works fine but clicking on the same button again creating duplicates!, which is not I need.
Is there any way I can fix this. used below code too(which took from stackoverflow) even this is not working.
function SortByName(a, b) {
var aName = a.name.toLowerCase();
var bName = b.name.toLowerCase();
return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
}
var selectArr = selectedList.sort(SortByName);
MY CODE
$(document).on('click', '#buttonAdd', function (e) {
var divCount = $('#SelectedEmployeeList').find('div').length;
if (divCount === 0) {
selectedList = []; // Clearing the list, to add fresh employee list.
}
$('#EmployeeList :selected').each(function (i, selected) {
selectedList[$(selected).val()] = $(selected).text();
});
// Returning DOM node from collection.
var empListNode = $("#SelectedEmployeeList")[0];
console.log(empListNode);
while (empListNode.firstChild) {
empListNode.removeChild(empListNode.firstChild);
}
for (var empID in selectedList) {
$("#SelectedEmployeeList").append("<div class= EmpList id=" + empID + ">" + selectedList[empID] + " <span class='close'>×</Span> </div>");
}
});
This is the place where all sort should happen #SelectedEmployeeList.
have shared the pics for references.
Sort is happening correctly on the left like here :
after clicking on "Add All >> " items are moved but not sorted :
any help will be appreciated.
UPDATE 1 :

This is your problem:
for (var empID in selectedList) {
$("#SelectedEmployeeList").append("<div class= EmpList id=" + empID + ">" + selectedList[empID] + " <span class='close'>×</Span> </div>");
}
For...in iterates over an object in no order. Save your employees in an array and iterate over it:
var selectedList = [];
$('#EmployeeList :selected').each(function (i, selected) {
// push an object into the selectedList array
selectedList.push({
empID : $(selected).val(),
text: $(selected).text(),
div: selected
});
});
// iterate over the array in order
for (var i = 0; i < selectedList.length; i++) {
// appends a NEW div
$("#SelectedEmployeeList").append("<div class= EmpList id=" + selectedList[i].empID + ">" + selectedList[i].text + " <span class='close'>×</Span> </div>");
// MOVES the div
$("#SelectedEmployeeList").append(selectedList[i].div);
}

Related

Get the value of a class when I check on a multiple options input

I want to get the value of team-id when I check it on a multiple options input and save this value on selectedTeams array
Common atributtes
teams: [],
selectedTeams: [],
Array teams get all teams on another function and works fine
I'm doing this function
GetSelectedTeams: function () {
var self = this;
var selected = $('input:checked').attr('team-id');
for (var i = 0; i < this.teams.length; i++) {
if (i == selected){
self.selectedTeams[i] = true;
}
}
var n = $('input:checked').length;
console.log("Selected Team is " + selected);
console.log("SelectedTeam length is " + self.selectedTeams.length);
console.log("Teams checked " + n);
}
The function trigger is
$('#teamsList').on('click','[id^=team]', function() {
this.GetSelectedTeams();
});
#teamsList is the list with all teams
<ul id="teamsList" style="list-style-type: none;">
And he will add with this structure that works fine
$('#teamsList').append('<li>\
<input type="checkbox" id="team' + item.Id + '" class="confirmCheckbox" team-id="' + item.Id + '" data-team-id="' + teamId + '" /> ' + item.teamName + '\
</li>\
');
Console shows the same team-id always, the lenght is always 2 and teams checked works fine.
You can get selected team id like this:
var selectedTeams=[];
$("input:checkbox").each(function(){
var $this = $(this);
if($this.is(":checked")){
selectedTeams.push($this.attr("data-team-id"));
}
});
here the variable selectedTeams will be having all teamid values for all of the checked checkboxes.

If-Else not working as expected if found matching element in array

I have a form where user can fill details and on clicking of add attendee button can add up to 9 people details. I am getting value of user name, selected checkbox item id and item quantity and storing inside array and passing these values in URL to add selected items and created user. On first click I'm checking if item is already there in array.
On first click I'm adding id's and quantity in array what I want to achieve is to increase quantity of that id which is already present in array, each time i click on this button it checks array and update quantity if its already present but its not working.
Here is my code
jQuery("#btnadd2").click(function() {
var qty;
var allVals = [];
var nameatt = jQuery("#txtAttendeeNames").val();
var nameatt= jQuery("#txtAttendeeNames").val();
var emattendee= jQuery("#txtAttendeeEmails").val();
var eventname = jQuery("#hdEventName").val();
var eventlocation = jQuery("#hdLocation").val();
jQuery(".big:checked").each(function() {
qty = parseInt(jQuery(this).parents().nextAll().children().find('input[name="quantity"]').val());
if (jQuery.inArray(jQuery(this).val(), allVals) == -1) {
allVals.push(jQuery(this).val()); //not present in array
} else {
qty = parseInt(jQuery(this).parents().nextAll().children().find('input[name="quantity"]').val() + 1);
}
});
for (var i = 0; i < allVals.length; i++) {
var rslt = allVals.join(',' + qty + ',' + 'custcol_name_of_attendees|' + nameatt + '||custcol_email_o f_attendees|' + emattendee + '||custcol_event_name|' + eventname + '||custcol_event_location|' + eventlocation + ';');
rslt1 = jQuery('#txtCntNameReg').val(rslt);
console.log(rslt1);
}
});
Try this line:
qty = qty + 1;
instead of this,
qty = parseInt(jQuery(this).parents().nextAll().children().find('input[name="quantity"]').val() + 1);
in else condition.

How to set the order of dropdown list items according to their ID numbers in GeoJSON properties

It is my fiddle: http://jsfiddle.net/anton9ov/d8yga33f/
I need to organize an order of items in my selector according to the ID numbers in the GeoJSON file. It is a part of my code where the items appear in the list:
map.on("layeradd", function(e) {
if(!e.layer.options) {
return;
}
if((e.layer.options.id != "markerLayer1") && (e.layer.options.id != "markerLayer2")) {
return;
}
var markers = e.layer.getLayers();
var mySelector = $("#mySelector");
for(var i = 0; i < markers.length; i++) {
mySelector.append("<option value='" + L.stamp(markers[i]) + "'>" + markers[i].feature.properties.name + "</option>");
}
});
Try using Array.prototype.sort():
map.on("layeradd", function(e) {
// ...
var markers = e.layer.getLayers();
// Get the dropdown
var mySelector = $("#mySelector");
markers.sort(function(a,b) {
// get the ids, and parse them as int
var aId = parseInt(a.feature.properties.id,10),
bId = parseInt(b.feature.properties.id,10);
return aId < bId ? -1 : aId > bId ? 1 : 0
}).forEach(function(marker) {
mySelector.append("<option value='"
+ L.stamp(marker) + "'>"
+ marker.feature.properties.id // I added the marker id
+ '. '
+ marker.feature.properties.name
+ "</option>");
})
});
See forked fiddle

Javascript won't filter eBay API results by price/listing type

After following eBay's API guidelines for displaying fixed price items that fall within a specified price range, results are still showing auction based items of varying prices outside the range. I followed their tutorial word for word, so I'm not sure what I'm doing wrong.
Code:
<div id="api"></div>
<script>
function _cb_findItemsByKeywords(root)
{
var items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
var html = [];
html.push('<table width="100%" border="0" cellspacing="0" cellpadding="3"><tbody>');
for (var i = 0; i < items.length; ++i)
{
var item = items[i];
var title = item.title;
var pic = item.galleryURL;
var viewitem = item.viewItemURL;
if (null != title && null != viewitem)
{
html.push(
'<tr id="api_microposts"><td>'
+ '<img src="' + pic + '" border="0" width="190">' + '<a href="' + viewitem + '" target="_blank">' + title +
'</a></td></tr>');
}
}
html.push('</tbody></table>');
document.getElementById("api").innerHTML = html.join("");
// Create a JavaScript array of the item filters you want to use in your request
var filterarray = [
{"name":"MaxPrice",
"value":"500",
"paramName":"Currency",
"paramValue":"USD"},
{"name":"MinPrice",
"value":"200",
"paramName":"Currency",
"paramValue":"USD"},
{"name":"FreeShippingOnly",
"value":"true",
"paramName":"",
"paramValue":""},
{"name":"ListingType",
"value":["FixedPrice"],
"paramName":"",
"paramValue":""},
];
// Define global variable for the URL filter
var urlfilter = "";
// Generates an indexed URL snippet from the array of item filters
function buildURLArray() {
// Iterate through each filter in the array
for(var i=0; i<filterarray.length; i++) {
//Index each item filter in filterarray
var itemfilter = filterarray[i];
// Iterate through each parameter in each item filter
for(var index in itemfilter) {
// Check to see if the parameter has a value (some don't)
if (itemfilter[index] !== "") {
if (itemfilter[index] instanceof Array) {
for(var r=0; r<itemfilter[index].length; r++) {
var value = itemfilter[index][r];
urlfilter += "&itemFilter\(" + i + "\)." + index + "\(" + r + "\)=" + value ;
}
}
else {
urlfilter += "&itemFilter\(" + i + "\)." + index + "=" + itemfilter[index];
}
}
}
}
} // End buildURLArray() function
// Execute the function to build the URL filter
buildURLArray(filterarray);
url += urlfilter;
}
</script>
<!--
Use the value of your appid for the appid parameter below.
-->
<script src=http://svcs.ebay.com/services/search/FindingService/v1?SECURITY-APPNAME=*App ID*&OPERATION-NAME=findItemsByKeywords&SERVICE-VERSION=1.0.0&RESPONSE-DATA-FORMAT=JSON&callback=_cb_findItemsByKeywords&REST-PAYLOAD&keywords=iphone%205%2016gb%20unlocked&paginationInput.entriesPerPage=3>
</script>
The specifications come from this page. I would tackle this problem in two steps:
Check to see if you get the same results even if you comment out this line:
url += urlfilter;
If that happens then your problem is the way you make the request and the parameters you set are not yet relevant. If it does change then the request is going through well enough and you need to fiddle what you pass in.
In that case the parameters need some fiddling. If you are getting any results then one issue could be with the ListingType filter. The specifications say that ListingType takes a string OR can take multiple values. It might be that you want to use:
{"name":"ListingType",
"value": "FixedPrice",
"paramName":"",
"paramValue":""}

how to do a search with an array

How could I do a search by name and surname with an array javascript?
and every time I search something that begins with je, div=result show me all Name and Surnames with Je in this case Jessica and Jey;
this would be a onkeydown event, right?
<input type='text' id='filter' placeholder='search in array'>
here I print the result:
<div id='result'></div>
this is my array :
var datos = [ ['Jessica','Lyn',3],
['Jhon','Cin',5],
['Alison','Peage',1],
['Thor','zhov',12],
['Jey','hov',32]
];
$("#filter").on('keyup', function () {
var val = $(this).val();
$("#result").empty();
$.each(datos, function () {
if (this[0].indexOf(val) >= 0 || this[1].indexOf(val) >= 0) {
$("#result").append("<div>" + this[0] + ' ' + this[1] + "</div>");
}
});
});
http://jsfiddle.net/MqTBm/
var $result = $('#result');
$('#filter').on('keyup', function () {
var $fragment = $('<div />');
var val = this.value.toLowerCase();
$.each(datos, function (i, item) {console.log( item[0].toLowerCase().indexOf(val) );
if ( item[0].toLowerCase().indexOf(val) == 0 ) {
$fragment.append('<p>' + item[0] + ' ' + item[1] + '</p>');
}
});
$result.html( $fragment.children() );
});
Here's the fiddle: http://jsfiddle.net/GkWGk/
The simple answer is to run a for loop over the array checking each element. However this is not a good idea if you have a large array. There are many ways to index an array. Thinking off the top of my head I might build a second array that stores the fields joined as one string as the index and then the array reference. So you can for loop through the reference object. Find the entry with string comparisons. Take the index reference to the real array.

Categories

Resources