Passing variable from function in javascript - javascript

I'm trying to take text as input from user and split into array and pass it.
<textarea id="texty">
</textarea>
<input type="button" onclick="funky()" />
<script type="text/javascript">
var str;
var array;
var ACL1;
var ACL2;
function funky() {
str = document.getElementById('texty').value;
array = str.split(' ');
}
for (var i = 0; i < array.length; i++) {
var xi = array[i];
if (xi === "ACL") {
ACL1 = array[i + 1];
ACL2 = array[i + 2];
}
}
I'm again using that variables ACL1 and ACL2 in some other place in the same page using this piece of code
<script type="text/javascript">
document.write(+ ACL1 + "<br>");
</script>
<script type="text/javascript">
document.write(+ ACL2 + "<br>");
</script>
Do anybody know where I'm going wrong?

All your funky() function does is split the string into an array and nothing more - you need to make your for loop part of funky() and see what happens.

You assign a value to array when the button is clicked.
You try to process that data into ACL1 and ACL2 and write them to the page while the document loads.
The button won't be clicked before the document loads.
Move the for loop inside the funky function
Get rid of your document.write scripts.
Replace them with div elements (or some other container that is more semantically appropriate).
Modify the funky function to add the content to the page once it is populated the variables
Find the element you want to put the content in (e.g. with document.getElementById or document.querySelector)
Put the content inside it (e.g. with document.createTextNode and document.appendChild

Related

Writing line breaks to a <span> element using JavaScript?

My goal is to take an array, and write each element onto a HTML page using a <span> element with .textContent using a for loop. Only problem is that instead of:
Error1
Error2
I get:
Error1<br/>Error2<br/>
HTML code:
<p><span id="EBox"></span></p>
JS code:
var EBox = document.getElementById("EBox");
var eArray = []; //Elements get added via push
for (var i = 0; i < eArray.length; i++) {
EBox.textContent = EBox.textContent + eArray[i] + '<br/>';
}
The entire system works, but it just ends up as one jumbled sentence. What can I change to make it add the line breaks? I've tried '<br>', '<br />' and '\n' with similar results.
Use .innerHTML .insertAdjacentHTML instead of .textContent as .textContent does not parse the HTML <br> but simply outputs it as text.
Also if you're appending to the HTML each time, it's better to use .insertAdjacentHTML as it does not reparse the previous HTML, thus making it much faster and less error prone than .innerHTML.
var strArr = ['foo', 'bar'];
strArr.forEach(function(str) {
document.querySelector('div').insertAdjacentHTML('beforeend', str + '<br>');
});
<div></div>
Instead of .textContent use .innerHTML.
I would also recommend building up a string first before using .innerHTML so the DOM isn't rebuilt each time...
var EBox = document.getElementById("EBox");
var eArray = []; //Elements get added via push
var html = "";
for (var i = 0; i < eArray.length; i++) {
html += eArray[i] + '<br/>';
}
EBox.innerHTML = html;
I found a better answer here:
https://developer.mozilla.org/pt-BR/docs/Web/CSS/word-break
You can use CSS to do this, see below:
span{word-break: break-word;}
or
span{word-break: break-all;}
BREAKE-WORD will put the next word in a new line and BREAKE-ALL will break the text justifying the content, when it gets bigger than the div or span container.
I hope I'd help :)

Dynamically display html elements via loop

I am working with javascript and jquery. I want to be able to display a buttom, some text, and/or really any html elements or components as many times as the loop allows. I am able to loop through and print alert statements
function LoopTest() {
var i=0;
var stop=5;
for (i=0;i<5;i++)
{ alert("count: " + i); }
}
Simple enough. This would give me 5 alert statements, but instead of using alert statements, I want to be able to display a button or some text or any other html elements. So I would get five buttons displayed on an html page. Is this possible? I'm actually using a .foreach function but for ease of use, a regular for loop would suffice for now. I want to be able to do this on button click (i.e., the function that has the loop starts running once I click a button) also. I'm just not sure really how to accomplish this. Any help would be greatly appreciated. Thanks in advance.
With vanilla Javascript (without using jQuery):
You can use document.createElement to create any type of element you want on the page. Here's the above loop creating <INPUT TYPE='BUTTON'> elements in a <div> with an id of test:
function LoopTest() {
var i=0;
var stop=5;
for (i=0;i<5;i++) {
var v = document.createElement('input');
v.type="button";
v.value="Button " +i;
document.getElementById('test').appendChild(v);
}
}
(In general, using document.write has been considered a bad practice for a while now.)
With jQuery, you can do:
for (i=0;i<5;i++) {
var btn = $("<button/>");
btn.text('Button '+i);
$('#test').append(btn);
}
You can use innerHTML field to add any html content into container on you page.
<script>
function LoopTest()
{
var i=0;
var stop=5;
for (i=0;i<5;i++)
{
document.getElementById("container").innerHTML += "<button>button</button>"
}
}
</script>
...
<div id="container"></div>
Refer: document.write(), Javascript events
<html>
<head>
<script>
function LoopTest() {
var i=0;
var stop = 5;
for (i=0;i<5;i++)
{
document.write('<p>' + i + '</p>'); // This writes the number in a paragraph
}
}
</script>
</head>
<body>
<!--
Here onclick event is used to recognize the click event,
which is fired when the user clicks the button,
this calls the LoopTest() function which generates 5 paragraphs with numbers
-->
<button onclick="LoopTest()">Click to generate content!</button>
</body>
</html>
This is a solution : http://jsfiddle.net/leojavier/gbuLykdj/
<div class="container">
<button class="trigger">Trigger</button>
</div>
JS
$('.trigger').on('click', function(){
LoopTest();
});
function LoopTest() {
var i=0;
var stop=5;
for (i=0;i<5;i++){
$('body').append('<button class="trigger">Trigger No. ' + i + '</button>')
}
}

How to insert HTML tags into JavaScript code?

I need to insert HTML code within JavaScript. See the following code as an example.
function myFunction2(x1,x2) {
var length = arguments.length;
for (var x=0; x<length ; x++)
{
<h1>arguments[x]</h1>
}
}
Is this possible? If not, can you suggest an alternative method to do the same work?
You should wrap the html '<b>'+variable+'</b>' Like this.
Example below.
function myFunction2(x1,x2) {
var results='';
var length = arguments.length;
for (var x=0; x<length ; x++){
// Close html tag in either ' or " to include array or variables use +
// '<p>'+MyVariable+'</p>'
results+='<h1>'+arguments[x]+'</h1>';
}
//Target an element you want to use to display your results
document.getElementById('results').innerHTML=results;
}
<div id="results">Insert h1 tags here...</div>
<button onclick="myFunction2('Argument One','Argument Two');">Call Function</button>
You can find many javascript DOM references online. Not my favorite but This one will give you plenty of examples to learn from.

JavaScript variable doesn't increment in function after getElementById of div

I try to create a JavaScript function that will have one of the variables (var c) which will get the inner text of div tag (the text should be numbers, so somehow it should make variables of numbers) and increment by one when users click button.
Problem: The value of variable c is not incrementing. It increments once, but if user clicks again the button it still stays the same.
//variable $j is in for loop, and the size depends on the other part of the code.
<input type="button" value="Add more" onClick="addmore('.$j.');">
$kxx .= '<div id="K'.$j.'">'.$kx[$j].'</div>';
$kx is for example 1,4,5,2,33,33. And when the index is for example 1, instead of incrementing c (2,3,4,5...) if users click button twice, it gives them 2,2 - instead of 2,3.
<script type="text/javascript">
function addmore(index) {
var c = document.getElementById("K"+index).innerHTML;
c++;
var textarea = document.createElement("textarea");
textarea.name = "odg" + index + c;
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner"+index).appendChild(div);
}
</script>
You're pulling that value out as a string. JS doesn't know what to do with c++ because it sees it as string++. Convert it to an int first with -
+c++
or
parseInt(c, 10)
updated to include parseInt() along with +c as suggested below.

Passing the JavaScript variable into HTML

My JavaScript code is:
<script type="text/javascript">
var current = 0;
var cars = new Array(5);
cars[0] = "Audi";
cars[1] = "Bentley";
cars[2] = "Mercedes";
cars[3] = "Mini";
cars[4] = "BMW";
document.getElementById("addCarBtn").onclick = function () {
if (!(current > cars.length - 1)) {
document.getElementById("carsDiv").innerHTML += cars[current] + "<br />";
current++;
}
}
</script>
I want to display the value of each array item one by one on button click the div.
But when i click the button, the array[0] i.e "Audi" is displayed but just for fraction of seconds. then it disappears and only the button is visible.
You can use a loop like:-
for(var i=0; i< cars.length;i++)
{
alert(cars[i]);
}
//It will show alert 5 times. You'll need to click through ok to traverse all array elements.
//I think it is what you're thinking, or have I interpreted it wrong.
// I'm assuming you're completely new to javascript then on your button write onclick="yourFuncName();"
function YourfuncName()
{
//Initailze your array here, like you have done or like kamituel has done
// then just print each array element one by one
for(var i=0; i< cars.length;i++)
{
alert(cars[i]);
}
}
How about the every method?
cars.every( function(c) {
alert("car: " + c);
});
You're almost there. Since the JS code was located before the HTML, the button element still doesn't exist. Best just wrap the code with window.onload and it should work:
window.onload = function() {
document.getElementById("addCarBtn").onclick = function() {
if (!(current > cars.length - 1)) {
document.getElementById("carsDiv").innerHTML += cars[current] + "<br />";
current++;
}
}
};
Live test case.
Edit: just noticed your button doesn't have type. This means that some browsers might make it a submit button by default, which will cause a page reload. To avoid it, make it a plain button:
<button id="addCarBtn" type="button">

Categories