In my HTML file I have this snippet of code:
<textarea class="form-control" id="textfield" rows="10"></textarea>
And in my Javascript file I have this:
input1 = document.getElementById('input1').value;
input2 = document.getElementById('input2').value;
textfield = document.getElementById('textfield');
if(document.getElementById('tmkbSelect').value == "option1") {
document.getElementById('tmkb').innerHTML = "Tafel";
for(input2i=0;input2i<20;input2i++){
document.getElementById('textfield').value = input1+" "+"*"+" "+input2i+" "+"="+" "+input1*input2i;
}
}
I'm basically trying to create a multiplication table. It works, but not quite.
The javascript code is in a function and I call that function using a button, but the problem is that the output is this:
3 * 19 = 57
I want it to be:
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
And so on, how do I do this?
I need to do this using only Javascript.
You need to concatenate the strings and then put them in the textarea.
You can add the strings to an array, and then concatenate them after the loop and put them in the textarea:
var lines = [];
for(input2i=0;input2i<20;input2i++){
lines.push(input1+" "+"*"+" "+input2i+" "+"="+" "+input1*input2i);
}
document.getElementById('textfield').value = lines.join('\n');
Use ShortHand operator for adding content to textarea.
document.getElementById("test").value += "\n 1";
Demo
In the loop, you assign the value:
... .value = input1+...
That means you overwrite the content every time. You need to append instead:
var content = '';
...
content += input1+...
...
document.getElementById('textfield').value = content;
Note the +=.
Don't forget to add '\n' after each line or everything will be in one line.
Related
i could not make it as function.Please help.When i modified as function and add button,it not work.
i'm newbie in javascript.i would like study by the simple script.But for the below script when i try to add "function xxx()" it not working with input button.
I try to solve by my own with google...failed.
<script>
var myStr = "xxx yyy zzz";
var strArray = myStr.split(" ");
// Display array values on page
for(var i = 0; i < strArray.length; i++){
document.write("<p>" + strArray[i] + "</p>");
}
</script>
Break your code into blocks if you ever are stuck on something. So first you are trying to break a string into an array so that's your first block. Then your second block would be to write it to the page. So we have our code basically written out in our heads.
---Break string
---Display broken string
So to make a function we need to write a function first
myFunction = function(){
};
But to get the function to be modular we need to be able to pass in variables
So we'll add two variables one being the string to pass through and one being the location to inject the looped broken text.
myFunction = function(str, location){
};
Now we have to do something with these variables.
myFunction = function(str, location){
///test if str is a string
if(typeof(str) == "string")
{
var l = str.split(" "); /// here we're spliting the string into an array by every space
if(l.length >= 1) ///test if there's atleast one item
for(i=0;i<l.length;i++) ///simple for loop
location.innerHTML += "This is a part of str " + l[i] + "<br>" ///you can do anything here you want to do.
}
};
Now as you can see it's modular at it's lowest point, this can be as complex as you want it. here is a test you can try out and mess around with. https://jsfiddle.net/s8pytzm3/1/
This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 8 years ago.
var jtj_code_lines = []; // this array will hold all the jtj codes line
var JTJ = function(j){
j = j.replace(" ","");
jtj_code_lines = j.split(';'); // splitting all the lines seperated from ;
for(var i=0; i<jtj_code_lines.length; i++){
if(jtj_code_lines[i].charAt(0) === '*'){ // * means that the following word is the name of a method that will perform some action
var q1 = jtj_code_lines[i].replace('*', ''),
q1_pos_1 = q1.indexOf('['); // find the position of the keyword [
var q1_funcname = q1.slice(0, q1_pos_1); // it find the name of that perticular function
if(q1_funcname === "Message"){ // this checks weather the function name is message
var q1_pos_2 = q1.indexOf(']'), // this ifnds the position of keyword ]
q1_func_value = q1.slice(q1_pos_1+1, q1_pos_2); // this finds what is written inside [] and accepts as the value of Message
alert(q1_func_value);
}else{
}
}
}
};
so the above function is pretty simple it finds the specific text written in the braces, i mean that if you write :
JTJ('*Message[hi];')
then it will alert hi and this is quit simple and this is alerting as expected but the problem is coming that if any * is after white space then that perticular thing is not being alerted, so the following have the same condition,*Message[go ]; starts with whitespace so it is not being alerted :
JTJ('*Message[sanmveg];*Message[saini]; *Message[go ];')
but i have a this line j = j.replace(" ",""); to remove all the white spaces, then why it is not working? is there any other way to do this?
thanks.
Fix: j = j.replace(/\s/gi,"");
this would remove all " " with "", in short it would act as replaceAll.
Before it was just replacing first matched " " with "".
This probably is a very easy solution, but browsing other questions and the internet did not help me any further.
I made a javascript function which will give me a random value from the array with its according points:
function random_card(){
var rand = Math.floor(Math.random()*cards.length);
var html = "card: "+cards[rand][0]+"<br/>points: "+cards[rand][1]+"<br/><br/>";
document.getElementById("Player").innerHTML += html;
var punten = cards[rand][1];
document.getElementById("Points").innerHTML += punten;
}
I've added a += punten so i can see that it works correctly. It shows me all the point in the div with the id Points.
But what i wanted to do is count it all together so if i were to draw a 4, King and a 10 it should show 24 instead of 41010.
Thanks in advance! And if you're missing any information please let me know
Currently you are just adding strings together, which concatenate (join together) hence why you end up with 41010. You need to grab the current innerHTML (total) and use parseInt() to convert from a string to a number, then add your new cards that have been chosen, then assign this new value to the innerHTML of your element.
Try the following
function random_card(){
var rand = Math.floor(Math.random()*cards.length);
var html = "card: "+cards[rand][0]+"<br/>points: "+cards[rand][1]+"<br/><br/>";
document.getElementById("Player").innerHTML += html;
var punten = cards[rand][1];
var curPoints = parseInt(document.getElementById("Points").innerHTML, 10) || 0;
var total = curPoints + parseInt(punten, 10);
document.getElementById("Points").innerHTML = total;
}
More info on parseInt() here
EDIT
I've added this line -
var curPoints = parseInt(document.getElementById("Points").innerHTML, 10) || 0;
Which will try and convert the innerHTML of the "Points" div, but if it is empty (an empty string converts to false) then curPoints will be equal to 0. This should fix the issue of the div being blank at the start.
innerHTML is a string and JavaScript uses + for both string concatenation as numeric addition.
var pointsInHtml = parseInt(document.getElementById("Points").innerHTML, 10);
pointsInHtml += punten;
document.getElementById("Points").innerHTML = punten;
The second parameter 10 of the parseInt method is usually a good idea to keep there to avoid the function to parse it as an octal.
It might be easier to keep a points variable and only at the end put it in the #Points container, that would make the parseInt no longer necessary
innerHTML will be a string, so you need to convert it into an integer prior to adding the card value :)
function random_card(){
var rand = Math.floor(Math.random()*cards.length);
var html = "card: "+cards[rand][0]+"<br/>points: "+cards[rand][1]+"<br/><br/>";
document.getElementById("Player").innerHTML += html;
var punten = cards[rand][1],
curPunten = parseInt(document.getElementById('Points').innerHTML);
document.getElementById("Points").innerHTML = curPunten + punten;
}
I have a small piece of code that generates an array with values based on a triangle. I will post the array below.
var endwallPanelLengths = [totalHeightInches];
var i = 0;
while (endwallPanelLengths[i] > eaveInches)
{
endwallPanelLengths.push(endwallPanelLengths[i] - peakHeightDecrease);
document.getElementById("test83").value="4 - " + endwallPanelLengths[i];
i++;
}
This array will have anywhere between 2 to 100 indexes. I want the code to write all of the values separated by breaks into a <textarea> with the id="test83".
If I run the code as it is set up above it will only write the value in array [1] not [0] or any of the others. How can I get it to write all of them so that they come out looking like this...
4 - 140 this is the value of array position [0]
4 - 126
4 - 116 and so on?
You keep replacing the value
document.getElementById("test83").value="4 - " + endwallPanelLengths[i];
You would need to append to the value
document.getElementById("test83").value += "4 - " + endwallPanelLengths[i] + "\n";
better yet, build up the values and set the value once
var endwallPanelLengths = [totalHeightInches],
i = 0,
output = [];
while (endwallPanelLengths[i] > eaveInches)
{
endwallPanelLengths.push(endwallPanelLengths[i] - peakHeightDecrease);
output.push("4 - " + endwallPanelLengths[i]);
i++;
}
document.getElementById("test83").value = output.join("\n");
If I'm understanding you correctly, that you want the array displayed with one item per line in your textarea, then you should be able to ditch your loop completely, and just do it in one shot.
document.getElementById("test83").value = endwallPanelLengths.join('\n');
Although it also looks like you're prepending '4 -' to each value. If that's the case, then you could just add one extra step to get those fours added:
var arr = endwallPanelLengths.map(function(item){ return '4 - ' + item; });
document.getElementById("test83").value = arr.join('\n');
Just be sure to grab the shim for Array.prototype.map from here if you need to support IE8
HTML:
<div id="holder"></div>
JavaScript:
var endwallPanelLengths = [totalHeightInches];
var i = 0;
var holder = document.getElementById("holder");
while (endwallPanelLengths[i] > eaveInches)
{
endwallPanelLengths.push(endwallPanelLengths[i] - peakHeightDecrease);
var e = document.createElement('div');
e.innerHTML = "4 - " + endwallPanelLengths[i] + "<br />";
holder.appendChild(e.firstChild);
i++;
}
Hopefully that does for you what you want. In your example, in your loop, you're setting the newest value to the same element, thus overwriting any previous values.
I have a text area where each line contains Integer value like follows
1234
4321
123445
I want to check if the user has really enetered valid values and not some funny values like follows
1234,
987l;
For that I need to read line by line of text area and validate that.
How can i read line by line of a text area using javascript?
Try this.
var lines = $('textarea').val().split('\n');
for(var i = 0;i < lines.length;i++){
//code here using lines[i] which will give you each line
}
This works without needing jQuery:
var textArea = document.getElementById("my-text-area");
var arrayOfLines = textArea.value.split("\n"); // arrayOfLines is array where every element is string of one line
Two options: no JQuery required, or JQuery version
No JQuery (or anything else required)
var textArea = document.getElementById('myTextAreaId');
var lines = textArea.value.split('\n'); // lines is an array of strings
// Loop through all lines
for (var j = 0; j < lines.length; j++) {
console.log('Line ' + j + ' is ' + lines[j])
}
JQuery version
var lines = $('#myTextAreaId').val().split('\n'); // lines is an array of strings
// Loop through all lines
for (var j = 0; j < lines.length; j++) {
console.log('Line ' + j + ' is ' + lines[j])
}
Side note, if you prefer forEach a sample loop is
lines.forEach(function(line) {
console.log('Line is ' + line)
})
This would give you all valid numeric values in lines. You can change the loop to validate, strip out invalid characters, etc - whichever you want.
var lines = [];
$('#my_textarea_selector').val().split("\n").each(function ()
{
if (parseInt($(this) != 'NaN')
lines[] = parseInt($(this));
}
A simple regex should be efficent to check your textarea:
/\s*\d+\s*\n/g.test(text) ? "OK" : "KO"
A simplifyied Function could be like this:
function fetch (el_id, dest_id){
var dest = document.getElementById(dest_id),
texta = document.getElementById(el_id),
val = texta.value.replace(/\n\r/g,"<br />").replace(/\n/g,"<br />");
dest.innerHTML = val;
}
for the html code below (as an example only):
<textarea id="targetted_textarea" rows="6" cols="60">
At https://www.a2z-eco-sys.com you will get more than what you need for your website, with less cost:
1) Advanced CMS (built on top of Wagtail-cms).
2) Multi-site management made easy.
3) Collectionized Media and file assets.
4) ...etc, to know more, visit: https://www.a2z-eco-sys.com
</textarea>
<button onclick="fetch('targetted_textarea','destination')" id="convert">Convert</button>
<div id="destination">Had not been fetched yet click convert to fetch ..!</div>