JavaScript, Adding html to jQuery append function - javascript

I am trying to use jQuery to add buttons on a page. I would like the buttons to appear vertical instead of horizontal. So I try
$(".guess").append("<p>" + guess_answer + "</p>");
But then it prints to the page:
[object Object]
[object Object]
[object Object]
[object Object]
Instead of the buttons. I have test the code without the paragraph tags and it works but doesn't when the html is place in it.
var question1 = {
question: "What is 4 times 1?",
answer: "Dream On",
possible: [1,2,3,4],
boolean: [true,false,false,false]
};
function generate () {
$(".question").html(question1.question);
for (var i = 0; i < question1.possible.length; i++) {
var guess_answer = $('<button>');
guess_answer.addClass("options text-center btn-group-lg");
guess_answer.attr({
"data-boolean" : question1.boolean[i]
});
guess_answer.text(question1.possible[i]);
//guess_answer.append(question1.possible[i]);
$(".guess").append("<p>" + guess_answer + "</p>");
}
}

Use guess_answer.prop("outerHTML") to get the element as HTML string
var question1 = {
question: "What is 4 times 1?",
answer: "Dream On",
possible: [1,2,3,4],
boolean: [true,false,false,false]
};
function generate () {
$(".question").html(question1.question);
for (var i = 0; i < question1.possible.length; i++) {
var guess_answer = $('<button>');
guess_answer.addClass("options text-center btn-group-lg");
guess_answer.attr({
"data-boolean" : question1.boolean[i]
});
guess_answer.text(question1.possible[i]);
//guess_answer.append(question1.possible[i]);
$(".guess").append("<p>" + guess_answer.prop("outerHTML") + "</p>");
}
}

Its because guess_answer as defined in your generate function contains a button object, you cannot append a HTML entity combining it with html tags using append.
If you want to add a button to the HTML, then simply write it in the append like so:
$(".guess").append("<p><button value='123'/></p>");
However you should use the class name to append HTML content, whilst it is valid, a class might not be unique and if you add content with ID's then you may create multiple instances with the same ID which isn't valid.

Your variable guess_answer is an object, more specifically a jQuery object holding a DOM node.
Use DOM methods to insert it
function generate() {
$(".question").html(question1.question);
for (var i = 0; i < question1.possible.length; i++) {
var guess_answer = $('<button />', {
'class' : 'options text-center btn-group-lg',
'data-boolean' : question1.boolean[i],
text : question1.possible[i]
}),
p = $('<p />');
$(".guess").append( p.append(guess_answer) );
}
}

I tried using appendTo(...) - like this
guess_answer.appendTo('.guess');
See code below:
var question1 = {
question: "What is 4 times 1?",
answer: "Dream On",
possible: [1, 2, 3, 4],
boolean: [true, false, false, false]
};
function generate() {
$(".question").text(question1.question);
for (var i = 0; i < question1.possible.length; i++) {
var guess_answer = $('<button>');
guess_answer.addClass("options text-center btn-group-lg");
guess_answer.attr({
"data-boolean": question1.boolean[i]
});
guess_answer.text(question1.possible[i]);
//guess_answer.append(question1.possible[i]);
var newPar = $("<p>");
newPar.appendTo('.guess');
guess_answer.appendTo(newPar);
}
}
generate();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="question"></div>
<div class="guess"></div>

Related

Use Javascript to write names that don't appear in master list to div with id

Working demo at http://verlager.com/pairing.php uses document.write() but I would prefer to write to a div's ID. I have tried several methods but I can't get the for loop to write to div with id of "textDiv".
<script>
function newly_minted() {
var res = "Attaya, James J|Blazak, Stephen A|Cavanaugh, Michael P|Decker, Howard|";
document.getElementById("textDiv").textContent = res;
}
newly_minted();
</script>
<div id="textDiv" style="background:green; color:fff; display:table; height:10rem; width:40rem; margin:4rem auto; clear:both;"></div>
For original post:
This code replaces textDiv content because of the simple assignment used:
var div = document.getElementById("textDiv");
div.textContent = resort;
var text = div.textContent; //should append not replace!
Try the '+=' operator instead:
var div = document.getElementById("textDiv");
div.textContent += resort;
var text = div.textContent; //should append not replace!
For the updated post:
Declare newly_minted before calling it from a different script element. Hoisting function declarations only applies to the script element in which the function is declared.
Replace $( resort) with resort (and split resort on "|" as in the original). The trailing "|" is not altered in this demonstration:
function newly_minted() {
var res = "Attaya, James J|Blazak, Stephen A|Cavanaugh, Michael P|Decker, Howard|".split('|');
for (let i = 0; i < res.length; i++) {
var resort = res[i] + " ● ";
$( "#textDiv" ).append(resort);
}}
newly_minted();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="textDiv"></div>
Alternatively, without using jQuery, preparing text content first and removing trailing dots:
function newly_minted() {
var res = "Attaya, James J|Blazak, Stephen A|Cavanaugh, Michael P|Decker, Howard|".split('|');
for (var i = 0, text =""; i < res.length; i++) {
text += res[i] + " \u25cf ";
}
text = text.replace(" \u25cf \u25cf ", ""); // remove two trailing dots
document.getElementById("textDiv").textContent = text;
}
newly_minted();
<div id="textDiv"></div>

How to write all data from Array?

I have HTML like :
<div id="divid">
1
2
3
.....................
</div>
I have script to get all links from a div like :
<script>
var links = document.getElementById('divid').getElementsByTagName('a') ;
</script>
Then I want write link into class like :
<script>
var links = document.getElementById('divid').getElementsByTagName('a') ;
document.write("<div class="'+link[1]+" "+ link[i]+'">Class is added links</div>");
</script>
That mean after write I have HTML:
<div class="d#link1 d#link2 d#link3">Classes is added links</div>
How can I do this? Using for loop or not? how?
You have to get the href property from each element. Put them in an array, and you can just join the strings:
var elements = document.getElementById('divid').getElementsByTagName('a');
var links = [];
for (var i = 0; i < elements.length; i++) {
links.push(elements[i].href);
}
document.write("<div class="' + links.join(" ") + '">Class is added links</div>");
Use join in combination with map:
var classString = links.map(function(link) { return link.attributes.href; } ).join(' ');

Javascript create multiple links?

I need to find a way to use javascript to make multiple links for my left nav. I will have seperators dividing the links into categories.
This is my current code.
links = new Array();
links[1]="<span class='asep' style='border-top: 0px; margin-top: 0px;'>Welcome</span>";
links[2]="<a href='#'>Home</a>";
links[3]="<span class='asep'>Body Jewelry</span>";
links[4]="<a href='#'>Circular Barbells</a>";
links[5]="<a href='#'>Belly Button</a>";
links[6]="<a href='#'>Curved Barbells</a>";
links[7]="<span class='asep'>User Controls</span>";
links[8]="<a href='#' onclick='window.print(); return false'>Print This Page</a>";
function writeLinks() {
document.getElementById('nav1').innerHTML = links[1] + links[2] + links[3] + links[4] + links[5] + links[6] + links[7] + links[8];
document.getElementById('featured').innerHTML = ' <b>Featured Product</b><br><img src="icon1.gif" border="0"><br>Product Title';
}
setTimeout(writeLinks, 0); // Fires the function on page load without stopping other loads
Is there an easier way to do this?
There are various aspects of your methods which can be made "easier":
links = new Array();
Can be better-written as links = [];. (almost) everything you'll come across in Javascript is already an object, so being verbose about it doesn't add clarity.
links[1]="first..."
links[2]="second...";
can be better-written using .push(), so that you don't need to specify each index, eg:
links.push("first");
links.push("second");
or, if you're doing it all at once, using an array-literal, eg:
links = [
"first",
"second"
];
less-nice, in my opinion, but also an option, could be a mixture of both, using .concat():
links = [
"first",
"second"
];
links = links.concat([
"third",
"fourth"
]);
It might make sense to group things together using an array of bare objects, too:
sections = [
{
heading: '<span class="asep">First section...</span>',
links: [
'First',
'Second'
]
},
{
heading: '<span class="asep">Second section...</span>',
links: [
'Third',
'Fourth'
]
},
];
function writeLinks(){
var html = "";
for( var i = 0; i < sections.length; i++ ){
var section = sections[i];
html += section.heading + section.links.join("");
}
document.getElementById('nav1').innerHTML = html;
}
setTimeout(writeLinks, 0);
Note also the use of .join("") to join all elements of an array together as strings.
Next, you've got a lot of duplication in your code. You could specify only the parts which are different, eg:
sections = [
{
heading: "First section...",
links: [
"First",
"Second"
]
},
/* ...snip... */
];
function writeLinks(){
var html = "";
for( var i = 0; i < sections.length; i++ ){
var section = sections[i];
html += '<span class="asep">' + section.heading + "</span>";
for( var j = 0; j < section.links.length; j++ ){
html += '' + section.links[j] + "";
}
}
document.getElementById('nav1').innerHTML = html;
}
setTimeout(writeLinks, 0);
You could get rid of some of that raw HTML and simplify some of the loops, etc, by using a common library, such as jQuery or Prototype. This would also allow you to actually check that the document is ready for you to operate on it, rather than using that fragile setTimeout() hack. eg:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
/* ...snip... */
$(function(){
var nav = $("<div />").attr("id", "nav1");
$.each(sections, function(i,section){
nav.append( $("<span />").addClass("asep").text(section.heading) );
$.each(section.links, function(i,link){
nav.append( $("<a />").attr("href", "#").text(link) );
}
}
$("#nav1").replaceWith( nav );
});
</script>
All of those may be considered "easier" depending on your mood.
var arr = [];
arr[0] = <span class='asep'>Body Jewelry</span>;
arr[1] = <span class='asep'>Do Something</span>;
function writeLinks(){
document.getElementById("nav1").innerHTML = arr.join("");
}
Array.Join is faster than concat operation .
This might be a bit overkill, but you might want to look at a client side framework that supports models and templates, such as backbone.js. Then you could store all your links in a model which can easily be changed (and will automatically update the view for you through events), and you can also use underscore.js templates so you don't have to write any html as a string literal.

print array with js and add html with jQuery

i want to print an array with js and just add to every element some data with html()
the code i use is :
<script type="text/javascript">
$(document).ready(function() {
var testArray = ["test1","test2","test3","test4"];
for(var i=0;i<testArray.length;i++){
document.write(" " +testArray[i]+"<br />").html("is the best");
}
});
</script>
but it doesnt works.
HTML:
<div id="myDIV"></div>
JS:
$(document).ready(function() {
var testArray = ["test1","test2","test3","test4"];
var vPool="";
jQuery.each(testArray, function(i, val) {
vPool += val + "<br /> is the best <br />";
});
//We add vPool HTML content to #myDIV
$('#myDIV').html(vPool);
});
Update:
Added demo link: http://jsfiddle.net/aGX4r/43/
Syntax problem mate!
Let me get that for you!
// first create your array
var testArray = ["test1", "test2", "test3", "test4"];
// faster ready function
$(function(){
for( var i=0; i<testArray.length; i++ ) {
current = testArray[i] + '<br />' + 'is the best'; // this is a string with html in it.
$(current).appendTo("body"); // add the html string to the body element.
}
});
First. document.write it's not a good practice.
Then, you code have a little error: Function (as in document.write) doesn't have html method. Thats a jQuery method.
So, in order to print the array in the body, you could do:
$('p').html(["test1","test2","test3","test4"].join('<br />')).appendTo(document.body);
It's a little difficult to tell what you want to do, but if you want to append to an element in your DOM, use jQuery.append();
for(var i=0;i<testArray.length;i++) {
jQuery('#mydiv').append(testArray[i]);
}

cannot set selectedIndex off select with javascript

I have this code and I keep getting undefined if I test the selectedIndex.
alert(x.selectedIndex);
So, setting it is also a problem.
Does anyone possibly see what the problem is?
//makes list off tags
function ttyps_select(data,naamsel,selectid, containerid){
if(!ttyps.length){
jQuery.each(data, function(index, itemData) {
ttyps.push( new Tagtype(itemData.tag_id, itemData.tag ));
});
}
opties = "<option value=\"-1\"></option>\n";
for(var i=0; i<ttyps.length; i++) {
var dfnkey = ttyps[i].tag_id;
var dfnsel = ttyps[i].tag;
if (dfnkey==selectid) {
opties +="<option value="+ttyps[i].tag_id+" SELECTED>"+dfnsel+"</option>\n";
} else {
opties +="<option value="+dfnkey+">"+dfnsel+"</option>\n";
}
}
$("<select name=\"" + naamsel + "\" size=\"1\" ></select>")
.html(opties)
.change(function(e){
select_tag(containerid);
})
.appendTo("#"+naamsel);
}
function select_tag(id) {
var x = $('#frmttypid'+id+' select');
var ttidx = x.val();
var tag = getTagtype(ttidx).tag;
x.selectedIndex=0;
x.blur();
if( tag ){
document.forms['frmtags']['frmtag'+id].value=tag;
}
}
thanks, Richard
$('selector') (jQuery) returns an object with array-like collection of matched DOM nodes. Your x variable is an jQuery object, not a reference to any particular <select/> element. use
x[0].selectedIndex
x[0] is a reference to the first DOM node in the jQuery object.

Categories