.innerHTML does not display the html code content I need - javascript

So I am trying to create text boxes dynamically using javascript, which is working fine, but when I try to use innerHTML to display the text boxes in nothing appears on my screen.
JavaScript Code:
var i = 1;
function instituteCreate(){
var y = document.createElement("INPUT");
y.setAttribute("type", "text");
y.setAttribute("Name", "institute_" + i);
document.getElementById('userdata').innerHTML = '<div class="row"><div class="col-md"><div
class="form-group"><div class="form-field">Institute';
document.getElementById('userdata').appendChild(y);
document.getElementById('userdata').innerHTML = '</div></div></div></div>';
i++;
}
I have the following in my html file:
<div id="userdata"></div>
And right before the closure I have the following which is calling the JS file:
<script src="js/addmore.js" type="text/javascript"></script>

When you use innerHTML with = you are completely reassigning everything inside of that element overwriting everything you had before.
You can either use += instead of = to not overwrite the value, and instead append.
Or create a template with backtick: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Related

Dynamic options in Option tag using 'For loop' with html tags in JavaScript? [duplicate]

I am trying to use a for loop in html but i dont even know if this is possible. Is it? and if yes how? I dont want to use php. only html and javascript.
this is my goal: i have a file containing .txt files. i want to count the number of txt files and when i get the number i want to send it to where i will use a for loop to put the txt file's numbers in a dropbox.
Thanks
Lots of answers.... here is another approach NOT using document.write OR innerHTML OR jQuery....
HTML
<select id="foo"></select>
JS
(function() { // don't leak
var elm = document.getElementById('foo'), // get the select
df = document.createDocumentFragment(); // create a document fragment to hold the options while we create them
for (var i = 1; i <= 42; i++) { // loop, i like 42.
var option = document.createElement('option'); // create the option element
option.value = i; // set the value property
option.appendChild(document.createTextNode("option #" + i)); // set the textContent in a safe way.
df.appendChild(option); // append the option to the document fragment
}
elm.appendChild(df); // append the document fragment to the DOM. this is the better way rather than setting innerHTML a bunch of times (or even once with a long string)
}());
And here is a Fiddle to demo it.
Yes you can for example
write this code in html body tag
<select>
<script language="javascript" type="text/javascript">
for(var d=1;d<=31;d++)
{
document.write("<option>"+d+"</option>");
}
</script>
</select>
HTML
<select id="day" name="day"></select>
<script type='text/javascript'>
for(var d=1;d<=31;d++)
{
var option = "<option value='" + d + "'>" + d + "</option>"
document.getElementById('day').innerHTML += option;
}
</script>
May be you can play with javascript and innerHTML. Try this
HTML
<body onload="selectFunction()">
<select id="selectId">
</select>
Javascript
function selectFunction(){
var x=0;
for(x=0;x<5;x++){
var option = "<option value='" + x + "'>Label " + x + "</option>"
document.getElementById('selectId').innerHTML += option;
}
}
One way is to use DynamicHTML. Let the html page have a place holder for the options of select tag.
<select id="selectBox"></select>
In a js file
var options = ["one","two","three"], selectHtml = "";
for(var optionIndex = 0; optionIndex < options.length; optionIndex++) {
selectHtml += ("<option>" + options[optionIndex] + "</option>");
}
document.getElementById("selectBox").innerHTML = selectHtml;
Put the above code in a function and call that function onload.
No you can't use a for loop in HTML. HTML is a markup language, you cannot use logical code. However you could use javascript to do your logic depending on what your objective is.
Here is an example using jQuery, a popular javascript library:
for(i=0; i<5; i++){
$("select").append("<option>" + i + "</option>");
}
See example: http://jsfiddle.net/T4UXw/
HTML is not a programming language, just a markup language, so it doesn't include things like for loops or if statements. Javascript does though. You could use javascript to generate/manipulate the HTML, and thus use for loops to create your <option> tags inside the <select>. As a startup for javascript see checkout w3schools.com
I don't like using plain javascript though, I would rather choose a javascript framework like jQuery to do this. Using jquery it is really easy to do cross-platform compatible manipulation of the HTML dom using javascript. You would only need to include some extra javascript files inside your HTML to get it working.
See http://jquery.com/
An example of using jquery would be this:
<select id='myselect'></select>
<script type='text/javascript'>
var values=[[1,'tree'],[2,'flower'],[3,'car']];
for(v in values){
var option=$('<option></option>');
option.attr('value',values[v][0]);
option.text(values[v][1]);
$('#myselect').append(option);
}
</script>
You can also try this out on http://jsfiddle.net/6HUHG/3/

How to render html partially inside div?

I have a div and I want to set some text inside this div. Problem is my text contains HTML elements and I don't want all these elements to be rendered. I mean some elements must rendered as HTML.
Is there any way to create a div content like this?
I want to create a div element like below;
<div id="bodyContent">
</div>
Setting with html method is not working.
var myHTMLContentPart1 = "<HTML><BODY>";
var myHTMLContentPart2 = "<span>hello</span>";
var myHTMLContentPart3 = "</BODY></HTML>";
$("#bodyContent").html(?);
EDIT:
I recommend you to use regex to remove html or body tags, also you can add any tag that you want to remove like this <\/?tagname>
html = '<html><body><span>Some Text</span></body></html>';
clean = html.replace(/<\/?html>|<\/?body>/g, '');
console.log(clean);
// For your code
var myHTMLContentPart1 = "<HTML><BODY>";
var myHTMLContentPart2 = "<span>hello</span>";
var myHTMLContentPart3 = "</BODY></HTML>";
var html = myHTMLContentPart1 + myHTMLContentPart2 + myHTMLContentPart3;
clean = html.replace(/<\/?html>|<\/?body>/g, '');
$("#bodyContent").html(clean);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="bodyContent">
</div>

selecting element from a html string inside variable

I have html string data inside variable like this
var htmlstring = "<div><div class='testdiv'>924422</div></div>"
What I am expecting is to fetch content of div having class.In this example .testdiv data.
How can I achieve?.
I know one approach: Append this html string to html page and then access.But I dont want to do it as I am using ajax and server returning kind of html string.Now I want to fetch data inside specific div.
So is there any alternative way to do?
First you don't use . in class name in html. And to fetch the content of that div in html string, you could use jquery find function.
var htmlstring = "<div><div class='testdiv'>924422</div></div>"
alert($(htmlstring).find('.testdiv').html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here's a way you can achieve it without jQuery.
var htmlstring = "<div><div class='testdiv'>924422</div></div>";
function getTestDiv(htmlString) {
var textVal = null;
var div = document.createElement('div');
div.innerHTML = htmlString;
var elements = div.childNodes;
if (elements.item(0).childNodes.item(0).className === 'testdiv') {
textVal = elements.item(0).childNodes.item(0).innerHTML;
}
return textVal;
}
console.log(getTestDiv(htmlstring));
You can do this by :
console.log($(htmlstring).find("div.testdiv").text());

Reading and formatting Access data

I'm using JavaScript and HTA to read data in access database (.mdb) on local but having a small issue. My JavaScript code is like this:
function miseryBusiness() {
var box = document.getElementById("lyrics");
box.innerHTML = "";
var db = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='paramore.mdb'";
var adoConn = new ActiveXObject("ADODB.Connection");
var adoRS = new ActiveXObject("ADODB.Recordset");
adoConn.Open(db);
adoRS.Open("SELECT * from 2007_RIOT WHERE track=4", adoConn, 1, 3);
var lyrics = adoRS.Fields("lyrics").value;
box.innerText = lyrics;
adoRS.Close();
adoConn.Close();
}
I have a div in the page with id="lyrics". Function gets the specified cell's value and change's div's inner text to that value.
What I want to do is use innerHTML instead of innerText. And if I use inner HTML I get the cell's value as a single line. I want to add line breaks to the end of the each line. Also an anchor to the beginning of the text.
If I was getting the text from a .txt file I'd use
while(!lyrics.AtEndOfStream) {
box.innerHTML += '<a id="miseryBusiness">' + lyrics.ReadLine() + '<br/>';
}
but this doesn't work with access database. Or I couldn't get it to work. Any ideas?
The HTA and .mdb file I'm using: link1 link2
If the lyrics are in a Memo field with hard line-breaks then the line terminator is almost certainly <cr><lf>, so try the following:
box.innerHTML = '<a id="miseryBusiness">' + lyrics.replace(/\r\n/g, '<br/>');

remove outer div

In my JavaScript code I have a string that contains something like:
var html = "<div class='outer'><div id='inner'>lots more html in here</div></div>";
I need to convert this to the string
var html = "<div id='inner'>lots more html in here</div>";
I'm already using using jQuery in my project, so I can use this to do it if necessary.
Why all these needlessly complex answers?
//get a reference to the outer div
var outerDiv = document.getElementById('outerDivId');//or $('#outerDivId')[0];
outerDiv.outerHTML = outerDiv.innerHTML;
And that's it. Just set the outerHTML to the inner, and the element is no more.
Since I had overlooked that you're dealing with an HTML string, it needs to be parsed, first:
var tempDiv = document.createElement('div');
tempDiv.innerHTML = htmlString;
var outerDiv = tempDiv.getElementsByTagName('div')[0];//will be the outer div
outerDiv.outerHTML = outerDiv.innerHTML;
And you're done.
Try:
var html = "<div class='outer'>"
+ "<div id='inner'>lots more html in here</div></div>";
html = $(html).html();
alert(html);
http://jsfiddle.net/TTEwm/
Try .unwrap() -
$("#inner").unwrap();
If html string always look like in your example you can use this simple code
var html = "<div class='outer'><div class='inner'>lots more html in here</div></div>";
html = html.slice(19,-6)
You can do something like this:
var html = "<div id='inner'>" + html.split("<div id='inner'>")[1].split("</div>")[0] + "</div>";
But you may want to add more protection for variations (in case you have the bad habit of not writing code using the same conventions), e.g "inner" or <DIV>
Demo

Categories

Resources