How to add multiple variables in .val() jquery function - javascript

I am adding data using AJAX then appending that data in dropdown, after that I am using .val().trigger() jQuery function to get that newly added data on the top of drop down by passing multiple variables in .val() function; val function is accepting one variable and working fine but I want to add multiple variables in val() function.
JS CODE
success: function(data) {
toastr['success']("<?php echo lang('add'); ?>", "Customer Device Added");
setTimeout(function() {
const obj = JSON.parse(data);
// console.log(data)
// console.log(obj)
jQuery('#customer_device').append('<option value="' + obj[0].device_brand + ' ' + obj[0].device_model + ' ' + obj[0].device_imei + '">' + obj[0].device_brand + ' ' + obj[0].device_model + ' ' + obj[0].device_imei + '</option>');
jQuery('#customer_device').val(obj[0].device_brand).trigger("change");
$('#customer_device_modal').modal('hide');
}, 500);
}
Here I am appending these data:
obj[0].device_brand, obj[0].device_model, obj[0].device_imei
I want to trigger these all variables in .val() function to get these in dropdown at top; as I am getting one variable in val function. Thank you

Related

I passed product name in onclick() function using jquery? but error

output += '<td class="cart-product-edit"><i class="fa fa-plus"></i></td>';
function SaveCart(cartid) {
var URL = "<?php echo site_url();?>";
var userid = "<?php echo $this->session->userdata('userid');?>"
var data = {
userid: userid
};
$.ajax({
url: URL + 'cart/SaveCart/' + cartid,
data: data,
type: 'POST',
dataType: 'json',
success: function(result) {}
});
}
Error:(console) (bag is productname)
cart:1 Uncaught ReferenceError: bag is not defined
at HTMLAnchorElement.onclick (cart:1)
There are two problems. The first is with this line:
onclick="SaveCart(' + element.CardID + ',' + element.ProductName + ')"
Your element.ProductName is presumably a string (named, in this case Bag) and that is causing your error.
You need to surround the string elements of your onclick with quotes:
onclick="SaveCart(' + element.CardID + ', \'' + element.ProductName + '\')"
The second issue is that SaveCart is defined with only a single parameter:
function SaveCart(cartid) {
You are actually passing two parameters to it, the CardID and the ProductName.
Maybe you don't need to pass the product name at all, in which case your onclick becomes:
onclick="SaveCart(' + element.CardID + ')"
Or you need to add the second parameter to SaveCart:
function SaveCart(cartid, productName) {
From the error message it appears that the issue is because element.CardID and element.ProductName are strings, yet you have not wrapped them in quotes in the HTML output. You need to escape the quotes you wrap them in so that they don't break the syntax:
output += '<td ... onclick="SaveCart(\'' + element.CardID + '\',\'' + element.ProductName + '\')" ... </td>';
You also need to amend SaveCart to accept both arguments:
function SaveCart(cartid, productname) {
// your logic here...
}
However a much better approach would be to get rid of the outdated on* event attributes and to attach your events unobtrusively. Then you can use data attributes to store the metadata in the element. Given you're already using jQuery, it can be done like this:
var element = {
CardID: 'abc123',
ProductName: 'Lorem ipsum'
}
let output = `<td class="cart-product-edit"><i class="fa fa-plus">Click me</i></td>`;
$('table tr').append(output);
$('table').on('click', '.product-edit', function() {
let $a = $(this);
let cardId = $a.data('cardid');
let productName = $a.data('productname');
console.log(cardId, productName);
// send your AJAX here...
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table><tr></tr></table>

How to iterate multiple json data in jquery response

I am getting multiple data from my JSON response like below.
WellNames […]
0 {…}
id 56
well_name AL HALL
api 34005205550000
1 {…}
id 498
well_name BONTRAGER
api 34005233850000
2 {…}
id 499
well_name BONTRAGER
api 34005233860000
I just want to iterate all data and append in select box having id result
i tried below code but getting undefined value in select tags.Please help me to display this values in my select tag.
Below is my jquery code
<script type="text/javascript">
$("#clientname").on('change', function() {
ajaxRequest = $.ajax({
url: '<?= Router::url(['controller' => 'Orders', 'action' => 'getWelldetails']) ?>',
type: 'POST',
data: {clientId: $("#clientname").val()},
dataType: "json",
success: function(response) {
$(response).each(function () {
$("<option value='" + response['id'] + "'>" + response['well_name'] + "</option>").appendTo('#result');
});
},
error: function(response) {
}
});
});
</script>
You need to loop through the WellNames property of your result, not on your result itself.
Also, you're not using jQuery each properly. Either use $.each or use a for loop:
for(let item of response.WellNames) {
$("<option value='" + item.id + "'>" + item.well_name + "</option>").appendTo('#result');
}
Yes its done from below changes which i forgot to write
$(response.WellNames).each(function (i,value) {
$("<option value='" + value['id'] + "'>" + value['well_name'] + " - " + value['api'] + "</option>").appendTo('#result');
});
You need iterate on *WellNames* property of your response.
Use hasOwnProperty so that you don't iterate on undefined property.
I will not suggest to add elements directly to control in a loop. So create an array containing html of and then add it to the control.
var arrHtml = [];
for (var item of response.WellNames) {
if (response.WellNames.hasOwnProperty(item)) {
arrHtml.push("<option value='" + item.id + "'>" + item.well_name + "</option>");
}
}
$('#result').innerHtml = arrHtml.join();

How to pass/generate table with parameters from one page to another

Hi i having a scenario where i am generating a dynamic table along with the dynamic button and when ever user clicks that button it has to get that row value and it has generate another dynamic table by taking this value as parameter .Till now i tried generating a dynamic table and with button and passed a parameter to that function here i stuck how to pass /accept a parameter to that function so that by using ajax call it can generate another dynamic table.
$.ajax({
type: 'GET',
url: xxxx.xxxxx.xxxxx,
data: "Id=" + clO + Name_=" + cl+ "",
success: function (resp) {
var Location = resp;
var tr;
for (var i = 0; i < Location.length; i++) {
tr = tr + "<tr>
tr = tr + "<td style='height:20px' align='right'>" + Location[i].Amount + "</td>";
tr = tr + "<td style='height:20px' align='right'>" + Location[i].Name + "</td>";
tr = tr + '<td><input type="button" class="nav_button" onclick="test(\'' + Location[i].Amount + '\',\'' + Location[i].Name + '\')"></td>';
tr = tr + "</tr>";
};
document.getElementById('d').style.display = "block";
document.getElementById('Wise').innerHTML = "<table id='rt'>" + "<thead ><tr><th style='height:20px'>Amount</th>" + "<th style='height:20px'>Name</th>""</tr></thead>"
+ tr + "<tr><td align='left' style='height:20px'><b>Total:"+ TotBills +"</b></td><td style='height:20px' align='right'><b></b></td></tr>" +
"</table>";
document.getElementById('Wise').childNodes[0].nodeValue = null;
},
error: function (e) {
window.plugins.toast.showLongBottom("error");
}
function test(value,val1,val2) {
navigator.notification.alert(value + ";" + val1 + ";" + val2);
// here i have to pass the another ajax by basing on the the onclick
}
so here in the function i have to pass the parameters and have to display in the new page and how is it possible ?
To pass data from a page to another your best bet is localStorage and SessionStorage;
SessionStorage - Similar to a cookie that expires when you close the browser. It has the same structure as the localStorage, but there is no way to change its permanence time, whenever closing will be deleted.
LocalStorage - This is similar to a cookie, but it never expires, so while there were records in the AppCache for that domain, the variable will exist (unless the user creates a routine to remove it).
Both attributes were added by HTML5. The above items called web storage. But there are other forms of local storage through HTML5, such as WebSQL database, Indexed Database (IndexDB), as well as conventional files (File Access).
Ex:
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
Is it what you meant ?
It's unclear what you're after, but I think I see where you're headed. From the code you included, it seems like you want something like this instead:
// This will take the user to a separate page, passing your parameters
function test(val1,val2) {
window.location.href("/UrlGoesHere?Amount=" + val1 + "&Name=" + val2);
}
Another option, based on what you've said, is to redraw the table. You could do that with something like this:
function test(val1,val2) {
$.ajax({
type: 'GET',
url: "/UrlGoesHere",
data: "Amount=" + val1 + "&Name=" + val2,
success: function (resp) {
// redraw table here
}
});
}

TypeError: a is undefined in jquery at the first line?

So, in my code, when I press my #jsonclick button, it activates my script which populates a table with information from a JSON page. The problem I am having is that I am getting a TypeError: a is undefined, and I have no idea why.
Here is my code:
jQuery function
$("#clickjson").click(function () {
$.getJSON("gmessagegroup.php?gid=" + $('#gbox').val(), function (data) {
$.each(data.messages, function (key, val) {
if (data.messages[key].clientmessageid != undefined) {
console.log(data.messages[key].clientmessageid + ":" + data.messages[key].from + " - " + data.messages[key].content);
$("#messages tbody tr:last").after('<tr><td>' + data.messages[key].clientmessageid + '</td><td>' + escapeHtml(data.messages[key].from).replace("https://bn1-client-s.gateway.messenger.live.com/v1/users/ME/contacts/8:", "") + '</td><td id=' + data.messages[key].clientmessageid + ' contenteditable="true">' + escapeHtml(data.messages[key].content) + '</td></tr>');
}
});
});
setTimeout(function () {
var message_status = $("#status");
$("td[contenteditable=true]").blur(function () {
var field_userid = $(this).attr("id");
var value = $(this).text();
$.post('groupedit.php', field_userid + "=" + value, function (data) {});
});
}, 1000);
});
The code is getting the value of the selected item in a dropdown select. I tried putting and alert in and it is putting out the correct value that is being pushed out to the PHP. I am unsure of where the TypeError comes into play, all I know is that when I remove ?gid=" + $('#gbox').val() from the end of the php, the error goes away. Problem is, I need that for the php to work. Can somebody please tell me why this is happening?
Thanks.
Actually in your json response messages is not found thats why it is responding as a is undefined check if you json data has messages or not like,
if(data && data.messages.length) // check for messages
$.each(data.messages, function (key, val) {
if (data.messages[key].clientmessageid != undefined) {
...
}
});
}
Snapshop

Concat parameter syntax

Not sure how to even ask the question, if any suggestions for the title please let me know...
I have the following function that retrieves via AJAX information of a JSON file. This function as you can see below:
setOptionsSettings("[data-machine-brand-options]", apiUrlMachineBrands, 'name');
function setOptionsSettings(htmlElement, url, apiParameter) {
$.ajax({
dataType: "json",
url: url,
// CREATE GENERIC SOLUTION for the spinner
beforeSend: function(xhr) {
$('main').html('<div class="spinner"><div class="hori-verti-centering"><div class="bounce bounce1"></div><div class="bounce bounce2"></div><div class="bounce bounce3"></div></div></div>');
setHeader(xhr);
},
success: function (data) {
$.each(data, function(i) {
$(htmlElement).append("<option id=" + data[i].id + " value=" + data[i].apiParameter + ">" + data[i].apiParameter + "</option>");
});
}
});
return {};
}
I'm trying to set apiParamter so when you call the function setOptionSettings you can place the name of the parameter you need to call. So in this case the parameter is name. How can I insert this into the function so it works?
I tried the following and other solutions but nothing would work, any suggestions?
$(htmlElement).append("<option id=" + data[i].id + " value=" + data[i]. + apiParameter + ">" + data[i]. + apiParameter + "</option>");
To access object property using string key use Bracket notation i.e data[i][apiParameter]
As you are using jQuery create element using it.
$(htmlElement).append($('<option></option>', {
"id": data[i].id,
"value": data[i][apiParameter]
}));

Categories

Resources