First, hello everyone as I'm new here.
To summarize my problem, I read the content of an XML file to display in a table.
The basic function to do this works well, I created a derivated function to include a search filter related to an input field.
The search algorithm works well and I'm able to preview the HTML code of the search result using the alert() function and this code seems proper and can be displayed in a browser properly as it would be supposed to. However the innerHTML code of the concerned div is not updated...
I would appreciate any kind of input or solution anyone could provide as I've been stuck on this ! Thanks !
Here is the code :
function printListMod2(){
//Search parameters ?
var searchContent = document.getElementById("searchField").value;
var i=0;
newHTML = "<table id=\"tableInstrus\">";
for (i=0;i<listInstrus.length;i++){
filename = returnFilename(i);
title = returnTitle(i);
tempo = returnTempo(i);
sample = returnSample(i);
multi = returnMulti(i);
style1 = returnStyle1(i);
style2 = returnStyle2(i);
var regEx = new RegExp(searchContent, 'gi');
var resultSearch = title.match(regEx);
if(resultSearch!=null){
if(i%2==0){
newHTML += "<tr class=\"tr0\"><td class=\"idColumn\">"+(i+1)+"</td><td class=\"emptyColumn\"></td><td class=\"nameColumn\">"+title+"</td><td class=\"tempoColumn\">"+tempo+"</td><td class=\"sampleColumn\">"+sample+"</td><td class=\"multiColumn\">"+multi+"</td><td class=\"styleColumn\">"+style1+"</td><td class=\"styleColumn\">"+style2+"</td><td class=\"addLink\"><a id="+filename+" onclick=\"addLinkToPlaylist("+i+")\"><img title=\"Add to playlist\" class=\"addButton\" src=\"images/buttonAdd.png\"/></a></td><td class=\"playLink\"><a onclick=\"playTrack("+i+","+true+")\"><img title=\"Play this track\" class=\"playButton\" src=\"images/buttonPlaySmall.png\"/></a></td></tr>";
}
else{
newHTML += "<tr class=\"tr1\"><td class=\"idColumn\">"+(i+1)+"</td><td class=\"emptyColumn\"></td><td class=\"nameColumn\">"+title+"</td><td class=\"tempoColumn\">"+tempo+"</td><td class=\"sampleColumn\">"+sample+"</td><td class=\"multiColumn\">"+multi+"</td><td class=\"styleColumn\">"+style1+"</td><td class=\"styleColumn\">"+style2+"</td><td class=\"addLink\"><a id="+filename+" onclick=\"addLinkToPlaylist("+i+")\"><img title=\"Add to playlist\" class=\"addButton\" src=\"images/buttonAdd.png\"/></a></td><td class=\"playLink\"><a onclick=\"playTrack("+i+","+true+")\"><img title=\"Play this track\" class=\"playButton\" src=\"images/buttonPlaySmall.png\"/></a></td></tr>";
}
}
}
newHTML += "<tr><td class=\"idColumn\"></td><td id=\"emptyColumn\"></td><td class=\"nameColumn\"></td><td class=\"tempoColumn\"></td><td class=\"sampleColumn\"></td><td class=\"multiColumn\"></td><td></td><td></td></tr>";
newHTML += "</table>";
alert(newHTML); //this displays the HTML code properly
document.getElementById("listDiv").innerHTML = newHTML; //this doesn't seem to do anything...
}
Is your script being executed before the document has finished loading?
Then it won't find #listDiv because the div doesn't exist yet.
I would check the javascript console output for errors and check if the following code doesn't return undefined:
{
...
console.log( document.getElementById('listDiv') );
}
Related
Hey :) I know a similiar question was asked before, but i just cant get it through. I want to create a method called something like makeMeSpaces, so my h2 text will have a space between each character.. and i might want to use it elsewhere aswell. I have this until now, from the logic point of view:
var text = "hello";
var betweenChars = ' '; // a space
document.querySelector("h1").innerHTML = (text.split('').join(betweenChars));
it also works pretty fine, but i think i want to do
<h2>Hello.makeMeSpaces()</h2>
or something like this
Thank you guys!
If you really want this in a 'reusable function,' you'd have to write your own:
function addSpaces(text) {
return text.split('').join(' ');
}
Then, elsewhere in code, you could call it like so:
var elem = document.querySelector('h2');
elem.innerHTML = addSpaces(elem.innerHTML);
Maybe this is what you want , not exactly what you showed but some what similar
Element.prototype.Spacefy = function() {
// innerText for IE < 9
// for others it's just textContent
var elem = (this.innerText) ? this.innerText : this.textContent,
// replacing HTML spaces (' ') with simple spaces (' ')
text = elem.replace(/ /g, " ");
// here , space = " " because HTML ASCII spaces are " "
space = " ",
// The output variable
output = "";
for (var i = 0; i < text.length; i++) {
// first take a character form element text
output += text[i];
// then add a space
output += space;
};
// return output
this.innerHTML = output;
};
function myFunction() {
var H1 = document.getElementById("H1");
// calling function
H1.Spacefy();
};
<h1 id="H1">
<!-- The tags inside the h1 will not be taken as text -->
<div>
Hello
</div>
</h1>
<br />
<button onclick="myFunction ()">Space-fy</button>
You can also click the button more than once :)
Note :- this script has a flow, it will not work for a nested DOM structure refer to chat to know more
Here is a link to chat if you need to discuss anything
Here is a good codepen provided by bgran which works better
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>
I have a string in the below non-escaped format in a HTML page:
<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>
What I need is to use jQuery/JavaScript to replace that string with just the link "SomeThing".
I have looked at some examples in StackOverflow, but they don't seem to work. I'm just getting started with jQuery and JavaScript, so would appreciate any help here.
Any ideas?
Try html() and text() in jquery to decode:
var str = '<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>';
var decoded = $('<div />').html(str).text();
alert($(decoded).text());
See Fiddle demo
var str = '<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>';
var helper = document.createElement('p');
// evaluate as HTML once, text now "<a href..."
helper.innerHtml = str;
// evaluate as HTML again, helper now has child element a
helper.innerHtml = helper.innerText;
// get text content only ("SomeThing")
alert(helper.innerText);
Here is a possible starting point.
Hope this gets you started!
function parseString(){
var str = '<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>';
var begin = str.indexOf('\">',0)+2; //--determine where the opening anchor tag ends
var end = str.indexOf('</a>',0); //--determine where the closing anchor tag begins
var parsedString = str.substring(begin,end); //--grab whats in between;
/*//--or all inline
var parsedString = str.substring(str.indexOf('\">',0)+2,str.indexOf('</a>',0));
*/
console.log(parsedString);
}
parseStr();
html file:
<div id ="main">
</div>
Javascript:
//create a div
var divElem = $('<div class="divText"></div>');
//create input element inside it
var inhtml = "<input type='text' id='12345' />";
//add to page
$(divElem).html(inhtml).appendTo('#main')
Following does not work as it is unable to find input element:
//retrieve input element
$('#12345').val('hello')
Following works:
document.getElementById('12345').value = 'hello'
Following works:
var ipElem = $(inhtml);
$(divElem).append(ipElem).appendTo('#main')
$(ipElem).val('hello')
Can anyone tell why first version of retrieving element does not work in jquery? (just starting with jquery... :) )
Edit:
I think '12345' works but not some weird id like: mytext0.15942923246580176
See here:
http://jsfiddle.net/9PVNb/4/
You're wrapping divElem in jQuery object twice:
var divElem = $('<div class="divText"></div>');
var inhtml = "<input type='text' id='12345' />";
$(divElem).html(inhtml).appendTo('#main') // Nop '$(divElem)' plus missing `;`
divElem.append(inhtml).appendTo('#main'); // Yup
EDIT:
Edit: I think '12345' works but not some weird id like: mytext0.15942923246580176
Your code at http://jsfiddle.net/9PVNb/4/ isn't working because:
// Your `id` has a `.` which you didn't escape
var elemid = 'mytext0.15942923246580176';
You can make it work by doing this:
alert($('#' + elemid).val()); //undefined. DOES NOT WORK
alert($('#' + elemid.replace('.', '\\.')).val()); // hello world IT WORKS!
works here: http://jsfiddle.net/xvKcd/
basic check:
are you using $(document).ready()? your code may be firing up before the element you needed was loaded.
did you load jQuery before anything else?
typos?
i need some help with this, i'm trying to generate some html with javascript, but always get the same, this is my javascript code
var datePickerHTML = function(id){
var html = "<div id='"+id+"' class='ui-datepicker'>";
html += "Hello World, my ID is "+id;
html += "</div>";
return html;
}
var UhmaCalendar = function(config){
var dpID = 'dp'+config.inputField;
this.dpID = dpID;
jQuery('#'+config.inputField).after(function(){
return datePickerHTML(dpID);
});
jQuery('#'+config.btn).click(function(){
jQuery('#'+dpID).toggle('slow');
}
}
now, in my html i write
UhmaCalendar({
btn : 'countday_pick',
inputField : 'countday'
});
UhmaCalendar({
btn : 'sartday_pick',
inputField : 'startday'
});
this is for 2 diferent input and buttons, but they always show the same div with the same text, and id i check the html withthe firebug, only one div is created, ad i want 2 div with diferent ids
i also try with
new UhmaCalendar({
btn : 'sartday_pick',
inputField : 'startday'
});
but is the same, what am i doing wrong here
thanks
You have forgotten to return html; in the function datePickerHTML.
With the newest edit, I was unable to reproduce the error. See http://jsbin.com/ucage4 for a demo which works correctly.
Hard to tell what's wrong, the code as quoted is unparseable. Some notes that may be of use:
var datePickerHTML = function(id){
var html = "<div id='"+id+"' class='ui-datepicker'>";
html += "Hello World, my ID is "+id;
html += "</div>";
// Should probably have `return html;` here
}
var UhmaCalendar = function(config){
this.dpID = 'dp'+config.inputField;
jQuery('#'+config.inputField).after(function(){
return datePickerHTML(dpID);
// ^-- This symbol is undefined, and != `this.dbID`
});
jQuery('#'+config.btn).click(function(){
jQuery('#'dpID).toggle('slow');
// ^-- syntax error (and `dbID` is undefined here too)
} // <-- Missing `);` here
}
If I had to guess at the intent:
var datePickerHTML = function(id){
var html = "<div id='"+id+"' class='ui-datepicker'>";
html += "Hello World, my ID is "+id;
html += "</div>";
return html; // tjc
}
var UhmaCalendar = function(config){
var dpID = 'dp'+config.inputField; // tjc
this.dpID = dpID; // tjc
jQuery('#'+config.inputField).after(function(){
return datePickerHTML(dpID);
});
jQuery('#'+config.btn).click(function(){
jQuery('#'+dpID).toggle('slow'); // tjc
}); // tjc
}
My suspicion is that the dpID thing(s) are the main error. I've fixed it above by creating a variable within the function which the enclosed functions inherit access to (because they're closures).
HTH