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;
});
});
Related
I currently click a button to show some info, but the info only appears below the button of the first item. I want it to appear below each corresponding button in my index of items.
Appreciate any tips on debugging.
Please see JS code below:
$(function(){
homeButton();
profileButton();
readMoreButton();
});
function readMoreButton(){
$(document).on('click', 'button.read-more.btn-more', function(event){
event.preventDefault();
appendReadMore(this.attributes.href.value)
});
}
function appendReadMore(url){
$.get(url, function (result){
$("#ReadMoreSpan").html("Location:"+result[0].location);
});
}
function iterateJobs(jobs){
var str = "<ul>";
jobs.forEach(function(job){
var job_id = job.id;
var link_path = '/repairmen/' + job['repairman']['id'] + '/jobs/' + job['id'];
str += '<li>Repairman: ' + job['repairman']['name'] + '<br>';
str += 'Customer: ' + job['customer']['name'] + '<br>';
str += '<ul>';
str += iterateTickets(job['tickets']);
str += '</ul>';
str += '<button class="edit btn-info" href="' + link_path + '/edit">Edit Job</button> | ';
str += '<button ' + `id=${job_id} ` + 'class="delete btn-danger" href="' + link_path + '">Delete Job</button> | ';
str += '<button class="read-more btn-more" href="' + link_path + '">Read More</button> <br><br>';
str+='<span id="ReadMoreSpan" ></span>';
str += '</li>';
});
str += '</ul>';
return str;
}
That is because you'll end up with multiple spans with the same id (#ReadMoreSpan), so whenever you call your function it will put the result of the AJAX call into the first one. You need to do two things:
Give all read more spans a unique ID so they can be identified
Pass that id to the event handler for the link click.
Let's start with the ID and add that as a data-parameter on the span (and also remove the #ReadMoreSpan, as ID's should be unique:
str += '<span data-job="' + job_id + '"></span>';
Having done that, we need to be able to access this id when fetching more data, so add the same ID to the button:
str += '<button class="read-more btn-more" data-job="' + job_id + '" href="' + link_path + '">Read More</button> <br><br>';
Now the two functions can be updated to handle this value:
function readMoreButton() {
$(document).on('click', 'button.read-more.btn-more', function(event){
event.preventDefault();
appendReadMore(this.attributes.href.value, this.getAttribute('data-job'))
});
}
function appendReadMore(url, jobId) {
$.get(url, function (result){
$("span[data-job='" + jobId + "']").html("Location:"+result[0].location);
});
}
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>";
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);
}
});
});
I have a an array of items which holds item objects. I want to create a function that when I click on a certain item it is removed from the array. I know I need to use something like splice and I have implemented the following solution but it does the seem to work.
Can anyone tell me what am I doing wrong.
function updateView() {
for (var i = 0; i < storeItems.length; i++) {
output += "<a href='#' id='itemTitle' onclick='removeRecord(" + i + ");'>"
+ storeItems[i].title + " " + "\n" + "</a>";
}
function removeRecord(i) {
storeItems.splice(i, 1);
var newItem = "";
// re-display the records from storeItems.
for (var i = 0; i < storeItems.length; i++) {
newItem += "<a href='#' onclick='removeRecord(" + i + ");'>X</a> "
+ storeItems[i] + " <br>";
};
document.getElementById('foods').innerHTML = newItem;
}
I think this the error is in the line below:
output += "<a href='#' id='itemTitle' onclick='removeRecord(" + i + ");'>" + storeItems[i].title + " " + "\n" + "</a>";
Because it does not recognise the "onclick" event even when I try to do a test with a simple alert.
Can anyone tell me what am I doing wrong. Also if you think you need more information to answer this question please let me know.
Thank you in advance.
Try ...
storeItems = storeItems.splice(i, 1);
WRONG: Basically, you have to assign the spliced array to something.
UODATE:
Here's the way I would do it ... tested in jsFiddle:
var storeItems = [{
title: "Dog"
}, {
title: "Cat"
}, {
title: "Bird"
}];
var foods = document.getElementById('foods');
foods.addEventListener('click', function(e) {
var index = e.target.getAttribute('value');
storeItems.splice(index, 1);
// re-display the records from storeItems.
updateView();
});
function updateView() {
var output = "";
for (var i = 0; i < storeItems.length; i++) {
output += "<a href='#' class='item' value='" + i + "'>" + storeItems[i].title + " " + "\n" + "</a>";
}
document.getElementById('foods').innerHTML = output;
}
updateView();
HTML:
<div id='foods'></div>
This effectively takes the onclick event off of the anchor tag (you could have them on any type of tag at this point) and I also reused your updateView code in the Listener so that it only needs maintained in one location.
I have a really big html-document consisting of a number of <h4> headers accompanied by a short <p> 'body'.
I need to add an anchor point (is it the correct term, btw?) to each of the headers.
I'm iterating over the headers, and adding them to a menu-ul:
headz = document.getElementsByTagName("h4");
arrayOfHeaders=[];
x = 0;
y = headz.length;
$("#menu").html("<ul>")
while (x<y){
arrayOfHeaders[x] = "<li><a href='#" + x +"'>" + headz[x].innerText + "</a></li>";
$("#menu").append(arrayOfHeaders[x])
x++;
}
$("#menu").append("</ul>")
I need a way to attach the anchor points to the headers.
Edit: To clarify - what i need is the add a name-tag to each of the -elements.
The first header should be edited from '<h4>' header'</h4>' to '<h4 name="0">'...
Without editing the html, of course.
Set ids to the if they do not have one.
headz = document.getElementsByTagName("h4");
arrayOfHeaders=[];
x = 0;
y = headz.length;
var str = "<ul>";
while (x<y){
var elem = headz[x];
var id = elem.id || "heading_" + x;
elem.id = id;
str += "<li><a href='#" + id +"'>" + elem.innerText + "</a></li>";
x++;
}
$("#menu").append( str + "</ul>");
and FYI innerText is not cross browser friendly.
jQuery solution
var str = "<ul>";
$("h4").each(
function(i){
var id = this.id || "header_" + i;
this.id=id;
str += '<li>' + this.innerHTML + '</li>';
}
);
str += "</ul>";
$("#menu").append(str);
Since you used jquery already, thought id write it all in it:
var html = '<ul>';
$('h4').each(function (index, header) {
html += '<li>' + header.html() + '</li>';
});
html += '</ul>';
$('#menu').append(html);
This might solve your problem
headz = document.getElementsByTagName("h4");
arrayOfHeaders=[];
x = 0;
y = headz.length;
var html = "<ul>";
while (x<y){
html += "<li><a href='#" + headz[x].id +"'>" + headz[x].innerText + "</a></li>";
x++;
}
$("#meny").append( html + "</ul>")
This one is similar to rissicay's answer but I think it's more concise:
var html = []; // create an empty array to store iterated html in
// loop over every heading...
$('h4').each(function(index) {
// and add it to array previously created
html.push("<li><a href='#" + index +"'>" + $(this).html() + "</a></li>");
// add name attribute to heading
$(this).attr('name', index);
});
// finally, append all to menu together with unordered list
$('#menu').append('<ul>' + html.join() + '</ul>');
Basically, try to minimize dom manipulation (.append(), .prepend(), .html()) as much as possible
I think the concept you refer to is sometimes known as an "internal link" - see here under the second section "HTML Links - The id Attribute".
Now looking at your example code you are clearly using jQuery so why not make the most of it?
$("h4").each(function() {
$("#links").append("<a href='#" + this.id + "'>link to " + this.id + "</a><br /><br />");
});
See the following fiddle - http://jsfiddle.net/r0k3t/PhrB6/
Hope that helps.