I have some javascript that takes user input, queries an endpoint with that input via ajax, and returns a field from the results as an appended <option> to a datalist. This is working properly and I see exactly what I need in the options list.
The next portion I've worked on is that when I click the option, I want other fields related to it in the object to populate the value of a form input. I've got this all structured but when I click an item it says result is not defined
in this line:
$("#groupName").val(result[$(foundOption).attr('srindex')]._source.name);
So my options are correct, and when I click an option it reflects the clicked option in the console. The issue is that I'm not passing the result into my else if correctly, apparently.
The heirarchy of my _source is correct but I just don't know how I need to change my .val argument in order to pull the right value.
Any ideas?
$('#productInput').on('input', function () {
let _this = $(this);
let foundOption;
let optSelector = `option[value='${_this.val()}']`;
if (_this.val() === '') {
return;
} else if ((foundOption = $('#returnedProducts').find(optSelector)).length) {
console.log(optSelector); //this prints the option[value] of the clicked value as it should
$("#groupName").val(result[$(foundOption).attr('srindex')]._source.name);
$("#groupNum").val(result[$(foundOption).attr('srindex')]._source.code);
} else {
const searchResult = $(this).val();
$.ajax({ url: '/account/autocomplete',
data: {
search_result:searchResult
},
"_token": "{{ csrf_token() }}",
type: "POST",
success: function (response) {
console.log(response);
console.log(searchResult);
$("#returnedProducts").empty();
let result = response.hits.hits;
console.log(result);
for(let i = 0; i < result.length; i++) {
$("#returnedProducts").append("<option srindex=" + [i] + " value=" + result[i]._source.name + ">" + result[i]._source.name + "</option>");
}
}
});
}
});
Update:
my object looks like this
hits
hits
_source
name
code
fiddle http://jsfiddle.net/qhbt569o/8/
Working example.
You've just to change _source by source inside the loop like :
for (let i = 0; i < result.length; i++) {
$("#returnedProducts").append("<option srindex=" + [i] + " value=" + result[i].source.name + ">" + result[i].source.name + "</option>");
}
Related
I have an ajax call that is returning me the data to be populated in a drop down list. Now, I need to be able to select a value which is returned and set the value of the drop down in the same function if possible. But by using $("#idOfDropDown").val(data), it is not getting set i.e While I am submitting the data, in the database all the options that were returned and populated are getting submitted and not the selected option. So, How do I set the selected value only?
Here's my AJAX function:
$.ajax({
type: "POST",
dataType: 'json',
url: "/Controller/Action",
data: {
param: param,
},
success: function(data) {
if (data.Response == "Unsuccessful") {
console.log("Unsuccessful");
} else if (data.Response == "Successful" || data.Response == "ConditionallySuccessful") {
for (var i = 0; i < data.ExteriorColor.Data.length; i++) {
$("#Exterior_Color").append($("<option></option>").val(data.ExteriorColor.Data[i]).html(data.ExteriorColor.Data[i]));
console.log(data.ExteriorColor.Data[i]);
}
var html = '<ul>'
for (var i = 0; i < data.Options.length; i++) {
html += '<li>' + data.Options[i] + '</li>';
}
html += '</ul>'
$("#twoColumnOptions").append(html);
$("#twoColumnOptions").data(html);
$("#Options").val(data.Options);
$("#Exterior_Color").val(data.ExteriorColor.Data).change(); //Value to be changed
if (data.ExteriorColor.isInstalled == true)
$("#Exterior_Color").attr("disabled", true);
}
},
error: function(result) {
console.log("Error while fetching data");
}
});
Try to trigger the change you made using .trigger('change') like:
$("#Options").val(data.Options).trigger('change');
//Or
$("#Options").val(data.Options).change();
I implemented something similar in my solution and my code is like this, you need to set the value like this:
success: function (response) {
var array = response;
if (array != '') {
for (i in array) {
$("#district").append("<option value='"+
array[i].Id + "'>" + array[i].DistrictName + "</option>");
}
}
},
I am trying to load data into table using JQuery and AJAX but when I click on the button data is not retrieved. I have done coding as shown below:
var globalgrid;
Here I am going to call json url and try to display it in the table.
function loadgrid() {
$.ajax({
type: 'GET',
dataType: 'json',
url: 'http://instatalk.in/sip/GetApprovedUsersList?page=1&limit=10',
success: function(griddata) {
globalgrid = griddata.lines;
// remove all data - but the headers!
$("#gridtable").find("tr:gt(0)").remove();
if (globalgrid.length === 0) {
$('#errormsg').html('Sorry, <strong>no</strong> rows returned!');
return;
}
for (var i = 0; i < globalgrid.length; i++) {
var line = globalgrid[i];
// insert after last row!
$('#gridtable > tbody:last').append('<tr><td>' + line.Id + '</td><td>' + line.AccountId + '</td><td>' + line.Name + '</td><td>' + line.IsFranchiseUser + '</td></tr>');
}
},
error: function(data, errorText) {
$("#errormsg").html(errorText).show();
}
});
}
I am getting the table heading only. When I click on the button I want data to be retrieved from the json data. I don't know where I am going wrong. Please do help.
This is my json file:
{"results":[{"Id":17,"AccountId":"5737329468","Name":"Martin (Nigeria)","IsFranchiseUser":false},{"Id"
:16,"AccountId":"3644824444","Name":"Deep Patel","IsFranchiseUser":false},{"Id":15,"AccountId":"4692068407"
,"Name":"Jacob (kiribati)","IsFranchiseUser":false},{"Id":14,"AccountId":"4650982975","Name":"sebin John
(spain)","IsFranchiseUser":false},{"Id":13,"AccountId":"2855375107","Name":"Jassi want(new jersey)"
,"IsFranchiseUser":false},{"Id":12,"AccountId":"6242007588","Name":"Moussa","IsFranchiseUser":false}
,{"Id":11,"AccountId":"3075258818","Name":"srkrbm (saudi arab)","IsFranchiseUser":true},{"Id":10,"AccountId"
:"3615509810","Name":"Om Saini","IsFranchiseUser":false},{"Id":9,"AccountId":"9251133143","Name":"swati
mohandas","IsFranchiseUser":false},{"Id":8,"AccountId":"8143395019","Name":"babu Kuppu","IsFranchiseUser"
:false}],"totalAccounts":16}
This line: globalgrid = griddata.lines;
According to your Json data format, you should use griddata.results.
I design a datalist on web page. And I want to fill this datalist using JQuery. Controller execute a query and get a list of facilities. Then pass this list to client side. This datalist can show all the facilities. When user click this textbox, the facilities will be listed in drop down list. But when user click more than once, there will be duplicates in datalist. That means, if you click twice, the result will be shown twice in datalist.
Here is code in MVC view
datalist:
<input type="text" list="facility" autocomplete="on" name="Facility" id="facilities" />
<datalist id="facility"></datalist>
JQuery Code:
$(document).ready(function () {
$('#facilities').click(function () {
//alert("Clicked");
var postData = $('#clientTxt').val();
$.ajax({
type: "POST",
url: '#Url.Action("FacilityCheck", "PCA")',
data: { clientTxt: postData },
success: function (result) {
//successful
for (var i = 0; i < result.facilities.length; i++) {
//alert(JSON.stringify(result.facilities[i]));
var option = "<option value ='" + result.facilities[i] + "'>" + result.facilities[i] + "</option>";
//I want to add an if judgement to avoid duplicates here
//Like contains() method in JAVA.
$('#facility').append(option);
}
},
error: function (result) {
alert('Oh no :(');
}
});
});
});
The duplicates image after clicking many times:
So please give me some advice. Thanks a lot!
It is because you are using the jQuery append() method and not replacing the HTML. Right now, you're just adding (appending) to it every time you iterate through your loop of result.facilities[i] instead of replacing the content.
Your best bet would be to add all of that source to a string and replace the $('#facility')'s innerHTML with the new content. You can use $('#facility').html(yourContentString); to do so.
Hope this helps!
For example...
success: function (result) {
var options = "";
//successful
for (var i = 0; i < result.facilities.length; i++) {
var option = "<option value ='" + result.facilities[i] + "'>" + result.facilities[i] + "</option>";
options = options + option;
} //end of loop
$('#facility').html(options); // replace the innerHTML of #facility with your new options string
},
Simply modify your success like this :
$('#facility').html('');
$('#facility').append(option);
Remove the items before appending them.
You can also use empty :
$('#facility').empty();
$(document).bind('pageinit', function () {
var vendor_id = $.urlParam('vendor_id');
$.ajax({
type: "GET",
url: "http://testservice/testmenu",
data: {
vendor_id: vendor_id
},
error: function () {
alert("Could not get the menu : " + url);
},
success: function parseXml(xml) {
var jsonData = $.parseJSON(xml);
$(jsonData).each(function (index, post) {
$(post).each(function (index, row) {
var finalString = [];
for(var index = 0; index < row.menu.length; index++) {
finalString.push('<div id="collapsibleMenu" data-mini="true" data-role="collapsible" data-inset = "true" data-content-theme="g">');
finalString.push('<h3>' + row.menu[index].category_name + '</h3>');
finalString.push('<ul id="menuDetails" data-role="listview">');
for(var j = 0; j < row.menu[index].products.length; j++) {
var output = ['<li data-icon="addToCart" id="addToCart"> <p>' + row.vendor_menu[index].products[j].prod_name + '</p><p> $' + Number(row.vendor_menu[index].products[j].price).toFixed(2) + '</p>' + '</li>'];
finalString.push(output);
}
finalString.push('</ul></div>');
}
$('#output').append(finalString.join(''));
});
});
$('#output').trigger('create');
}
});
});
function test(prod_id) {
alert("entered test " + prod_id);
addToCart(prod_id, 1);
}
In the following code, where I am doing the following:
<a href="javascript:test("+row.menu[index].products[j].prod_id")">
This is obviously giving me an error. The point is, I need to pass the prod_id dynamically into the javascript test method. I am not sure how to do that. If I just call test without passing prod_id, it works great. Please help!
Try removing the quotes in the argument.
I think I might have figured it out.
Try this.
<a href="javascript:test(\''+row.menu[index].products[j].prod_id+'\')">
This looks like the perfect reason to use a template engine. You might use a Jade template like this:
for post in posts
for row in post
for menu in row.menu
#collapsibleMenu(data-mini="true", data-role="collapsible", data-inset="true", data-content-theme="g")
h3= menu.category_name
ul#menuDetails(data-role="listview")
for product in menu.products
li#addToCart(data-icon="addToCart")
a(href="#", data-product-id=product.prod_id)
p= product.prod_name
p= '$' + Number(product.price).toFixed(2)
Then you can simplify your $.ajax call to:
$.ajax({
// ...
dataType: 'json',
success: function(data) {
$('#output').append(templateFunction(data));
}
});
For the click event, use event delegation:
$('#output').on('click', 'a[data-product-id]', function() {
addToCart(Number($(this).data('product-id')), 1);
});
Easy, yeah? Now change all of your ids to classes, because ids must be unique and yours aren't!
I have an array (via ajax) that looks like this:
data[i].id: gives the id of user i
data[i].name: gives the name of user i
I want to output the array like this:
X Leonardo Da Vinci
X Albert Einstein
X William Shakespeare
...
The X is an image (x.gif) that must be clickable. On click, it must go to functiontwo(), passing the parameter data[i].id. Functiontwo will open a jquery dialog with the question "Delete id data[i].id"?
I know this can't be too hard to do, but I can't seem to figure it out...
This is what I have so far:
function functionone() {
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
success : function(data){
var message = "";
var i = 0;
while (i < (data.length - 1))
{
var myvar = data[i].id;
message = message + "<div class=" + data[i].id + "><img src=x.gif></div>" + data[i].name + "<br />";
$('#somediv').html(message).fadeIn('fast');
$("." + data[i].id + "").click(function () {
functiontwo(myvar);
});
i++;
}
}
});
}
function functiontwo(id) {
...}
I know why this isn't working. Var i gets populated again and again in the while loop. When the while loop stops, i is just a number (in this case the array length), and the jquery becomes (for example):
$("." + data[4].id + "").click(function () {
functiontwo(myvar);
});
, making only the last X clickable.
How can I fix this?
Thanks a lot!!!
EDIT:
This is my 2nd function:
function functiontwo(id) {
$("#dialogdelete").dialog("open");
$('#submitbutton').click(function () {
$('#submitbutton').hide();
$('.loading').show();
$.ajax({
type : 'POST',
url : 'delete.php',
dataType : 'json',
data: {
id : id
},
success : function(data){
var mess = data;
$('.loading').hide();
$('#message').html(mess).fadeIn('fast');
}
});
//cancel the submit button default behaviours
return false;
});
}
In delete.php there's nothing special, I used $_POST['id'].
As I pointed out in my comment. The problem is the .click part. Either use bind, or use a class for all the elements, and a click-event like this $('.classnamehere').live('click',function () { // stuff });
function functionone() {
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
success : function(data){
var message = "";
var i = 0;
while (i < (data.length - 1))
{
var myvar = data[i].id;
message = message + "<div class=\"clickable\" id=" + data[i].id + "><img src=x.gif></div>" + data[i].name + "<br />";
$('#somediv').html(message).fadeIn('fast');
i++;
}
}
});
}
$('.clickable').live('click',function () {
alert($(this).attr('id') + ' this is your ID');
});
The usual trick is create a separate function to create the event handler. The separate function will receive i as a parameter and the generated event will be able to keep this variable for itself
make_event_handler(name){
return function(){
functiontwo(name);
};
}
...
$("." + data[i].id + "").click( make_event_handler(myvar) );