getting value and label from an attribute using jquery - javascript

From the following a I need to get value from the data-autocomplete attribute (we have label and value in there but I need to collect only value) by using jQuery, please help.
North Chigwell Primary, 115 Allunga Road, CHIGWELL TAS 7011
This is code how I am trying :
callback: function (e) {
var a = $(e.currentTarget); // access the selected item
var address = $.trim(a.text());
// data-autocomplete
var moniker = $(a).attr("data-autocomplete");
$('#addressQas').val(address);
//$.ajax({
new FancyAjaxinator().jsonPost({
url: "/address/selectLine",
//dataType: "json",
data: {
"moniker": moniker,
"address": address
},
success: function (data) {
//console.log(data.responseObject);
var qasAddress = data.responseObject;
$('#address-line1').val(qasAddress.addressLine1);
if (qasAddress.state) {
$('#address-line2').val(qasAddress.addressLine2);
$('#address-townCity').val(qasAddress.suburb);
$('#address-state').val(qasAddress.state);
$('#address-state').parent().find('span.ui-selectmenu-text').text($("#address-state option[value=" + qasAddress.state + "]").text());
$('#address-postcode').val(qasAddress.postcode);
$('#address-line1').valid();
$('#address-townCity').valid();
$('#address-state').valid();
$('#address-postcode').valid();
}
$('#QASaddressField').hide();
$('.qasAddressFields').show();
//setFocus();
}
});
this.close;
return false;
}

Try
var a = $('a');// or the jQuery wrapper for the target a
var json =a.data('autocomplete');
console.log(json.value)
Demo: Fiddle
Using .attr()
var moniker = $(a).attr("data-autocomplete");
var json = JSON.parse(moniker);
console.log(json.value);

Related

Using Javascript how to store previous search history in browser

I have implemented autocomplete feature using JQuery, but now I wanted to store last 20 searched per inputfield in browser. So, if user when focuses the suggestion will be fetched from the browser. If user types then from Rest API using ajax I am fetching the data.
$("input[type='text']").autocomplete({
source: function(request, response) {
var id = $(this.element).prop("id");
var id2=this.element[0].id;
var id3=$(this.element.get(0)).attr('id');
console.log(id);
console.log(id2);
console.log(id3);
var params = {'page':1,'size':"10"};
params[id]=request.term;
var jsonParams = JSON.stringify(params);
$.ajax({
type: "POST",
url:"http://localhost:5645/search",
data: jsonParams,
headers: {"X-CSRF-TOKEN": $("input[name='_csrf']").val()},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
//const result = new Set()
var result=[];
console.log(id);
console.log(msg.details)
console.log(msg.details.length)
for(var i = 0; i < msg.details.length; i++) {
var obj = msg.details[i];
if(obj!=null && columnMapping[id]!=undefined && obj[columnMapping[id]]!=undefined){
console.log(obj[columnMapping[id]]);
//result.add(obj[columnMapping[id]]);
result.push(obj[columnMapping[id]]);
}
console.log(result);
}
//response(Array.from(result));
response(result);
}
/* error: function() {
response([]);
} */
})
},
select: function(event, ui) {
alert(ui.item ? ("You picked '" + ui.item.label) : "Nothing selected, input was " + this.value);
return false;
}
}).autocomplete("instance")._renderItem = function(ul, item) {
console.log('test');
var item = $("<div>" + item.label + "</div>")
return $("<li>").append(item).appendTo(ul);
};
Above is the jquery code which I am using for autocomplete. So, if no input is there I need to fetch from browser recent search. So, when user types unique search keys should be inserted. How I can store and retrive using javascript.

HTML value passed to WebService is showing NULL

I have a AJAX Web Serice that runs an SQL statment, which works.
I am trying to take an HTML value from my web page and use it as an additional variable in my query.
Here is how I am capturing that variable on my web page.
<div style="margin-left:0px">
<label>Enter Number here: </label><br>
<input type= text id="demo">
</div>
...and this is my Web Service call.
//Generate code
function Generate() {
var myGrid = $('#jqquotes'),
selectedRowId = myGrid.jqGrid('getGridParam', 'selrow');
docid = myGrid.jqGrid('getCell', selectedRowId, 'docid');
document.getElementById("demo").innerHTML = document.getElementById("demo").value;
alert(document.getElementById("demo").value);
var quotenum = document.getElementById("demo".value);
if (confirm('Are you sure you want to generate a quote?')) {
$.ajax({
url: '/WebService1.asmx/Generate',
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "GET",
data: { docid: docid, quotenum: JSON.stringify(quotenum) },
success: function () {
//Get selected
var grid = $("#jqquotes");
var rowKey = grid.jqGrid('getGridParam', "selrow");
//Refresh grid
$('#jqquotes').trigger('reloadGrid');
//Set Selected
setTimeout(function () {
jQuery('#jqquotes').jqGrid('setSelection', rowKey);
}, 200);
}
});
} else {
return false
}
}
The alert box correct displays the HTML value from the box id "Demo"
But the WebService fails, saying the value is NULL, JSON reponse is:
Message "The parameterized query '(#docid nvarchar(5),#quotenum nvarchar(4000))UPDATE [dbo].[quote' expects the parameter '#quotenum', which was not supplied."
...and the GET URL shows the value as NULL
https://localhost:44338/WebService1.asmx/Generate?docid=10146&quotenum=null
Any help greatly appreciated.
I think the problem is here:
var quotenum = document.getElementById("demo".value);
This should be
var quotenum = document.getElementById("demo").value;
as in the line above it.

Retrieving data from myapifilms.com api

I am following a tutorial on YouTube showing how to get data from the myapifilms.com api and I am having trouble rendering the data to HTML. Currently my ajax call is working and the data is showing in the console. The problem I am having is getting the data to show on the page itself. I searched through the question already asked but had no luck. Here's my js code so far:
$(document).ready(function(){
$("#searchMovie").click(searchMovie);
var movieTitle = $("#movieTitle");
var table = $("#results");
var tbody = $("#results tbody"); //table.find("tbody");
function searchMovie() {
var title = movieTitle.val();
$.ajax({
url: "http://www.myapifilms.com/imdb/idIMDB?title="+ title +"&token= + token goes here +&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=1&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0&quotes=0&fullSize=0&companyCredits=0",
dataType: "jsonp",
success: renderMovies
})
function renderMovies(movies) {
console.log(movies);
tbody.empty();
for(var m in movies) {
var movie = movies[m];
var title = movie.title;
var plot = movie.simplePlot;
var posterUrl = movie.urlPoster;
var imdbUrl = movie.urlIMDB;
var tr = $("<tr>");
var titleTd = $("<td>").append(title);
var plotTd = $("<td>").append(plot);
tr.append(titleTd);
tr.append(plotTd);
tbody.append(tr);
}
}
}
});
I feel like I am so close but can't quite figure what I am missing. Again I was following a tutorial so if there's a better way to accomplish this goal I'm definitely open to suggestions.
Update:
I changed my code to this and I'm getting undefined in the browser. I changed the for loop to this
success: function (movies) {
console.log(movies);
tbody.empty();
for (var m in movies) {
$(".movies").append("<h3>"+ movies[m].title +"</h3>");
$(".movies").append("<h3>"+ movies[m].plot +"</h3>");
}
}
I figured out a solution, instead of using myapifilms, I used the tmdb api instead. Changing my code to this worked:
var url = 'http://api.themoviedb.org/3/',
mode = 'search/movie?query=',
input,
movieName,
key = 'myapikey';
//Function to make get request when button is clicked to search
$('button').click(function() {
var input = $('#movie').val(),
movieName = encodeURI(input);
$.ajax({
type: 'GET',
url: url + mode + input + key,
async: false,
jsonpCallback: 'testing',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
console.dir(json.results);
for (var i = 0; i < json.results.length; i++){
var result = json.results[i];
$(".moviesContainer").append('<div class="movies col-md-12">'+
'<img class="poster" src="http://image.tmdb.org/t/p/w500'+ result.poster_path +'" />'
+'<h3>'+ result.title +'</h3>'
+'<p><b>Overview: </b>'+ result.overview +'</p>'
+'<p><b>Release Date: </b>'+ result.release_date +'</p>'
+'</div>');
}
},
error: function(e) {
console.log(e.message);
}
});
});

AJAX list update, get new elements and count

I have this HTML list
<ul id='usernameList'>
<li class='username'>John</li>
<li class='username'>Mark</li>
</ul>
and a form to add new names via AJAX, multiple add separated by commas. The response is a list with the names
[{name:David, newUser:yes}, {name:Sara, newUser:yes}, {name:Mark, newUser:no}]
I'm trying to insert this names sorted alphabetically in the list, like this example https://jsfiddle.net/VQu3S/7/
This is my AJAX submit
var form = $('#formUsername');
form.submit(function () {
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
dataType: "json",
beforeSend: function () {
//
},
success: function (data) {
var listUsernames = $('#usernameList');
var numUsernames = listUsernames.children().length;
$.each(data, function(i, user) {
if(user.newUser == "yes"){
var htmlUser = "<li class='username'>" + user.name + "</li>";
var added = false;
$(".username", listUsernames).each(function(){
if ($(this).text() > user.name) {
$(htmlUser).insertBefore($(this));
added = true;
}
});
if(!added)
$(htmlUser).appendTo($(listUsernames));
}
// HERE I DO alert('numUsernames')
// I get the same number of users before sending form
// How can I update here the value of listUsernames and numUsernames?
});
}
});
return false;
});
My question is, how I can update the value of listUsernames and numUsernames after adding an item?
You just need to update numUsernames at that point.
Add this where your comments are:
numUsernames = listUsernames.children().length;
listUsernames already has the updated children, as it's a reference to the parent element.
Edit: Re: your comment below:
This should probably work:
$(".username", listUsernames).each(function(){
if ($(this).text() > user.name) {
$(htmlUser).insertBefore($(this));
added = true;
return false; // stop `.each` loop.
}
});
First you don't need a double jQuery wrapping:
$(htmlUser).appendTo($(listUsernames));
listUsernames is already a jQuery object, so try:
$(htmlUser).appendTo(listUsernames);
And after every adding, you can update the numUsernames variable with:
numUsernames = listUsernames.children().length;
but this is not necessary because you can always access listUsernames.children().length in the success handler.
I update your JSFiddle
var listUsernames = $('#usernameList');
var numUsernames = listUsernames.children().length;
var data = [{name:'David', newUser:'yes'}, {name:'Sara', newUser:'yes'}, {name:'Mark', newUser:'no'}]
$.each(data, function(i, user) {
if(user.newUser == "yes"){
var htmlUser = "<li class='username'>" + user.name + "</li>";
var added = false;
$(".ingredient", listUsernames).each(function(){
if ($(this).text() > user.name) {
$(htmlUser).insertBefore($(this));
added = true;
}
});
if(!added)
$(htmlUser).appendTo($(listUsernames));
}
// HERE I DO alert('numUsernames')
// I get the same number of users before sending form
// How can I update here the value of listUsernames and numUsernames?
});

Getting wrong Form Data name when posting

I am trying to pass multiple parameters to a javascript function. When reviewing the post data I get incorrect data names.
HTML:
//Test function with button (HTML)
<button onClick='printList("projects",{"qid":1,"oid":3),getSampleEntity);'>Test getSampleEntity</button>
Javascript:
var getSampleEntity = function(oid, qid) {
//Returns Object
return $.ajax({
url: URL + 'downloadQuadrat_Organism.php',
type: 'POST',
data: { 'organismID': oid, 'quadratID': qid },
dataType: dataType
});
}
....
var printList = function(lid,options,get) {
var items = get(options);
var list = $("ul#"+lid);
list.empty();
items.success(function(data){
$.each(data, function(item,details) {
var ul = $('<ul/>');
ul.attr('id', lid+'_'+details.ID);
var li = $('<li/>')
.text(details.ID)
.appendTo(list);
ul.appendTo(list);
$.each(details,function(key,value) {
var li = $('<li/>')
.text(key+': '+value)
.appendTo(ul);
});
});
});
}
The resulting post data:
organismID[qid]:1
organismID[oid]:3
I see what is happening, but my question is how do I pass multiple parameters in to my printList() so that those parameters will be passed effectively to getSapleEntity()?
Try
var items = get(options.oid, options.qid);

Categories

Resources