i`m working on school project
how can i access the name of variable and store it to in another variable ex: y[i].
what to write in place of comment below in javascript code.
var p = ["a","b","d"];
var q = ["d","b","c"];
var value = "d";
var x = [];
var y = [];
function testArrays(needle, arrays) {
for (var i=0; i<arrays.length; i++) {
x[i] = arrays[i].indexOf(value);
// y[i] = // store array`s name here
}
document.getElementById("demo").innerHTML = x + y;
}
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<p>Click the button to display the position of the element "Apple":</p>
<button onclick="testArrays(value, [p, q])">Try it</button>
<p id="demo"></p>
</body>
</html>
Here is what you search for : You have to construct a object with your arrays and pass trow all the arrays.
var obj = {
p:["a","b","d"],
q: ["d","b","c"]
};
var value = "d";
var x = [];
var y = [];
function testArrays(needle, arrays) {
for(key in arrays){
x.push(arrays[key].indexOf(value));
y.push(key);
}
document.getElementById("demo").innerHTML = x + y;
}
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<p>Click the button to display the position of the element "Apple":</p>
<button onclick="testArrays(value, obj)">Try it</button>
<p id="demo"></p>
</body>
</html>
Since you ask for what i was talking about. I'll give you the code.
Again, to re-iterate my point, you cannot get the variable name. But if you must have the variable somehow, you can work around by putting all the variables you need access to in an object.
you will not get the variable name of the object, but you can access all the properties names of this object.
Here is the codepen link to see the code running.
html
<p id="test"><p>
js
var variableList = {};
variableList.var1 = 1;
variableList.var2 = -50;
variableList.var3 = [2,4];
variableList.var4 = "4";
variableList.var5 = 5.5;
var ele = document.getElementById("test");
for(var propertyName in variableList) {
ele.innerHTML = ele.innerHTML + "<br>" + propertyName + " : " + variableList[propertyName];
}
Related
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>moving word</title>
</head>
<body>
<p id="word">w3resource</p>
</body>
</html>
<script type="text/javascript" src="five.js"></script>
function MovingLetters() {
var text = document.getElementById("word").value;
var len = text.length;
var lastletter = text.charAt(len-1);
text = text.substring(0,len-1);
text = lastletter + text;
}
MovingLetters();
$(function() {
setInterval(MovingLetters, 1000);
});
Console gives me :
Cannot read property 'length' of undefined
No idea why it is undefined because I defined it 2 lines before that one while that one reflects to a <p> in the html code that runs before the js script runs. Can someone help?
using value is for input elements, you should use textContent, innerText or if you want the html innerHTML:
var text = document.getElementById("word").textContent;
function MovingLetters() {
var word = document.getElementById("word")
var text = word.textContent;
var len = text.length;
var lastletter = text.charAt(len - 1);
text = text.substring(0, len - 1);
text = lastletter + text;
word.textContent = text
}
MovingLetters();
setInterval(MovingLetters, 1000);
<p id="word">w3resource</p>
You dont't want the value you want what's called innerHTML. you can achieve this by doing document.getElementById("word").innerHTML.length.
I am trying to write a solution for a javascript application that takes a number input & depending on that number is how many times it runs a specific function. I am using a text box for input field & a button to process the number of times the user wants the function to run. It is for a game of dice game. User enters how many games he wants to play and clicks button to run the roll_dice function that many times. I'm not sure if I am going the right way with using a for loop to take users numeric input and loop through its value until it ends for example
function games() {
var num = document.getElementById("inp").vale;
var i;
for (i = 0; i < num; i++) {
roll_dice();
}
}
You have a typo. It's .value.
You can convert a string to a number by using * 1.
Something like this:
function games() {
var num = document.getElementById("inp").value * 1; // Convert the string value a number.
var i;
for (i = 0; i < num; i++) {
roll_dice();
}
}
function roll_dice() {
console.log("Test.");
}
var btnRun = document.getElementById("btnRun");
btnRun.onclick = function() {
games();
};
<input id="inp" type="text" />
<button id="btnRun" type="button">Run</button>
The value you get from input box is string you need to convert it into int . If you are using int in loop .
var num = parseInt(document.getElementById("inp").value);
function games() {
var num = document.getElementById("inp").value;
var i;
for (i = 0; i < Number(num); i++) {
roll_dice();
}
}
**<label>Game:</label><input type="text" id="input" value="0" />
<button id="btn">Submit</button>
<script>
document.getElementById("btn").addEventListener("click",function(){
var inputVal=document.getElementById("input").value*1;
rollDice(inputVal);
});
function rollDice(dice){
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<label>Game:</label><input type="text" id="input" value="0" />
<button id="btn">Submit</button>
<script>
document.getElementById("btn").addEventListener("click",function(){
var inputVal=document.getElementById("input").value*1;
rollDice(inputVal);
});
function rollDice(dice){
for(var i =0;i<dice;i++){
var x = Math.random()*100;
console.log(x);}
}
</script>
</body>
</html>
for(var i =0;i<dice;i++){
var x = Math.random()*100;
console.log(x);}
}
</script>**
And thanks in advance for looking into this, I am trying to show elements of 2 arrays in html (li) tags. This should be the format echoed out:
array1; array2
c201;100
c202;0
c450;320
......
The elements that will be pushed into the array are coming from input fields. I have created the following code and I get to see the correct format but when I copy and paste the values above, it loses the format and instead of having two columns, it pastes elements of array2 just below the elements of array1:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>My Web Page</title>
<script>
var array_accounts = [];
var array_credits = [];
var x = 0;
var i = 0;
var z = 0;
function spara(){
var accounts_code_str = document.getElementById('accounts').value;
var accounts_code_comma = accounts_code_str.split(' ');
var accounts_code_comma = accounts_code_comma.join(';<br>');
array_accounts.push(accounts_code_comma);
console.log(array_accounts);
var iz_credits_str = document.getElementById('credits').value;
var iz_credits_comma = iz_credits_str.split(" ");
//var iz_credits_comma = iz_credits_comma.join('<br> ');
for(var z=0; z<iz_credits_comma.length; z++){
if(iz_credits_comma[z] < 0){
iz_credits_comma[z] = 0;
}
}
var iz_credits_comma = iz_credits_comma.join('<br> ');
array_credits.push(iz_credits_comma);
showAccounts();
showCredits();
}
</script>
</head>
<body>
<h1>Accounts and IZ credits</h1>
<div id="form">
<form>
<label>Insertar Accounts codes</label>
<input type="text" name="accounts" id="accounts" />
<label>Insertar Iz credits</label>
<input type="text" name="credits" id="credits" />
<input type ="button" onclick="spara()" value="Process data" />
</form>
</div>
<div id="codes" style="float:left">
<script>
function showAccounts(){
for (var x=0;x<array_accounts.length;x++){
document.write('<div style="float:left;">'+array_accounts[x]+';</div>');
}
}
</script>
</div>
<div id="credits" style="float:left">
<script>
function showCredits(){
for (var i=0;i<array_credits.length;i++){
document.write('<div style="float:left;">'+array_credits[i]+'<br></div>');
}
}
</script>
</div>
</body>
</html>
Many thanks in advance for your help!
Hope this helps!
<script>
var array_accounts = [];
var array_credits = [];
var x = 0;
var i = 0;
var z = 0;
function spara(){
var accounts_code_str = document.getElementById('accounts').value;
array_accounts = accounts_code_str.split(' ');
console.log(array_accounts);
var iz_credits_str = document.getElementById('credits').value;
var iz_credits_comma = iz_credits_str.split(" ");
array_credits=iz_credits_comma;
//var iz_credits_comma = iz_credits_comma.join('<br> ');
for(var z=0; z<iz_credits_comma.length; z++){
if(iz_credits_comma[z] < 0){
iz_credits_comma[z] = 0;
}
}
showAccounts();
}
function showAccounts(){
var ol = document.createElement("OL");
for (var x=0;x<array_accounts.length;x++){
var li = document.createElement("LI");
var textnode = document.createTextNode(array_accounts[x]+';'+array_credits[x]);
li.appendChild(textnode);
ol.appendChild(li)
}
document.getElementById("codes").appendChild(ol);
}
</script>
Modify the two javascript functions and that should do the trick! Thanks.
I have a textfield in which i am entering data i want that if user enter 1000 then it show 1,000 in textfield but this same value 1000 is also used in calculations further so how to solve this if user enter 1000 then just for display it show 1,000 and if we use in calcualtion then same var shows 1000 for calculating.
<HTML>
<body>
<input type="text" id="test" value="" />
</body>
<script>
var c=document.getElementById(test);
</script>
</html>
so if c user enter 1000 then it should dispaly 1,000 for dispaly one and if user uses in script
var test=c
then test should show 1000
document.getElementById returns either null or a reference to the unique element, in this case a input element. Input elements have an attribute value which contains their current value (as a string).
So you can use
var test = parseInt(c.value, 10);
to get the current value. This means that if you didn't use any predefined value test will be NaN.
However, this will be evaluated only once. In order to change the value you'll need to add an event listener, which handles changes to the input:
// or c.onkeyup
c.onchange = function(e){
/* ... */
}
Continuing form where Zeta left:
var testValue = parseInt(c.value);
Now let's compose the display as you want it: 1,000
var textDecimal = c.value.substr(c.value.length-3); // last 3 characters returned
var textInteger = c.value.substr(0,c.value.length-3); // characters you want to appear to the right of the coma
var textFinalDisplay = textInteger + ',' + textDecimal
alert(textFinalDisplay);
Now you have the display saved in textFinalDisplay as a string, and the actual value saved as an integer in c.value
<input type="text" id="test" value=""></input>
<button type="button" id="get">Get value</input>
var test = document.getElementById("test"),
button = document.getElementById("get");
function doCommas(evt) {
var n = evt.target.value.replace(/,/g, "");
d = n.indexOf('.'),
e = '',
r = /(\d+)(\d{3})/;
if (d !== -1) {
e = '.' + n.substring(d + 1, n.length);
n = n.substring(0, d);
}
while (r.test(n)) {
n = n.replace(r, '$1' + ',' + '$2');
}
evt.target.value = n + e;
}
function getValue() {
alert("value: " + test.value.replace(/,/g, ""));
}
test.addEventListener("keyup", doCommas, false);
button.addEventListener("click", getValue, false);
on jsfiddle
you can get the actual value from variable x
<html>
<head>
<script type="text/javascript">
function abc(){
var x = document.getElementById('txt').value;
var y = x/1000;
var z = y+","+ x.toString().substring(1);
document.getElementById('txt').value = z;
}
</script>
</head>
<body>
<input type="text" id="txt" value="" onchange = "abc()"/>
</body>
This works with integer numbers on Firefox (Linux). You can access the "non-commaed"-value using the function "intNumValue()":
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
String.prototype.displayIntNum = function()
{
var digits = String(Number(this.intNumValue())).split(""); // strip leading zeros
var displayNum = new Array();
for(var i=0; i<digits.length; i++) {
if(i && !(i%3)) {
displayNum.unshift(",");
}
displayNum.unshift(digits[digits.length-1-i]);
}
return displayNum.join("");
}
String.prototype.intNumValue = function() {
return this.replace(/,/g,"");
}
function inputChanged() {
var e = document.getElementById("numInp");
if(!e.value.intNumValue().replace(/[0-9]/g,"").length) {
e.value = e.value.displayIntNum();
}
return false;
}
function displayValue() {
alert(document.getElementById("numInp").value.intNumValue());
}
</script>
</head>
<body>
<button onclick="displayValue()">Display value</button>
<p>Input integer value:<input id="numInp" type="text" oninput="inputChanged()">
</body>
</html>
I am trying to add a bulleted list to the page after the user enters 'exit' into a prompt; the list should not include the term 'exit'. I was able to get the list in full using document.write but this included the 'exit' and got rid of my page formatting. I am pretty sure I need to use innerHTML, but when I do this all I get is the page without any of the array items. Any help is greatly appreciated.
<html>
<head>
<img src="http://profperry.com/Classes20/JavaScript/lordoftherings.png" />
<title>Javascript Test</title>
<script>
function askMe() {
var fav_characterList = new Array();
i = 0;
var fav_character = "";
while(fav_character != 'exit'){
fav_character = prompt("Who's your favorite Lord of the Rings character\n\n Enter 'exit' to stop prompting", "");
fav_characterList[i] = fav_character;
i++;
}
n = (fav_characterList.length);
for(i = 0; i <= (n-1); i++){
var list = fav_characterList[i];
var MyList = getElementById('results');
MyList.innerHTML = "<li>"+list+"</li>";
}
}
</script>
</head>
<body onload="askMe()">
<ul>
<div id="results">
</div>
</ul>
<br/>
<br/>
</body>
you have to use document.getElementById() and also generate a string inside the loop and use inner html after the loop so that the previous li's dont get over written.
update the code portions like
n = (fav_characterList.length);
var kk="";
for(i = 0; i <= (n-1); i++){
var list = fav_characterList[i];
kk += "<li>"+list+"</li>"
}
var MyList = document.getElementById('results');
MyList.innerHTML = kk;
and in html , remove the div inside ul and giv id to ul
<ul id="results">
</ul>
and here is the full code becomes:
<html>
<head>
<img src="http://profperry.com/Classes20/JavaScript/lordoftherings.png" />
<title>Javascript Test</title>
<script type="text/javascript">
function askMe()
{
var fav_characterList = new Array();
i = 0;
var fav_character = "";
while(fav_character != 'exit')
{
fav_character = prompt("Who's your favorite Lord of the Rings character\n\n Enter 'exit' to stop prompting", "");
fav_characterList[i] = fav_character;
i++;
}
n = (fav_characterList.length);
var kk="";
for(i = 0; i <= (n-1); i++)
{
var list = fav_characterList[i];
kk += "<li>"+list+"</li>"
}
var MyList = document.getElementById('results');
MyList.innerHTML = kk;
}
</script>
</head>
<body onload="askMe()">
<ul id="results">
</ul>
<br/>
<br/>
</body>
</html>
You should use MyList.innerHTML += "<li>"+list+"</li>"; (notice the use of += instead of =)
Also, change your <ul> HTML to be:
...
<ul id="results">
</ul>
...