How do I add a checkbox to an added list? - javascript

Project: Shopping List
I have created a function that will take input from a form. I am able to display what the user entered. Now I want to add a checkbox next to item displayed, so I can eventually give the option to check the item and remove it.
This is my function:
function addItem() {
var item = [];
item = document.getElementById('items-listed');
item.innerHTML += "<li>" + document.form.itemEntered.value + "</li>";
// item.innerHTML += "<li><input type="checkbox" />" + document.form.itemEntered.value + "</li>";
}
I attempted to create the checkbox but it was not working, so I commented it out.
Here is the project running in Code Pen
http://cdpn.io/JGCDB

This should do it:
item.innerHTML += "<li><input type='checkbox'>" + document.form.itemEntered.value + "</li>";
The issue you experienced is called escaping.
You are generating a string in JS using double-quotes so if you want to use a literal double-quote inside your string then you need to escape it, please study the code below:
item.innerHTML += "<li><input type=\"checkbox\">" + document.form.itemEntered.value + "</li>"; //good
item.innerHTML += '<li><input type="checkbox">' + document.form.itemEntered.value + '</li>'; //good
item.innerHTML += '<li><input type=\'checkbox\'>' + document.form.itemEntered.value + '</li>'; // good
item.innerHTML += "<li><input type="checkbox">" + document.form.itemEntered.value + "</li>"; //bad
item.innerHTML += '<li><input type='checkbox'>' + document.form.itemEntered.value + '</li>'; //bad
The devil is always in the details.

Related

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>";

creating dynamic li elements from json with typeahead - loop error

Using typeahead.js I'm creating li elements from the color item in the json response
Json:
"results": [
{
"title": "The Collection",
"attribute": "The Collection",
"url": "#/test",
"image": "images/products/londonretro-caine.jpg",
"color": ["brown", "yellow", "grey"]
},
The json has a color key that is sometimes a string, and sometimes an array with several colors
I've looped through the response and created a html dynamically
html += '<li></li>'
I've added a conditional to check if the item in the json is an array of colors.
If it is an array of colors, I've replaced the html with as many li items, as there are colors in the array
I've tried two methods:
1. One is that I make html equal to the new li elements like so: html += '<li></li>...'
the other is that I've changed html to an array and I pushed the li elements into it replacing the original html : html.push('<li></li>')
With method 1, I get the following result:
I get all the colors in a separate li,
but I also get an extra first li with the colors like so:
<li class='product-spot__variants-variant' style='background-color:brown,yellow,grey' title='brown,yellow,grey'>'brown,yellow,grey'</li>
With method 2, I only get the last li with the last color:
<li class='product-spot__variants-variant' style='background-color:grey' title='grey'>'grey'</li>
I left both solutions in the following code.
Any ideas? Thanks, Ask please if it's unclear..
my typeahead code:
suggestion: function (item) {
var glassesColor = item.color;
var html = "<li class='product-spot__variants-variant' style='background-color:"+ glassesColor +"' title='"+ glassesColor +"'>'"+ glassesColor +"'</li>";
_.forEach(item.color, function (k) {
if (typeof item.color === 'object') {
html += "<li class='product-spot__variants-variant' style='background-color:"+ k +"' title='"+ k +"'>'"+ k +"'</li>";
html = [];
html.push("<li class='product-spot__variants-variant' style='background-color:" + k + "' title='" + k + "'>'" + k + "'</li>");
var myhtml = html.join('');
html = myhtml;
}
});
//console.log(html);
var output = '<div class="search-autocomplete search-glasses">\n';
output += '<a href="' + item.url + '">';
output += (item.image ? '<img class="search-autocomplete__image" src="' + item.image + '" alt="' + item.title + '">' : '');
output += '<span class="search-autocomplete__title">' + item.title + '</span>';
output += (item.attribute ? '<span class="search-glasses__attribute">' + item.attribute + '</span>' : '');
output += '<ul class="product-spot__variants">';
output += html;
output += '</ul>';
output += '</a>\n';
output += '</div>\n';
return output;
}
ok so I just created another conditional for the string and put the html equals code there..
otherwise everything was fine
if (typeof item.color === 'string') {
html = "<li class='product-spot__variants-variant' style='background-color:"+ glassesColor +"' title='"+ glassesColor +"'>'"+ glassesColor +"'</li>";
}

jQuery/JSON data not looping in created HTML

Currently trying to loop through a JSON file and for each object, create a article tag around the data as I format it with HTML, I am successful and creating the first article tag but the I cannot loop through to the next object with the $.each function
HTML code
<body>
<div id='container'>
<div id='content'>
<article class='tumblrPost'>
<header>
<h1> Dragonball Z Motivation </h1>
</header>
<img src='images/dragonball_z.jpg' alt='dragonball z' title='dbz' />
<footer>
<h1> Watch the Video Life & Motivation with Dragonball Z </h1>
</footer>
</article>
</div>
</div>
</body>
</html>
('document').ready(function() {
getPosts();
});
function getPosts() {
var articlePosts = $('div#content article');
$.getJSON('animeTest.json', function(data) {
$.each(data, function(key, val) {
output = "<article>";
output += "<header>";
output += "<h1>" + val.header + "</h1>";
output += "</header>";
output += "<img src='images/" + val.image + "' title='image' />";
output += "<footer>";
output += "<h1>" + val.footer + "</h1>";
output += "</footer>";
output += "</article>";
});
articlePosts.last().after(output);
});
}
You are overwriting output on each cycle
output = "<article>";
Quick fix: try appending the content inside the loop cycle too (and don't declare a global)
$.each(data, function(key, val) {
var output = "<article>";
output += "<header>";
output += "<h1>" + val.header + "</h1>";
output += "</header>";
output += "<img src='images/" + val.image + "' title='image' />";
output += "<footer>";
output += "<h1>" + val.footer + "</h1>";
output += "</footer>";
output += "</article>";
articlePosts.last().after(output);
});
BTW, I feel more comfortable operating on jQuery elements instead of concatenating html. You should try it!
var output = $('<article></article');
var header= $('<header></header');
header.append("<h1>" + val.header + "</h1>").appendTo(output);
output.append("<img src='images/" + val.image + "' title='image' />");
var footer= $ ('<footer></footer>');
footer.append("<h1>" + val.footer + "</h1>").appendTo(output);
articlePosts.last().after(output);
it saves you the pain of closing tags
You're resetting output on each iteration. Technically, you are probably only seeing the last result shown as an article in the HTML.
Instead, declare output right before $.each(), and then only ever append to it. Once you're done looping, append the entire result to your page:
function getPosts() {
var articlePosts = $('div#content article');
$.getJSON('animeTest.json', function(data) {
var output = ''; // make sure you use 'var' so it's not a global variable
$.each(data, function(key, val) {
output += "<article>";
output += "<header>";
output += "<h1>" + val.header + "</h1>";
output += "</header>";
output += "<img src='images/" + val.image + "' title='image' />";
output += "<footer>";
output += "<h1>" + val.footer + "</h1>";
output += "</footer>";
output += "</article>";
});
articlePosts.last().after(output);
});
}
Lastly, if you find yourself building HTML like this often, I would suggest looking into various HTML/JavaScript templating solutions. They would make your JavaScript code far cleaner and easier to maintain by keeping your HTML and JavaScript separate.

How to add new class to the existing class in this case

I am new to Javascript and Jquery so please excuse if this is a dumb question
HTML is being constructed dynamically as shown
var favoriteresultag = '<ul>';
favoriteresultag += "<section id='"+name+"' class='ulseWrap lielement'>" + "<div class='intit someclassss'>"+ name + "</div>" + "</section>";
How can i add/concat one more variable to the class ulseWrap lielement ??
I tried this way
var classactive = '';
if (some condition) {
classactive = 'activeRest';
} else {
classactive = '';
}
favoriteresultag += "<section id='" + name + "' class='ulseWrap lielement '+classactive+' '>" + "<div class='intit someclassss'>" + name + "</div>" + "</section>";
String concatenation, just like you're doing:
favoriteresultag += "<section id='"+name+"' class='ulseWrap lielement " + classactive + "'>" + "<div class='intit someclassss'>"+ name + "</div>" + "</section>";
Try this with jquery if you are using it
$('.actual_class').addClass('new_class')
In your case can be
$('#'+name).addClass('activeRest')
or
$('.ulseWrap.lielement').addClass('activeRest')

Add anchor point to headers?

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.

Categories

Resources