Get the correspoding values from CSV - javascript

I need to solve one issue regarding csv. I have read all the values from csv (I have three fields like region,state,acc_name) and loaded into corresponding dropdown list.but my issue is if i select the region i need to get the corresponding state values from csv I have done something but not even get any single line code please help me to do that task.
My code is:
$(document).ready(function() {
// AJAX in the data file
$.ajax({
type: "GET",
url: "data.csv",
dataType: "text",
success: function(data) {
processData(data);
}
});
// Let's process the data from the data file
function processData(data) {
var table = $("<table />");
var rows = data.split(/\r\n|\n/);
for (var i = 1; i < rows.length - 1; i++) {
var row = $("<tr />");
var cells = rows[i].split(/,(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/);
for (var j = 0; j < rows.length; j++) {
var cell = $("<td />");
cell.html(cells[j]);
row.append(cell);
}
var usedNames = {};
$("select[name='company1'] > option").each(function() {
if (usedNames[this.text]) {
$(this).remove();
} else {
usedNames[this.text] = this.value;
}
});
$("select[name='company2'] > option").each(function() {
if (usedNames[this.text]) {
$(this).remove();
} else {
usedNames[this.text] = this.value;
}
});
$("select[name='company3'] > option").each(function() {
if (usedNames[this.text]) {
$(this).remove();
} else {
usedNames[this.text] = this.value;
}
});
var newvalue = cells[1].replace("\"", "");
//var newvalue=cells[1].trim();
var final1 = newvalue.replace("\"", "");
var pandu = cells[0];
$("#region").append("<option value =" + cells[0] + "> " + cells[0] + " </option>");
$("#state").append("<option value =" + final1 + "> " + final1 + "</option>");
$("#accname").append("<option value =" + cells[2] + ">" + cells[2] + "</option>");
table.append(row);
}
}
});
function getstate()
{
...
}
HTML:
Region:
<select id="region" class="select" name="company1" onchange="getstate()"></select>
<br> State:
<select id="accname" class="select" name="company3"></select>
<br> Acct_Name:
<select id="state" class="select" name="company2"></select>
<br>

Related

How to append table row inside parent table after selecting dropdown list using JavaScript and Ajax?

I am creating a table using Ajax and JavaScript and using Spring Boot as a backend technology. So the scenario is:
There are two dropdowns one for selecting company name from list and with that company, corresponding truck list would be displayed. After selecting company name and truck from both the dropdowns, clicking on search button there would display a table with dynamic data of selected company and truck. So, for each created row there is select drop down in table row. So I want to display further data when selecting any of the option list from dropdown.
I want to display child row inside parent row after selecting any of the option from dropdown list using Ajax and JavaScript.
Below is my script where I am creating table with dynamic data:
function searchdata(){
var companyid = $("#searchQueryDD").val();
var truckid = $("#searchtruckdd").val();
var url = "api/gettablebycompanyandtruck";
$.post(url, {
companyid : companyid,
truckid : truckid,
limit : limit,
}, function(data, status) {
if (data.status == "OK") {
if (data.statusCode == 1) {
var list = data.response;
var row = "", tripnumber="";
var newtrip = [];
var uniquetrip = {};
var row = "";
if(list.length > 0){
for(var i = 0; i < list.length; i++){
tripnumber = list[i].tripnumber;
uniquetrip[tripnumber] = list[i];
}
for(var i in uniquetrip){
newtrip.push(uniquetrip[i]);
}
for(var i = 0; i < newtrip.length; i++){
row = row + "<tr>" +
"<td>"+newtrip[i].company.companyname+"</td>" +
"<td>"+newtrip[i].driver.username+"</td>" +
"<td>"+newtrip[i].truck.name+"</td>" +
"<td>"+newtrip[i].tripnumber+"</td>" +
"<input type='hidden' id='company_id' value='"+newtrip[i].company.companyid+"'>" +
"<input type='hidden' id='trip_number' value='"+newtrip[i].tripnumber+"'>"+
"<td><select onchange='getmorerows();' id='sub_trip'>" +
"<option selected disabled>Choose subtrip</option><option value='1'>1</option>" +
"<option value='2'>2</option><option value='3'>3</option></select></td>"+
"<td>"+newtrip[i].pickupdate+"</td>" +
"<td>"+newtrip[i].deliverydate+"</td>"+
"<td>"+newtrip[i].loadrate+"</td>" +
"<td>"+newtrip[i].dispatchfee+"</td>" +
"<td>"+newtrip[i].fuel+"</td>" +
"<td>"+newtrip[i].cardfee+"</td>" +
"<td>"+newtrip[i].onroadrepair+"</td>" +
"<td>"+newtrip[i].shoprepair+"</td>" +
"<td>"+newtrip[i].trailerrent+"</td>" +
"<td>"+newtrip[i].comcheck+"</td>" +
"<td>"+newtrip[i].advance+"</td>" +
"<td>"+newtrip[i].miscellenous+"</td>" +
"<td>"+newtrip[i].total+"</td>" +
"<td>"+newtrip[i].layover+"</td>" +
"<td>"+newtrip[i].grandtotal+"</td>" +
"<td>" +
"<a data-toggle='modal' data-target='#mode_payment' onclick=\"getpayment('"+newtrip[i].tripid+"');\">"
+"<i class='fa fa-paypal' aria-hidden='true' style='color:#3585a5'></i>" +
"</a>" +
"<a onclick=\"getTrip('"+newtrip[i].tripid+"');\">"
+"<i class='fa fa-pencil-square-o ml-3' style='color: #3384a4;'></i>" +
"</a>" +
"<a href='invoice?id="+newtrip[i].tripid+"'>"
+"<i class='fa fa-file-pdf-o ml-3' aria-hidden='true' style='color:red'></i>" +
"</a>" +
"</td>" +
"</tr>";
}
}else{
row = row + "<tr><td colspan='19' style='font-size: initial;font-family: initial;'>No Data Available.</td></tr>";
}
document.getElementById('searchresulttable').innerHTML = row;
$("#triptable").css('display','inline-block');
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
});
}
And below script is to handle onchange event on select options:
function getmorerows() {
var companyid = document.getElementById("company_id").value;
var tripnumber = document.getElementById("trip_number").value;
var subtrip = document.getElementById("sub_trip").value;
var url = "api/getbysubtrip";
$.post(url,{
companyid : companyid,
tripnumber : tripnumber,
subtrip : subtrip,
},function(data, status){
if (data.status == "OK") {
if (data.statusCode == 1) {
var list = data.response;
var childrow = "";
if(list.length > 0){
for(var i = 0; i < list.length; i++){
childrow = childrow + "<tr class='display-nonee'>" +
"<td>"+list[i].company.companyname+"</td>"+
"<td>"+list[i].company.companyname+"</td>"+
"<td>"+list[i].company.companyname+"</td>"+
"</tr>";
var tr = $(this).parent().parent().nextAll(':lt(2)');
if (tr.is(".display-none")) {
tr.removeClass('display-none');
} else {
tr.addClass('display-none');
}
}
}
document.getElementById('searchresulttable').innerHTML = childrow;
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
});
}
Change one line in getmorerows()
document.getElementById('searchresulttable').innerHTML = childrow; to $('#searchresulttable').append(childrow);

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?

jquery .grep is not removing array element

$(document).ready(function () {
var numbers = ['sachin', 'raaj', 'rahul', 'mahesh', 'sandip'];
$('#btn').click(function ()
{
var c = $("#ad_list option:selected").text();
numbers = jQuery.grep(numbers, function (value) {
return value != c;
}); >
});
var option = '';
for (i = 0; i < numbers.length; i++) {
option += '<option value="' + i + '">' + numbers[i] + '</option>'; >
}
$('#ad_list').append(option);
});
below is html code dropdownlist showing element in array
<label>ADD:</label>
<select name="ADD_list" id="ad_list"></select>
<input type="submit" id="btn" />
You need to update your option after removing the selected element:
function updateOption(numbers) {
$("#ad_list").empty();
var option = '';
for (i = 0; i < numbers.length; i++) {
option += '<option value="' + i + '">' + numbers[i] + '</option>';
}
$('#ad_list').append(option);
}
$(document).ready(function () {
var numbers = ['sachin', 'raaj', 'rahul', 'mahesh', 'sandip'];
$('#btn').click(function () {
var c = $("#ad_list option:selected").text();
numbers = jQuery.grep(numbers, function (value) {
return value != c;
});
updateOption(numbers);
});
updateOption(numbers);
});
Fiddle Demo

Adding a HREF to a JQuery Dynamically Populated Select

I have a form based menu which automatically populates the select options with the contents of a primary-nav UL. It wonderfully increments the with dashes reflecting the positions of the menu.
However, it doesn't populate the with the HREFs of the links within the ULs.
This is the code that I have:
<script>
$(function() {
var options = '<option selected></option>';
$('#primary-nav').find('a').each(function () {
var text = $(this).text(),
depth = $(this).parent().parents('ul').length,
depthChar = '',
i = 1;
for (i; i < depth; i++) { depthChar += '– ';
}
options += '<option>' + depthChar + text + '</option>';
});
$('<select id=\'mobile-menu\' />').append(options).appendTo('#mobile-nav');
$("#primary-nav select").change(function() {
window.location = $(this).find("option:selected").val();
});
});
</script>
I need to somehow add the below to the above so that when clicked the selected option goes to a url, and not a url based on the displayed value;
$("#primary-nav a").each(function() {
var el = $(this);
$("<option />", {
"value" : el.attr("href"),
"text" : el.text()
}).appendTo("#primary-nav select");
});
Can anyone advise me how I can do this?
Thank you.
You can just add the value attribute in your current code:
$('#primary-nav').find('a').each(function () {
var text = $(this).text(),
href = $(this).attr('href'),
depth = $(this).parent().parents('ul').length,
depthChar = '',
i = 1;
for (i; i < depth; i++) {
depthChar += '– ';
}
options += '<option value="'+href+'">' + depthChar + text + '</option>';
});
$('<select id=\'mobile-menu\' />').append(options).appendTo('#mobile-nav');

Categories

Resources