splitting item in jQuery - javascript

Original Example
Failed Example
Here's the returned data:
var availableTags = [
'ActionScript|AppleScript|Asp',
'BASIC',
'Clojure|C++|C|COBOL|ColdFusion',
'Erlang',
'Fortran',
'Groovy',
'Haskell',
'Java|JavaScript',
'Lisp',
'Perl|PHP|Python',
'Ruby',
'Scala|Scheme',
];
How can I split the items into arrays during the renderItem function,and when users type PHP it will only return PHP from 'Perl|PHP|Python'?
Here's my code:
$('#tags').autocomplete({
source: availableTags,
search: function(event, ui) {
$('#wrapper').empty();
},
})
.data('autocomplete')._renderItem = function(ul, item) {
return $('<div class="element"></div>')
.data('item.autocomplete', item)
var smallchoice = item.label.split('|');
$.each(smallchoice,function(j,smallchoice){
$option = '<a href="#" >' + smallchoice+ '</a>'
})
.append($option)
.appendTo($('#wrapper'));
};

Here is an example of what you trying to do.
.data('autocomplete')._renderItem = function(ul, item) {
var inp = $("#tags").val();
var items = item.label.split("|");
for (var i = 0; i < items.length; i++) {
index = items[i].toUpperCase().indexOf(inp.toUpperCase());
if (index == 0 || index > 0) {
item = items[i];
return $('<div class="element"></div>')
.data('item.autocomplete', item)
.append('' + item + '')
.appendTo($('#wrapper'));
}
}
};
JSFiddle

Related

Change Ajax Post parameters & returned HTML based on alternating dependant dropdowns

I have 3 dropdowns containing values that are populated on page load
<select class='form-control' id='make' placeholder='Make:'>
<select class='form-control' id='model' placeholder='Model:'>
<select class='form-control' id='version' placeholder='Version:'>
I have a function that updates the values in the 'other' dropdowns that aren't clicked, based on the value of the dropdown that is clicked - but I have this function repeated 3 times, for each dropdown
$('#model').change(function(){
let selectedModel = $(this).val();
$.ajax({
url: 'php/dropdown.php',
type: 'POST',
data: {model: selectedModel},
success:function(data)
{ $('#make').html('');
$('#version').html('');
let makeJSON = JSON.parse(data)[0];
let versionJSON = JSON.parse(data)[2];
for (let i = 0; i < makeJSON.length; i++) {
if (makeJSON[i].mMake!= '' && makeJSON[i].mMake!= null) {
$('#make').html($('#make').html() + '<option value="' + makeJSON[i].mMake + '">' + makeJSON[i].mMake + '</option>');
}
}
for (let i = 0; i < versionJSON.length; i++) {
if (versionJSON[i].mVersion != '' && versionJSON[i].mVersion != null) {
$('#version').html($('#version').html() + '<option value="' + versionJSON[i].mVersion + '">' + versionJSON[i].mVersion + '</option>');
}
}
}
});
});
And the PHP looks something like this:
$model = $_REQUEST['model'];
$sqlupdateModel = "SELECT DISTINCT mMake, mVersion FROM Cars WHERE mModel = '$model';
$stmtModel = sqlsrv_query( $conn, $sqlupdateModel);
if( $stmtModel === false)
{
die( print_r( sqlsrv_errors(), true));
}
$updateModel = [];
while( $row = sqlsrv_fetch_array( $stmtModel, SQLSRV_FETCH_ASSOC)){
$updateModel[] = $row;
}
echo json_encode(array($updateMake, $updateModel, $updateVersion));
...and this all works fine,
Basically, I'm looking for a simpler solution for reusing the function (both JS & PHP) instead of rewriting it 3 times!
In terms of what I have attempted,
$('#make, #model, #version').change(function(){
let columnValue = $(this).val();
.......
data: {model: columnValue},
success:function(data)
{$(this).html(''); //this doesn't work obviously!
After this I'm snookered
This one should work for JS side, you will have to check mapping function for response
$('#make, #model, #version').change(function(ev){
let selected = $(this).val();
let id = ev.target.id;
let data = {};
data[id] = selected;
$.ajax({
url: 'php/dropdown.php',
type: 'POST',
data: data,
success:function(data)
{
let options = ['make', 'model', 'version']
const response = {
make: JSON.parse(data[0].map(make => make.mMake)),
model: JSON.parse(data[1].map(make => make.mModel)),
version: JSON.parse(data[2].map(make => make.mVersion))
}
options.filter(option => option !== id).forEach(option => setDropdown(option, response[option]));
}
});
});
function setDropdown(id, data) {
const id = `#${id}`
$(id).html('');
for (let i = 0; i < data.length; i++) {
if (data[i] != '' && data[i] != null) {
$(id).html($(id).html() + '<option value="' + data[i] + '">' + data[i] + '</option>');
}
}
}

Count the results returned in an AJAX call from selected parent

My first pop up list distinct customers with distinct cust_id from the AJAX call. I'm trying to get the count of the number of rows with cust_id that are the same as the selected customer.
For example: If I select "Jeffs Music" from the distinct list I need the count to return 5 since there are 5 rows that cust_id = "15"
$('.add-invoice').live('click', function() {
$("#invoice_div").css("display", "block");
$.ajax({
url: 'invoice_fill.php',
data: {
action: "invoice"
},
dataType: 'json',
success: function(data) {
var result = [];
$.each(data, function(i, e) {
var matchingItems = $.grep(result, function(item) {
return item.customer === e.customer && item.cust_id === e.cust_id;
console.log(item.cust_id);
});
if (matchingItems.length === 0) {
result.push(e);
}
});
var xyz = (JSON.stringify(result));
console.log(xyz);
populateSelectBoxes($('#invoice_div #ddinvoice'), result);
function populateSelectBoxes($select, result) {
var invoices = [];
$.each(result, function() {
invoices.push('<li data-value="' + this.cust_id + '">' + this.customer + ' : ' + this.invoice + '</li>');
});
$select.append(invoices.join(''));
}
function populateTableRow(data, selectedProductAutonum) {
var invoices;
$.each(result, function() {
if (this.cust_id == selectedProductAutonum) {
invoices = this;
var arr = this.cust_id;
var occurrences = {};
for (var i = 0, j = arr.length; i < j; i++) {
occurrences[arr[i]] = (occurrences[arr[i]] || 0) + 1;
}
console.log(occurrences);
return false;
// changed autonun to cust_id to give unique record/product call (changed in line 248 as well)
}
});
$(".item-row:last").after(
'<tr class="item-row"><td class="item-name"><div class="delete-wpr"><textarea form ="testinsert" name="item_name[]">Item Name</textarea><a class="delete" href="javascript:;" title="Remove row">X</a><a class="add-product" href="javascript:;" title="Add Product">A</a></div></td><td class="description"><textarea form ="testinsert" name="item_desc[]">Description</textarea></td><td><textarea class="cost" form ="testinsert" name="item_cost[]">$0</textarea></td><td><textarea class="qty" form ="testinsert" name="item_qty[]">0</textarea></td><td><span class="price" form ="testinsert" name="item_price[]">$0</span></td></tr>');
if ($(".delete").length > 0) $(".delete").show();
bind();
$('#address-title').val(invoices.customer);
$('#address-one').val(invoices.address);
//$('#address-two').val(invoices.sales + '\n' + invoices.owed);
//$('#address-three').val(invoices.address3);
///////////////////////////////////////////
$('#invoice_num').val(invoices.invoice);
$('#paid').val(invoices.paid);
$('#owed').val(invoices.sales);
$('#auto_num').val(invoices.autonum);
///////////////////////////////////////////
$('[name="item_name[]"]').val(invoices.product);
$('[name="item_desc[]"]').val(invoices.description);
$('[name="item_cost[]"]').val(invoices.cost);
$('[name="item_qty[]"]').val(invoices.quantity);
$('[name="item_price[]"]').val(invoices.price);
}
$('#invoice_div #ddinvoice li').click(function(e) {
var selection = $(this).attr("data-value");
$(this).parent().parent().parent().hide();
populateTableRow(data, selection);
$('ul').empty();
});
}
});
update_total();
});
Look at this jsFiddle for full code. That should be clear, however the AJAX calls are not working in it?

Break a JSON string intro ordered list by category

I'm trying to get a JSON object into a unordered list by Continent then country.
JSON looks like:
var mylocations = '{
"Locations":[
{"Place":"Africa_Egypt"},
{"Place":"Africa_SouthAfrica"},
{"Place":"Africa_SouthAfrica"},
{"Place":"Africa_SouthAfrica"},
{"Place":"Americas_Brazil"},
{"Place":"Americas_Canada"},
{"Place":"Americas_USA"},
{"Place":"Europe_Switzerland"},
{"Place":"Europe_UK"}
]
}';
Here's what I have so far:
arr = $.parseJSON(mylocations);
var continent = {},
country;
$.each(arr.Locations, function( i, el ) {
var ul = $('<ul></ul>');
country = el.Place.substr(0, el.Place.indexOf("_"));
if (continent.hasOwnProperty(country)) {
continent[country] += 1;
children = $('<li>' + country + '</li>');
children.appendTo('ul')
}
else {
$('#country-list').append(ul);
continent[country] = 1;
}
});
// print results
for(var key in continent){
console.log(key + ' (' + continent[key] + ')');
}
What I'm after is:
<ul>
<li>
Continent
<ul>
<li>Country</li>
<li>Country</li>
</ul>
</li>
<li>
Continent
<ul>
<li>Country</li>
<li>Country</li>
</ul>
</li>
</ul>
Struggling to get this working. Here's what I have so far:
jsfiddle
Any help would be appreciated.
Here's my solution. It's not the best, but I hope it's not the worst :D
For any question/complain I'm here. Hope it helps
console.log(arr)
var ul = $('<ul></ul>');
var mylocations = '{"Locations":[{"Place":"Africa_Egypt"},{"Place":"Africa_SouthAfrica"},{"Place":"Africa_SouthAfrica"},{"Place":"Africa_SouthAfrica"},{"Place":"Americas_Brazil"},{"Place":"Americas_Canada"},{"Place":"Americas_USA"},{"Place":"Europe_Switzerland"},{"Place":"Europe_UK"}]}';
var arr = $.parseJSON(mylocations);
var locations = {}
$.each(arr.Locations, function( i, el ) {
var delimiter = el.Place.indexOf("_");
var continent = el.Place.substr(0, delimiter);
var country = el.Place.substr(delimiter+1, el.Place.length);
locations[continent] = locations[continent] || []
locations[continent].push(country)
});
for(var continent in locations) {
$('<li>' + continent + '</li>').appendTo(ul)
var continentUL = $('<ul></ul>');
for(var countryIndex in locations[continent]) {
$('<li>' + locations[continent][countryIndex] + '</li>').appendTo(continentUL)
}
continentUL.appendTo(ul)
}
ul.appendTo($('#country-list'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="country-list">
</div>
Here's my approach:
var htmlResult = "<ul>";
var parsedLocations = {};
// Regroup object by continents containing array of countries
$.each(myLocations.Locations, function( index, value) {
var temp = value.Place.split("_");
var continent = temp[0];
var country = temp[1];
if(!parsedLocations[continent]) {parsedLocations[continent] = [];}
parsedLocations[continent].push(country);
});
// Loop through each continent, and
$.each(parsedLocations, function(continent, countries) {
htmlResult += "<li>" + continent + "<ul>";
// Iterate through each country within the continent
$.each(countries, function(index, country) {
htmlResult += "<li>" + country + "</li>";
});
htmlResult += "</ul></li>";
});
htmlResult += "</ul>";
I have forked your jsfiddle and updated it here
May you find this useful :)

Update totals in a table

I have:
$('#createStockOrder').click(function () {
modal('create-stock-order', {}, function () {
var $modal = $(this);
var submitted = false;
var model = [];
$('.glyphicon-plus').click(function () {
var product_id = $('#productSelect option:selected').text(),
size_id = $('#sizeSelect option:selected').text(),
colour_id = $('#colourSelect option:selected').text(),
quantity = $('#quantity').val();
// Get index of the element where all the fields matches
var index = getObjectIndex(model, product_id, size_id, colour_id);
// If object found in the array
if (index !== false) {
// Update the quantity in the same element
model[index].quantity = quantity;
} else {
// Add the element in the array
model.push({
product_id: product_id,
size_id: size_id,
colour_id: colour_id,
quantity: quantity
});
}
printStock(model);
});
var form = document.getElementById('create_sale');
var $form = $(form);
$form.on('submit', function (e) {
e.preventDefault();
if (!submitted) {
submitted = true;
$('#create_sale .btn-primary').addClass('disabled');
var formData = new FormData(form);
qwest.post(form.action, formData)
.then(function (resp) {
$modal.modal('hide');
})
.catch(function (xhr, response, e) {
var html = '';
$.each(response, function (i, v) {
html += '<p>' + v + '</p>';
});
$('#create_sale .alert').html(html).removeClass('hide');
$('#create_sale .btn-primary').removeClass('disabled');
submitted = false;
});
}
})
}, {width: 1000});
});
// Currently the function is Static, but it can be changed to dynamic
// by using nested loop and a flag to store the match status
function getObjectIndex(arr, product_id, size_id, colour_id) {
// Loop over array to find the matching element/object
for (var i = 0; i < arr.length; i++) {
var obj = arr[i];
if (obj.product_id === product_id && obj.size_id === size_id && obj.colour_id === colour_id) {
// When all key-value matches return the array index
return i;
}
}
// When no match found, return false
return false;
}
function printStock(model) {
var html = '';
var total_row_quantity = 0;
var total_row_value = 0;
$.each(model, function (i1, v1) {
html += '<tr>';
$.each(v1, function (i2, v2) {
html += '<td>' + v2 + '</td>';
$('#product_totals tr').each(function(i3, v3){
var product_code = $('td', v3).eq(0).html();
if(product_code == v2) {
total_row_quantity += parseInt(model[i1].quantity);
total_row_value += parseFloat($('td', v3).eq(2).html()*model[i1].quantity);
$('td', v3).eq(1).html(total_row_quantity);
$('td', v3).eq(3).html(accounting.formatMoney(total_row_value, ''));
} else {
total_row_quantity = 0;
total_row_value = 0;
}
})
});
html += '</tr>';
});
$('#stock_order tbody').html(html);
}
The HTML is:
<tbody id="product_totals">
<tr data-id="1">
<td>JW1501</td>
<td class="code-quantity-total">0</td>
<td>79.00</td>
<td class="code-cost-total">0</td>
</tr>
<tr data-id="2">
<td>JW1502</td>
<td class="code-quantity-total">0</td>
<td>99.00</td>
<td class="code-cost-total">0</td>
</tr>
<tr data-id="3">
<td>JW1501-1</td>
<td class="code-quantity-total">0</td>
<td>20.00</td>
<td class="code-cost-total">0</td>
</tr>
<tr data-id="4">
<td>JW1502-2</td>
<td class="code-quantity-total">0</td>
<td>25.00</td>
<td class="code-cost-total">0</td>
</tr>
</tbody>
The list of rows (JW1501, JW1502) is dynamic.
The problem I am having is that if a variant of e.g. JW1502 is added, only the total quantity and value is calculated for that one. Any previous different variants of JW1502 are ignored.
How can I fix this?
Example content of var model:
[
{"product_id":"JW1501","size_id":"70A","colour_id":"小豹纹","quantity":"1"},
{"product_id":"JW1501","size_id":"75B","colour_id":"小豹纹","quantity":"2"},
{"product_id":"JW1502","size_id":"85A","colour_id":"黑色","quantity":"1"}
]
The above for JW1501 would show the incorrect quantity of 2, not 3.
...
$('#product_totals tr').each(function (i3, v3) {
console.log(v1, v2, v3)
...
Outputs:
Object {product_id: "JW1501", size_id: "70A", colour_id: "小豹纹", quantity: "2"}
"JW1501"
<tr data-id=​"1">​<td>​JW1501​</td>​<td class=​"code-quantity-total">​2​</td>​<td>​79.00​</td>​<td class=​"code-cost-total">​158.00​</td>​</tr>​
I have completely changed your printStock function to achieve your goal:
function printStock(model) {
$("#product_totals tr").each(function(){
var id = $("td:eq(0)", this).text().trim();
var price = parseFloat($("td:eq(2)", this).text());
var count = 0;
$.each(model, function(i, item){
if (item.product_id == id) count += (+item.quantity);
});
$("td:eq(1)", this).text(count);
$("td:eq(3)", this).text((count * price).toFixed(2));
});
var rows = $.map(model, function(item){
return [
"<td>" + item.product_id + "</td>",
"<td>" + item.size_id + "</td>",
"<td>" + item.colour_id + "</td>",
"<td>" + item.quantity + "</td>"
].join("");
});
var html = "<tr>" + rows.join("</tr><tr>") + "</tr>";
$('#stock_order tbody').html(html);
}
The main difference is that my code groups items in model by product_id for further counting.
Also refer my fiddle.

Data not being stored in variable

I'm trying to add data to an empty var, but data is not getting stored.
When calling hotel_list, it shows empty. What am I missing? Thanks!
var hotelData = JSON.parse(data);
function hotelList(){
var hotel_list = '';
for (i = 0; i < hotelData.length; i++) {
function list(index, hotel) {
hotel_list += '<li class="hotel" data-index="'+ index +'">'+ hotel.name +'</li>';
document.getElementById("hotel-listing").innerHTML = hotel_list;
};
};
};
document.addEventListener('DOMContentLoaded', function() {
hotelList();
});
var data = '[{"name": "h1"}, {"name": "h2"}]';
var hotelData = JSON.parse(data);
function hotelList(){
var hotel_list = '';
(hotelData || []).forEach(function (hotel, index) {
hotel_list += '<li class="hotel" data-index="'+ index +'">'+ hotel.name +'</li>';
});
document.getElementById("hotel-listing").innerHTML = hotel_list;
};
document.addEventListener('DOMContentLoaded', function() {
hotelList();
});
<div id="hotel-listing"></div>

Categories

Resources