How to get html output for variable? - javascript

I have such a script (changed and easyfied for better understanding):
$(document).ready(function() {
var summary;
function validateSteps(stepnumber){
if(stepnumber == 1){
...
var resultStep1 = '<b>Shape1: </b>' + $('#chooseshape1').val();
summary = resultStep1;}
if(stepnumber == 2){
...
var resultStep2 = '<b>Shape2: </b>' + $('#chooseshape2').val();
summary += resultStep2;}
if(stepnumber == 3){
...
var resultStep3 = '<b>Shape3: </b>' + $('#chooseshape3').val();
summary += resultStep3;}
}
$('#resultSteps').val(summary);
}
I get no output for #resultSteps
Only when I write $('#resultSteps').text(summary); I get output in that div but it looks like:
<b>Shape1: </b>round, <b>Shape2: </b>square<b>Shape3: </b>rectangle
But I want output like this:
Shape1: round Shape2: sqaure Shape3: rectangle
How to achieve this?

$("#resultSteps").html(summary);

Use .html which outputs the elements as they should be, so <b>text</b> would become text.
$("#resultSteps").html(summary);
.val wouldn't work as I presume #resultSteps is not an input-field.
.text would probably remove the tags (<b>).
Docs

Related

Why doesn't my innerHTML method work to list things in my contact form?

I am making a program, and I'm wondering why all I see on my html page is the form, but only a single . where the bulleted list for an unordered list should be. I input the user input in the fields, but it doesn't show me the data in the fields, like it's supposed to, when I click submit. Here's the code.
function getFormElements() {
var gather_form_elements = new Array(
$("#first_name").val(),
$("#last_name").val(),
$("email").val(),
$("#phone_number").val()
);
displayValues(gather_form_elements);
}
function displayValues(gather_form_elements) {
for(i=0; i<gather_form_elements.length; i++)
{
document.getElementById("contact_info").innerHTML = "<li>" + gather_form_elements[i] + "</li>";
}
}
Because you are overiding it on every iteration. Try to accumulate the html before using innerHTML like this:
var html = "";
for(var i = 0; i < gather_form_elements.length; i++) {
html += "<li>" + gather_form_elements[i] + "</li>";
// ^^ the += is crucial. If you don't use it, it will just replace the content of html (the innerHTML in your code), we need to use += to append to html instead of overriding it.
}
document.getElementById("contact_info").innerHTML = html;
You can acheive the same result using only one line of code:
document.getElementById("contact_info").innerHTML =
'<li>' + gather_form_elements.join('</li><li>') + '</li>';

li append function not work

I'm using blogger as my blogging platform. In my blog homepage, I create a function to grab all images from single post for each post (there are 5 posts in my homepage), then append all images from single post to single slider, for each post.
This is my function script (I place it after <body> tag):
<script type='text/javascript'>
//<![CDATA[
function stripTags(s, n) {
return s.replace(/<.*?>/ig, "")
.split(/\s+/)
.slice(0, n - 1)
.join(" ")
}
function rm(a) {
var p = document.getElementById(a);
img = p.getElementsByTagName("img").each( function(){
$(".flexslider .slides").append($("<li>").append(this));
});
p.innerHTML = '<div class="entry-container"><div class="entry-content"><div class="entry-image"><div class='flexslider'><ul class='slides'></ul></div></div><div class="entry-header"><h1>' + x + '</h1></div><p>' + stripTags(p.innerHTML, SNIPPET_COUNT) + '</p></div></div>'
}
//]]>
</script>
Then my variable, each post have single variable, different for each post based on it's ID:
<script type='text/javascript'>var x="Post Title",y="http://myblog.url/post-url.html";rm("p8304387062855771110")
My single post markup:
<span id='p8304387062855771110'></span>
The problem is, the append function in my script not work. Am I forget something in my code?
Your jQuery/JavaScript is very ropey. There is no method each on a nodelist. Try not to mix jQuery/JavaScript up so much. And you might consider using a array/join on the html you want to insert to keep the line length readable. That way you might have noticed that your HTML quotes were not consistent.1
var $p = $('#' + a);
$p.find('img').each(function () {
var html = $('<li>').append($(this))
$('.flexslider .slides').append(html);
});
var html = [
'<div class="entry-container"><div class="entry-content">',
'<div class="entry-image"><div class="flexslider">',
'<ul class="slides"></ul></div></div><div class="entry-header">',
'<h1><a href="',
y,
'">',
x,
'</a></h1></div><p>',
stripTags(p.innerHTML, SNIPPET_COUNT),
'</p></div></div>'
].join('');
$p.html(html);
1 Personally I prefer single quotes for JS work and double quotes for HTML attributes and never the twain shall meet.
I think <li> doesnt work try li like this:
$(".flexslider .slides").append($("li").append(this));
You could get rid of type="text/javascript" and //<![CDATA[, it is 2014, after all ;-)
Also, .*? is not what you mean.
<script>
function stripTags(s, n) {
return s.replace(/<[^>]*>/g, "") // Be careful with .*? : it is not correct
.split(/\s+/)
.slice(0, n - 1)
.join(" ")
}
function rm(id) {
var $p = $('#' + id);
img = $p.find("img").each( function(){
$(".flexslider .slides").append($("<li>").append(this));
});
p.innerHTML = '<div class="entry-container"><div class="entry-content"><div class="entry-image"><div class="flexslider"><ul class="slides"></ul></div></div><div class="entry-header"><h1>' + x + '</h1></div><p>' + stripTags(p.innerHTML, SNIPPET_COUNT) + '</p></div></div>'
}
</script>

Javascript generating content from an array on user search

I'm having issues dynamically creating content from an array of images. What I want to happen is that when keywords are entered into the searchbar (try "joyride" or "nick"), all of the images that match the keywords show up. Currently, only one image shows up, and it doesn't necessarily match the keyword. I think I'm going wrong with the javascript function - I feel like I shouldn't be using innerHTML to create the photos, especially because when the keyword is deleted, it just leaves the one image.
Would it be easier to do it all in jQuery/javascript, instead of generating the initial gallery of images in jQuery and trying to do the filtering in javascript? I'm lost.
http://scf.usc.edu/~uota/itp301/final/odc-photos.html
This is a working version of the page, with the arrays and other code that I am using.
Thanks in advance!
$(document).ready(function(){
for(var i = 0; i < src.length; i++){
var content = "<div class='pics' id='imagesection" + i + "'>";
content += "<div class='images'><img class='imagesfiles' height='133px' width='200px' src='" + src[i] + "'></div>";
content += "</div>";
$("#gallery").append(content).hide().fadeIn(250);
}
});
var songSearch = function(keyword){
var foundFlag = false;
var content = "";
for (var i = 0; i < src.length; i++){
if (tags[i].toLowerCase().indexOf(keyword) != -1 || keyword == "") {
content = "<div class='pics' id='imagesection" + i + "'>";
content += "<div class='images'><img class='imagesfiles' height='133px' width='200px' src='" + src[i] + "'></div>";
content += "</div>";
findFlag = true;
}
}
if(findFlag){
document.getElementById("gallery").innerHTML = content;
}
else{
content = "Your search did not return any results.";
}
}
</script>
It looks like the problem is on this line in the songSearch function:
content = "<div class='pics' id='imagesection" + i + "'>";
You are redefining the variable content instead of concatenating it. This way it will always be just the last image. Try changing it to:
content += "<div class='pics' id='imagesection" + i + "'>";
There is also have a variable inside the songSearch function called foundFlag that is later referenced as findFlag. That shouldn't be causing the issue though.

How do I make keep these values from rewriting into the HTML?

I have a small piece of code that is writing some values into a textarea inside a form. The write whenever I click a button. However if I click the button more than once they will write over and over. I need to be able to click the button multiple times (for example if the user changes a value) and have the values that I am writing simply refresh rather than repeat. Here is what I have...
var endwallPanelLengths = [totalHeightInches];
var i = 0;
while (endwallPanelLengths[i] > eaveInches)
{
endwallPanelLengths.push(endwallPanelLengths[i] - peakHeightDecrease);
document.getElementById("test83").value += "4 - " + endwallPanelLengths[i] + "\n";
i++;
}
When I click the button the first time the values are correct however they write again after everytome i click it?
In this line:
document.getElementById("test83").value += "4 - " + endwallPanelLengths[i] + "\n";
you're appending a value to test83. Presumably (since I can't see your html!!!) you just need to remove the + from the +=.
EDIT: in case you want to append all of the values in your loop, and nothing else, simply clear the value before you enter your loop and leave the +=
document.getElementById("test83").value = "";
var endwallPanelLengths = [totalHeightInches];
......
I think you want to do the whole iteration when the user change a value. Then you just need to reset the value of the textarea to empty before the loop. Something like this:
var endwallPanelLengths = [totalHeightInches];
var i = 0;
document.getElementById("test83").value = ''; //Reset the value
while (endwallPanelLengths[i] > eaveInches) {
endwallPanelLengths.push(endwallPanelLengths[i] - peakHeightDecrease);
document.getElementById("test83").value += "4 - " + endwallPanelLengths[i] + "\n";
i++;
}
I have worked out a demo page. Hope that is what you are after.
Try this:
var endwallPanelLengths = [totalHeightInches];
var i = 0;
document.getElementById("test83").value = '';
while (endwallPanelLengths[i] > eaveInches)
{
endwallPanelLengths.push(endwallPanelLengths[i] - peakHeightDecrease);
document.getElementById("test83").value += "4 - " + endwallPanelLengths[i] + "\n";
i++;
}
I'm assuming that all the code is executed eacht time you click the button, am I right ?
you need to implement a clickEventhandler that checks whether or not your texts exists.....

inline if else statements in jQuery

I have a jQuery function that is executed by two different buttons.
$("#btnSearch, #btnDirectorSearch").click(function () {
Part of the html that this function builds depends on which button was hit. I am using data- attributes to store my variables like this:
var div = $(this).data("str");
And the html string I am building depends on what value the variable "div" is. Is there a way to do an inline if/else statement in jQuery?
if div = "choice1" {
html += '<tr data-str = "str1" data-dataItem = "dataItem1" data-result-title = "' + name + '" data-result-id="' + sel + '">';
} else {
html += '<tr data-str = "str2" data-dataItem = "dataItem2" data-result-title = "' + name + '" data-result-id="' + sel + '">';
}
That seems cumbersome and I'm hoping there is a better jQuery way of doing this.
Thanks!
you have a syntax error
if div = "choice1"
should be
if (div == "choice1")
Anyway, the pattern you're looking for is:
div == "choice1" ? <code for true> : <code for false>
you can use condition ? code when true: code when false
but i would suggest you to stick with curley braces only, as it looks better and easier to debug.
one more thing , do it as below
if(div==="choice1"){
}
else{
}
use ===
Since it's only the number that changes in the output, you could do this:
var num = div == "choice1" ? 1 : 2;
html += '<tr data-str="str'+num+'" data-dataItem="dataItem'+num+'" data-result-title="'+name+'" data-result-id="' + sel + '">';
If your choices are limited, you could add a small lookup array:
var choices = {
choice1: {
str: "str1",
data: "dataItem1"
},
choice2: { ... }
};
html += '<tr data-str="' + choices[div].str
+ '" data-dataItem="' + choices[div].data
+ '" data-result-title="' + name + ... etc;

Categories

Resources