How to use other parameters with an exception included - javascript

I have this function:
function searchItem(e, pageNumber){
e.preventDefault();
searchString = searchBox.value;
article = document.getElementById("homeSection");
var xmlhttp = getXmlHttpRequestObject();
var string = '';
if(xmlhttp){
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
var response = JSON.parse(xmlhttp.responseText);
for(var i=0; i<response.length; i++){
var price = parseFloat(response[i].Price);
string += '<section class="searchResult">';
string += '<p class="photo"><img src="' + response[i].Photo + '"></p>';
string += '<section>';
string += '<h1 class="name">' + response[i].Name + '</h1>';
string += '<p class="price">£' + price.toFixed(2) + '</p>';
string += '<p class="description">' + response[i].Description + '</p>';
string += '<p class="productID">ID: ' + response[i].ID + '</p>';
string += '<p class="quantity">Quantity: ' + response[i].Quantity + '</p>';
string += '</section>';
string += '</section>';
if(pageNumber != 1){
string += '<section><button id=previousPage>Previous</button><button id=nextPage>Next</button></section>';
}
}
article.innerHTML = '<h1>Search</h1><section><h1 class="bottomBorder">You searched for: "' + searchString + '"</h1></section>';
article.innerHTML += string;
}
};
xmlhttp.open("POST", "search.php?search=" + searchString, false);
xmlhttp.send("&rpp=" + rowsPerPage + "&last=" + lastPage + "&page=" + pageNumber);
}
}
What i am curious about is how to call the function because it has an exception in it.
It worked fine when i was using it in a javascript event:
searchButton.addEventListener("click", searchItem);
but when i tried calling the function with parameters like this it didn't work, it tells me that e is not defined:
searchButton.addEventListener("click", function(){
searchItem(1);
});
Which i do understand because i haven't passed through a parameter for e but i want to know is why it works as an event without a pseudo function and how i should call it with a pseudo function.

The function requires the event as the first argument. This is set when using the function itself as the click handler, but when you create your own click handler, you need to capture the event and explicitly pass it:
searchButton.addEventListener("click", function(e){
// capture the event object--^
searchItem(e, 1);
// ^ pass it to the function
});

Related

Building html output with a input checkbox with javascript

I'm building a string that will be place in a div pro grammatically. I am trying to call the onclick attribute of the input checkbox and having a little bit of trouble. I am trying to pass a unique value id with each checkbox click. The code below is what I'm using. See below for the problem:
var count = 1;
$.each(JSON.parse(data.d), function (k, v) {
var searchName = v.searchName;
resultString += "<div class='row form-group'>";
resultString += "<div class='col-sm-1 right-content'><input type='checkbox' onclick = 'authorCheckboxclick(this)' id='" + searchName + "'></div>";
resultString += "<div class='col-sm-11'>";
resultString += "<span>";
//resultString += v.text
resultString += count + ". " + v.text
resultString += "</span>";
resultString += "<br />";
resultString += "<span>";
//resultString += "Consectetur adipisicing, Consequatur, 2015.";
resultString += "</span>";
resultString += "</div>";
resultString += "</div>";
//resultString += "<br><br>";
count++;
});
In the authorCheckboxclick function if I put var answerid = $(this).attr('id'); I get undefined.
function authorCheckboxclick(elem) {
var answerid = $(this).attr('id');
alert(answerid); //I get undefined
var answerid = $(this).attr(elem.id);
alert(answerid); //I get undefined
var answerid = $(this).attr(elem.id);
alert(answerid); //I get undefined
var searchTerm = elem.id;
alert(searchTerm); //I get proper value
searchTerm = searchTerm.substring(0, 3);
alert(searchTerm); //I get proper value
var answerid = $(this).attr(elem.id);
alert(answerid); //I get undefined
var search = searchTerm.toUpperCase();
var array = jQuery.grep(dataMembers, function (value) {
return value.toUpperCase().indexOf(search) >= 0;
});
Is there a reason my jQuery call is not working and my JavaScript is? Is there a best practice to send the id value to a junction? Am I mixing Apples with Orange? Which method show be faster?
The immediate solution to your problem is that you're using the this keyword in your function. As you are calling the function from an on* attribute the scope of the function will be the window, not the element that raised the event. To fix this, simply use the element you provide in the parameter, ie. $(elem) instead of $(this).
A better solution entirely would be to use an unobtrusive delegated event handler which can utilise the this keyword as you're attempting to. It also has the benefits of leaving cleaner HTML code and being a better separation of concerns. Try this:
var count = 1;
$.each(JSON.parse(data.d), function(k, v) {
var searchName = v.searchName;
resultString += '<div class="row form-group">' +
'<div class="col-sm-1 right-content"><input type="checkbox" id="' + searchName + '"></div>' +
'<div class="col-sm-11">' +
'<span>' + count + ". " + v.text + '</span><br />' +
'<span></span>' +
'</div>' +
'</div>';
count++;
});
$(document).on('change', '.row :checkbox', function() {
var answerid = this.id;
var search = searchTerm.toUpperCase();
var array = jQuery.grep(dataMembers, function(value) {
return value.toUpperCase().indexOf(search) >= 0;
});
});

this.id is not working to detect which link is clicked in href

I am new to javascript and I am creating a bookstore using the google API. I have a small issue which I couldn't figure out. In the below piece of code that I saw from example code of google api bookstore function, I am trying to create href for the title of the book and pass its selfLink to the destination page i.e book-description.html.
When I put alert(this.id) on onclick It works, but for a normal method get(this) it does not work. I do not need an alertbox I want to take the id of the link clicked in href and pass it to another html.
handleResponse(response) {
for (var i = 0; i < response.items.length; i++) {
var item = response.items[i];
var a = item.volumeInfo.title;
var selfL = item.selfLink;
//var b = a.link("book-description.html");
var image = item.volumeInfo.imageLinks.smallThumbnail;
document.getElementById("content").innerHTML += "</br>" + "</br>" + "<br>" + "<img src =" + "'" + image + "'" + " class='im'/>";
document.getElementById("content").innerHTML += "<h4 class='right'>" + "<a href = 'book-description.html'id = " + "'" + selfL + "'" +
"onclick ='get(this);'>" + a + "</a></h4>";
function get(e) {
var link = e.id;
localStorage.setItem("Link", link);
}
document.getElementById("content").innerHTML += "<h4 class='right'>" + "AUTHOR:" + item.volumeInfo.authors + "</h4>";
document.getElementById("content").innerHTML += "<h5 class='right'>" + "PUBLISHER:" + item.volumeInfo.publisher + "</h5>";
var rating = item.volumeInfo.averageRating;
if (rating) {
document.getElementById("content").innerHTML += "<h5 class='right' id='rating'>" + rating + "</h5>";
} else {
document.getElementById("content").innerHTML += "<h5 class = 'right' id ='rating'>Not Rated Yet</h5>";
}
//document.getElementById("content").innerHTML += "<br>" + "<br>" + "<br>" + item.volumeInfo.publisheddate;
}
}
There are a number of problems with your code, but specifically in answer to your question; your function get is scoped so it is only available within the function handleResponse. For it to be accessible from an onclick it must be in page scope.
Simply move this
function get(e) {
var link = e.id;
localStorage.setItem("Link", link);
}
Into the head of your page
In programming there is the concept of DRY (Don't repeat yourself). So store a reference to document.getElementById("content") and reuse that variable.
var content = document.getElementById("content");
content.innerHTML = ...
You're missing some spaces in your output html. This may work in some browsers, others will struggle
<a href = 'book-description.html'id=
Should have a space between the end of one attribute and the start of another
<a href='book-description.html' id=
And for heaven sake, sort out the concatenation of your strings. You dont need a + if its just a simple string
document.getElementById("content").innerHTML += "</br>" + "</br>";
should be
document.getElementById("content").innerHTML += "</br></br>";

insert values into my json between tags

I have this code:
$json = '[{"data":{"name":"Widget Shop USA","widget_a":300,"widget_b":250},"template":{"name":"<h1 class=\"name\"></h1>","cost":"<span class=\"cost\">Price: $</span>"}}]';
$array = json_decode($json, true);
$widget_a = $array[0]['data']['widget_a'];
$widget_b = $array[0]['data']['widget_b'];
$data_name = $array[0]['data']['name'];
$array[0]['template']['cost'] .= $widget_a + $widget_b;
$array[0]['template']['name'] .= $data_name;
What i am trying to do is to get the $array[0]['template']['cost'] and the $array[0]['template']['name'] and pass them into $json variable between the HTML fragments (h1,span). How can i achieve that?
i try to encode the $array:
$json_new = json_encode($array);
but the variables comes after the HTML fragments...Is there any way to pass it between H1 and SPAN tags?
To the question addressed in you comment, you can loop through a JSON, grab the relevant property and assign it like so:
function mm(obj) {
for (var prop in obj) {
obj.name = "<h2>" + obj.employees[0].firstName +"</h2>";
}
return obj;
}
console.log(mm(json));
Working JSBin https://jsbin.com/sefohu/edit?js,console
You can use:
indexOf and slice
for example:
$widget = $array[0].data.widget_a + $array[0].data.widget_b;
$data_name = $array[0].data.name;
$indexCost = $array[0].template.cost.indexOf('$<');
$array[0].template.cost = $array[0].template.cost.slice(0, $indexCost + 1) + $widget + $array[0].template.cost.slice($indexCost + 1, $array[0].template.cost.length);
$indexName = $array[0].template.name.indexOf('><');
$array[0].template.name = $array[0].template.name.slice(0, $indexName + 1) + $data_name + $array[0].template.name.slice($indexName + 1, $array[0].template.name.length);
alert($array[0].template.name);
alert($array[0].template.cost);
or use temp method:
$temp = document.createElement('template');
$temp.innerHTML = $array[0]['template']['name'];
$temp.getElementsByTagName('h1')[0].innerHTML = $array[0]['data']['name'];
$array[0]['template']['name'] = $temp.innerHTML;
if you can change the json my suggestion:
$json = '[{"data":{"name":"Widget Shop USA","widget_a":300,"widget_b":250},"template":{"nametag":"h1","nameclass":"name","costtag":"span","costclass":"cost"}}]';
and use:
$array = JSON.parse($json);
$widget = $array[0].data.widget_a + $array[0].data.widget_b;
$array[0].template.cost = '<' + $array[0].template.costtag + ' class="' + $array[0].template.costclass + '" >' + $widget + '</' + $array[0].template.costtag + '>';
$array[0].template.name = '<' + $array[0].template.nametag + ' class="' + $array[0].template.nameclass + '" >' + $array[0].template.name + '</' + $array[0].template.nametag + '>';
alert($array[0].template.name);
alert($array[0].template.cost);

loop from json files and search then get the value via jquery and json

I have a bit of a question. which is a loop.
I have a simple looping which when I clicked some numbers and it will search and loop through out my json file.
here is my code
function showSortedRoute(){
$.getJSON('my.json', function(data) {
var $resultHTML = $("#divResult");
var result = "";
result = '<ul class = "list clearfix">';
$.each(data, function (key, val){
if (val.area_id == getRuoute) {
var image = val.image;
var structure_name = val.name;
var copy = val.copy;
var address = val.address;
var access = val.access;
var type = val.type;
var getarea = val.area;
result += '<div class="iconArea">';
result += '<h4>' + name + '</h4>';
result += '<h4><b>' + getarea + '</b></h4>';
result += '</div>';
result += '<p class="catch">' + copy + '</p>';
result += '<dl class="detailArea clearfix">';
result += '<dd>' + address + '</dd>';
result += '<dd>' + access + '</dd>';
result += '</dl>';
result += "</ul>";
$resultHTML.html(result);
} else {
alert("No area ID Found" + getRoute);
}
});
});
}
this does not give me any results, saying no area ID found, but in
alert("no area id found" + getRoute);
and the alert shows displays like four times.
I can check that the value is the same.
code for matching up with integers with json is not working.
There's a few errors in your code:
getRuoute in this line: if(val.area_id == getRuoute){ seems to be
undeclared variable
name in this line: result += '<h4>' + name + '</h4>'; is also
undeclared
getRoute in this line: alert("No area ID Found" + getRoute);
seems to be undeclared variable
Here is corrected and optimized version:
$.getJSON('my.json', function(data) {
var $resultHTML = $("#divResult"),
result = '<ul class = "list clearfix">';
$.each(data, function (key, val){
if (val.area_id == 'getRuoute') { // check type and name of 'getRuote', maybe 'getRoute'?
var image = val.image,
structure_name = val.name,
copy = val.copy,
address = val.address,
access = val.access,
type = val.type,
getarea = val.area;
result += '<div class="iconArea">';
result += '<h4>' + structure_name + '</h4>';
result += '<h4><b>' + getarea + '</b></h4>';
result += '</div>';
result += '<p class="catch">' + copy + '</p>';
result += '<dl class="detailArea clearfix">';
result += '<dd>' + address + '</dd>';
result += '<dd>' + access + '</dd>';
result += '</dl>';
result += "</ul>";
$resultHTML.html(result);
} else {
alert("No area ID Found" + getRoute);
}
});
});

Simple jQuery if statement, API returns 'null'

Using the Sunlight Congress API to pull a list of representatives, I'd like to return folks' nicknames if they are used. If a representative doesn't use a nickname, the API returns 'null'.
I'm messing up the syntax for the if statement. Here's my most recent misguided approach:
if (rep.nickname == 'null'){myFolks += rep.first_name + ' ';}
 
Here's the full context:
$(document).ready(function () {
$('#rep-lookup').submit(function(e){
e.preventDefault();
var $results = $('#rep-lookup-results'),
zipcode = $('#txt-zip').val(),
apiKey = '_YOUR_API_KEY';
var requestURL = 'http://congress.api.sunlightfoundation.com/legislators/locate?callback=?';
// collect the data
$.getJSON(requestURL, {
'apikey' : apiKey,
'zip' : zipcode,
}, function(data){
if (data.results && data.results.length > 0) {
var myFolks = '<p>Here are your Congress folk:</p>';
$.each(data.results, function(i, rep) {
myFolks += '<p>';
myFolks += '<a href="' + rep.contact_form + '" target="_blank">';
myFolks += rep.nickname;
if (rep.nickname == 'null'){myFolks += rep.first_name + ' ';}
myFolks += rep.last_name + ' ';
myFolks += '</a>';
myFolks += '</p>';
});
myFolks += '<p>Please write to them in support of this legislation.</p>';
$results.html(myFolks);
} else {
$results.html('<p>None found for zip code ' + zipcode + '. Please try again.</p>');
}
});
});
});
myFolks += (rep.nickname && rep.nickname !== "null") ? rep.nickname : rep.first_name + ' ';
via: #tomcreighton

Categories

Resources