create Dynamic HTML Element In JS - javascript

var vStatus = "welcome";
var val = '';
var fContactInfo = new Array();
fContactInfo.push('<div class="readText"> <div class="leftText">123</div><div class="middleText">'+ if(vStatus != ""){ +'<div>Sent'+vStatus+'</div>'+} if(val! = ''){ +'<div>Submitted '+val+'</div>'+}+'</div> <div class="rightText"></div></div>');
$('#A1').html(fContactInfo.join(' '));
**
http://jsfiddle.net/JaqfH/
**
Hello Everyone,
I am trying to create new html element here but the value which i give are conditional. when try the above code it gives me error. can anyone please help me with this.

You had syntax errors in your code.
Corrected: http://jsfiddle.net/vGcT8/1/
You can't add strings and if expressions.

Related

JS exstract part of URL from multiple form fields

I have a form that has multiple fields all with the same class. These are populated with URL's that follow the same structure. I am trying to extract the same section from each URL. So far var res = x.split('/')[5]; will achieve this but only for the first URL. I can also use var x = document.querySelectorAll(".example") to change all the url's but I cannot find the correct way to combine both of these function. so far my code looks like this:
script>
function myFunction() {
var x = document.querySelectorAll(".example").innerHTML;
var res = x.split('/')[5];
var i;
for (i = 0; i < x.length; i++) {
x[i].innerHTML = res;
}
}
</script>
I have looked around but can't find a solution that fits. Thanks in advance for your help.
So loop over the HTML Collection, this is making assumptions based on code.
// Find all the elements
var elems = document.querySelectorAll(".example")
// loop over the collection
elems.forEach(function (elem) {
// reference the text of the element and split it
var txt = elem.innerHTML.split("/")[5]
// replace the text
elem.innerHTML = txt
})
<div class="example">1/2/3/4/5/a</div>
<div class="example">1/2/3/4/5/b</div>
<div class="example">1/2/3/4/5/c</div>
<div class="example">1/2/3/4/5/d</div>
<div class="example">1/2/3/4/5/e</div>
<div class="example">1/2/3/4/5/f</div>

text string output stops after first space, js/html

I apologize in advance, this is the first Stack Overflow question I've posted. I was tasked with creating a new ADA compliant website for my school district's technology helpdesk. I started with minimal knowledge of HTML and have been teaching myself through w3cschools. So here's my ordeal:
I need to create a page for all of our pdf and html guides. I'm trying to create a somewhat interactable menu that is very simple and will populate a link array from an onclick event, but the title="" text attribute drops everything after the first space and I've unsuccessfully tried using a replace() method since it's coming from an array and not static text.
I know I'm probably supposed to use an example, but my work day is coming to a close soon and I wanted to get this posted so I just copied a bit of my actual code.
So here's what's happening, in example 1 of var gmaildocAlt the tooltip will drop everything after Google, but will show the entire string properly with example 2. I was hoping to create a form input for the other helpdesk personnel to add links without knowing how to code, but was unable to resolve the issue of example 1 with a
var fix = gmaildocAlt.replace(/ /g, "&nb sp;")
//minus the space
//this also happens to break the entire function if I set it below the rest of the other variables
I'm sure there are a vast number of things I'm doing wrong, but I would really appreciate the smallest tip to make my tooltip display properly without requiring a replace method.
// GMAIL----------------------------
function gmailArray() {
var gmaildocLink = ['link1', 'link2'];
var gmaildocTitle = ["title1", "title2"];
var gmaildocAlt = ["Google Cheat Sheet For Gmail", "Google 10-Minute Training For Gmail"];
var gmailvidLink = [];
var gmailvidTitle = [];
var gmailvidAlt = [];
if (document.getElementById("gmailList").innerHTML == "") {
for (i = 0; i < gmaildocTitle.length; i++) {
arrayGmail = "" + gmaildocTitle[i] + "" + "<br>";
document.getElementById("gmailList").innerHTML += arrayGmail;
}
for (i = 0; i < gmailvidTitle.length; i++) {
arrayGmail1 = "";
document.getElementById("").innerHTML += arrayGmail1;
}
} else {
document.getElementById("gmailList").innerHTML = "";
}
}
<div class="fixed1">
<p id="gmail" onclick="gmailArray()" class="gl">Gmail</p>
<ul id="gmailList"></ul>
<p id="calendar" onclick="calendarArray()" class="gl">Calendar</p>
<ul id="calendarList"></ul>
</div>
Building HTML manually with strings can cause issues like this. It's better to build them one step at a time, and let the framework handle quoting and special characters - if you're using jQuery, it could be:
var $link = jQuery("<a></a>")
.attr("href", gmaildocLink[i])
.attr("title", gmaildocAlt[i])
.html(gmaildocTitle[i]);
jQuery("#gmailList").append($link).append("<br>");
Without jQuery, something like:
var link = document.createElement("a");
link.setAttribute("href", gmaildocLink[i]);
link.setAttribute("title", gmaildocAlt[i]);
link.innerHTML = gmaildocTitle[i];
document.getElementById("gmailList").innerHTML += link.outerHTML + "<br>";
If it matters to your audience, setAttribute doesn't work in IE7, and you have to access the attributes as properties of the element: link.href = "something";.
If you add ' to either side of the variable strings then it will ensure that the whole value is read as a single string. Initially, it was assuming that the space was exiting the Title attribute.
Hope the below helps!
UPDATE: If you're worried about using apostrophes in the title strings, you can use " by escaping them using a . This forces JS to read it as a character and not as part of the code structure. See the example below.
Thanks for pointing this one out guys! Sloppy code on my part.
// GMAIL----------------------------
function gmailArray() {
var gmaildocLink = ['link1', 'link2'];
var gmaildocTitle = ["title1", "title2"];
var gmaildocAlt = ["Google's Cheat Sheet For Gmail", "Google 10-Minute Training For Gmail"];
var gmailvidLink = [];
var gmailvidTitle = [];
var gmailvidAlt = [];
if (document.getElementById("gmailList").innerHTML == "") {
for (i = 0; i < gmaildocTitle.length; i++) {
var arrayGmail = "" + gmaildocTitle[i] + "" + "<br>";
document.getElementById("gmailList").innerHTML += arrayGmail;
}
for (var i = 0; i < gmailvidTitle.length; i++) {
var arrayGmail1 = "";
document.getElementById("").innerHTML += arrayGmail1;
}
} else {
document.getElementById("gmailList").innerHTML = "";
}
}
<div class="fixed1">
<p id="gmail" onclick="gmailArray()" class="gl">Gmail</p>
<ul id="gmailList"></ul>
<p id="calendar" onclick="calendarArray()" class="gl">Calendar</p>
<ul id="calendarList"></ul>
</div>

How do I remove the string values?

I was trying to figure out on how can I remove the string values. And also when I can remove them all? So here's the code.
HTML:
<div id="a"> </div>
<div id="x" onclick="EraseAll()"> </div>
JAVASCRIPT:
function ABC(){
document.getElementById('a').innerHTML += "<img src=\"buttonx.png\" id=\"Erase\" onclick=\"Erase()\"> </div>" + document.getElementById('n').value + document.getElementById('q').value + parseInt(document.getElementById('t').value);
}
Ive tried this code, but it won't work,
function Erase(){
var n = document.getElementById('n').value;
var q = document.getElementById('q').value;
var t = document.getElementById('t').value;
n = n.replace(n, " ");}
I'm still learning Javascript , so if any help would do, and also please only use Javascript, I've been asked to use Javascript only.
If I understand what you're looking for this should do it -
document.getElementById('n').value = '';
document.getElementById('q').value = '';
document.getElementById('t').value = '';

Trying to set a variable using document.getElementById('').innerHTML

I am utterly new to JavaScript and am trying to self-learn a few things - so be gentle.
I am trying to set a variable using document.getElementById(' ').innerHTML but I can't get it to work - I just get "undefined" returned when I try to use this variable.
All of the examples I have seen says that this should work, but it isn't and I'm at my wits' end. Any help will be greatly appreciated.
This is the code...
<script>
var str = document.getElementById('str').innerHTML;
function calc()
{
if(document.getElementById('checkbox').checked)
document.getElementById('str').innerHTML = str ;
else
document.getElementById('str').innerHTML='unchecked';
}
</script>
Checkbox: <input type="checkbox" id="checkbox" name="checkbox" onclick="calc();"/>
<div>Str: <span id="str">6</span></div>
My ultimate aim is to add a number to the variable "str" using another variable; so something like...
var str = document.getElementById('str').innerHTML;
var add = 2
function calc()
{
if(document.getElementById('checkbox').checked)
document.getElementById('str').innerHTML = str + add;
else
document.getElementById('str').innerHTML='unchecked';
}
I'm aware that I probably need to parse the str variable as an integer for this, but I've stumbled before I've even got that far.
Please help.
The value of str is determined when the page is loading (and before the element exists). I believe you want it inside calc:
function calc()
{
var span = document.getElementById('str');
var str = span.innerHTML;
var add = 2;
if(document.getElementById('checkbox').checked)
span.innerHTML = str + add;
else
span.innerHTML = 'unchecked';
}
The problem is that your span is below the script and actually str is not still there. Here is an example which works http://jsfiddle.net/krasimir/2C25E/
<script>
function calc() {
var str = document.getElementById('str').innerHTML;
var add = 2;
if(document.getElementById('checkbox').checked)
document.getElementById('str').innerHTML = parseInt(str) + add;
else
document.getElementById('str').innerHTML='unchecked';
}
</script>
Checkbox: <input type="checkbox" id="checkbox" name="checkbox" onclick="calc();"/>
<div>Str: <span id="str">6</span></div>
Also you should use parseInt to be sure that you get a Number and not a String.
if you had included the script in side the <head>tag This will work for you.
function calc() {
var str = document.getElementById('str').innerHTML;
//more code
Try this, a working version and a bit optimised:
var str = document.getElementById('str');
var chk = document.getElementById('checkbox');
var add = 2
function calc() {
chk.checked ? str.innerHTML = parseInt(str.innerHTML) + add : str.innerHTML = 6;
}
chk.onchange = function () {
calc();
};
Demo here

How to extract all hyperlink titles from big html string using javascript?

I got an HTML string as :var code; I want to extract all hyper link title values in this big string and place them in textarea. I tried the following but it never works. could any one tell me what i am doing wrong?
sample hyperlinks to look for(i want to extract mango,cherry,...) :
mango
cherry
my code string has blocks of data like below:
<div class="details">
<div class="title">
mango
<span class="type">3</span>
</div>
</div>
full code:
$.getJSON('http://anyorigin.com/get?url=http://asite.com/getit.php/&callback=?', function(data){
//$('#output').html(data.contents);
var siteContents = data.contents;
//writes to textarea
document.myform.outputtext.value = siteContents ;
var start = siteContents.indexOf('<ul class="list">');
var end = siteContents.indexOf('<ul class="pag">', start);
var code = siteContents.substring(start, end);
document.myform2.outputtext2.value = code ;
var pattern = /<a href="([^"]+?)">([^<]+?)<\/a>/gi;
code = code.match(pattern);
for (i = 0; i < code.length; i++) {
document.write($2<br />'));
}
});
</script>
It looks like you're trying to parse HTML with regex. This post has some more info on that topic.
Since this question is tagged as jQuery, you could try something like the following...
Make a jQuery object out of the returned HTML:
$markup = $(data.contents);
Find the anchors:
$anchors = $markup.find('a');
Get the text (or whatever attribute you want from it):
arrText = [];
$anchors.each(function() {
arrText.push($(this).text());
});
Put result into textarea:
$textarea.val(arrText.join(','));
To achive this jquery is the simplest solution, you can try below code
$('a').each(function(){
var copiedTitle = $(this).html();
var previous = $('#test').html();
var newText = previous +"\n"+ copiedTitle;
$('#test').html(newText);
});
JS Fiddle

Categories