How to display an image as many times as input(number) given by the user in html using javascript? There seem to be an error in my code,dont know how to rectify.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to add a new element to the array.</p>
<input type="number" id="myNumber" value="">
<button onclick="imag(c,x)">Try it</button>
<p id="demo"></p>
<script>
function imag(c,x) {
var x = document.getElementById("myNumber").value;
var c="<img src='C:/Users/Akhil/Desktop/New folder/G.jpg'/>";
var arr = [];
for (var i = 0; i < x; i++) {
arr.push(c);
document.getElementById("demo").innerHTML = arr;
}
}
</script>
</body>
</html>
Try this:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to add a new element to the array.</p>
<input type="number" id="myNumber" value="">
<button onclick="imag()">Try it</button>
<p id="demo"></p>
<script>
function imag() {
var x = document.getElementById("myNumber").value;
var c = '\<img src="http://static.guim.co.uk/sys-images/Guardian/Pix/pictures/2014/4/11/1397210130748/Spring-Lamb.-Image-shot-2-011.jpg"\/\>';
var arr = [];
for (var i = 0; i < x; i++) {
arr.push(c);
document.getElementById("demo").innerHTML = arr;
}
}
</script>
</body>
</html>
Notice that I just changed <button onclick="imag(c,x)">Try it</button> to <button onclick="imag()">Try it</button>; and I switched your apostrophes here: var c="<img src='C:/Users/Akhil/Desktop/New folder/G.jpg'/>";
You told javascript that imag() should get two variables. but you never gave the function actual variables (and you filled them inside the function). so I removed the variables from the function's deceleration.
second thing I did was change the Quotation marks and Apostrophes since HTML standards require Quotation marks for the tags' content. switching between them allows you to keep the HTML standard.
The .innerHTML property takes a string. So, you need to convert your array to a single string like this:
document.getElementById("demo").innerHTML = arr.join("");
Note that 'C:/Users/Akhil/Desktop/New folder/G.jpg' is generally not a valid URL to refer to your image so you may need to fix that too. You can read here to see how file URLs work: http://en.wikipedia.org/wiki/File_URI_scheme
And, there's no reason to pass two empty variables to your imag() function. You can change this:
<button onclick="imag(c,x)">Try it</button>
to this:
<button onclick="imag()">Try it</button>
Firstly, you call imag function with the c and x, but the code doesn't know anything about them. That's why you get a TypeError.
You should create an event handler for the click event of the button, not this inline handler, where you can pass whatever you like at values of x and c.
Check this plunk here
And lastly, the innerHTML property takes a string (HTML or plain text). But in this case it will join all your values, comma separated, because the toString method of the array is invoked. Reference here
Your variables x and c are undefined, there is nothing in it so your code breaks. This is how parameters work, you give them a value and pass them to the function, so c becomes 'hello' and x becomes 5, fiddle:
<p>Click the button to add a new element to the array.</p>
<input type="number" id="myNumber" value="">
<button onclick="imag('hello',5)">Try it</button>
<p id="demo"></p>
Javascript
function imag(c,x) {
var arr = [];
for (var i = 0; i < x; i++) {
arr.push(c);
document.getElementById("demo").innerHTML = arr;
}
}
But this is not very flexible right? So your solution is already stated in other answers. You don't pass in parameters and make the variables in the function everytime you click on the button and please stop using inline calls. It is really outdated, messy and unnecessary! Learn how to use eventhandlers.
Related
How do I use a checkbox in JS/jQuery to toggle just between 2 numbers?
I want unchecked to always be $0 and checked to always be $100. The code below comes close. I'm looking to use str.replace as opposed to switching divs using display:none.
Code:
function myFunction() {
let str = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML = str.replace("$0", "$100");
}
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String</h2>
<p>The replace() method searches a string for a specified value, or a regular expression,
and returns a new string where the specified values are replaced.</p>
<p id="demo">$0</p>
<input type="checkbox" onclick="myFunction()" value="Try It">
</body>
</html>
function myFunction() {
const element = document.getElementById('demo')
element.innerText = element.innerText === '$0' ? '$100' : '$0'
}
I'm trying to build something simple here:
a user types into an input field a url eg. http://sharepoint.com/human-resources/usa/Lists/testList/EditForm.aspx?ID=666&Source=http%3A%2F%sharepoint.com
.. hits "submit", when the URL gets spit out as a link, changing into: https://sharepointusa.com/en-us/human-resources/usa/Lists/testList/EditForm.aspx?ID=666&Source=http%3A%2F%sharepoint.com
I've been trying unsuccessfully to just spit out the whole URL, losing parameters, so I need a new approach, what is an easy vanilla javascript to just replace http://sharepoint.com/ with https://sharepointusa.com/en-us/ and leave the rest of the URL?
thanks
EDIT: 2 great answers, thank you, I adapted the first answer to my original code, while I play around with the second answer to see how it compares!:
<br>
<input type="text" id="userInput" value="Enter your text here"><br>
<input type="button" onclick="changeText2()" value="change text">
<script>
function changeText2()
{
var input=document.getElementById('userInput').value;//gets the value entered by user
const updatedUrl = input.replace('http://sharepoint.com/', 'https://sharepointusa.com/en-us/');
document.getElementById("link").href = updatedUrl;
document.getElementById("link").innerHTML = updatedUrl;
}
</script>
if you have a variable containing the full original url
const url = 'http://sharepoint.com/human-resources/usa/Lists/testList/EditForm.aspx?ID=666&Source=http%3A%2F%sharepoint.com';
then you can just do
const updatedUrl = url.replace('http://sharepoint.com/', 'https://sharepointusa.com/en-us/');
and updatedUrl will have what you're asking for.
It1 got it right before me! anyways, this is a more advanced representation of how to change it directly from the input fields.
<!DOCTYPE html>
<html>
<body>
<input id="demo" value="http://sharepoint.com/human-resources/usa/Lists/testList/EditForm.aspx?ID=666&Source=http%3A%2F%sharepoint.com">
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var str = document.getElementById("demo").value;
var changed = str.replace("sharepoint", "sharepointusa");
document.getElementById("demo").value = changed;
}
</script>
</body>
</html>
I'm trying to get it to add the two numbers inputted by the user, and print it inside of the p tag. Any help would be much appreciated. Here's the code:
<html>
<!DOCTYPE HTML>
<meta charset="UTF-8" name="viewport" content="width=device-width">
<head>
<title>Calculator</title>
</head>
<body>
<h2>Enter in the values you want to add</h2>
<form>
<input id="num1" name="num1" type="number"> //value one
</br>
<input id="num2" name="num2" type="number"> //value two
<button id="calculate">Calculate</button> //Click to calculate
</form>
<p id="p">The answer will show here</p>
<script>
var p1=document.getElementById("p");
var p=p1.innerHTML;
var calc=document.getElementById("calculate");
calc.addEventListener("click", answer); //When the button is clicked it calls the function answer()
function answer() {
var num1=document.getElementById("num1");
var num2=document.getElementById("num2");
var x=num1.innerHTML;
var y=num2.innerHTML;
p=x+y; //print the sum of the two values, inside of the p tag
}
</script>
</body>
To decode what's going on in your JavaScript, please see my annotations to the code:
var p1=document.getElementById("p"); // Stores a reference to an element with id "p" to variable p1
var p=p1.innerHTML; // Retrieves the HTML contents of said attribute and assigns it to variable p (not needed)
var calc=document.getElementById("calculate"); // Stores a reference to an element with id "calc" (your button) to variable calc
calc.addEventListener("click", answer); // Attaches an event handler to the element referenced via variable calc
function answer()
{
var num1=document.getElementById("num1"); // Stores a reference to an element with id "num1" in variable num1
var num2=document.getElementById("num2"); // Stores a reference to an element with id "num2" in variable num2
var x=num1.innerHTML; // Retrieves the HTML contents of the element referenced by num1 and stores it in variable x (error)
var y=num2.innerHTML; // Retrieves the HTML contents of the element referenced by num2 and stores it in variable y (error)
p=x+y; // Since both x and y are strings, they are concatenated and the result is stored in variable p (produces wrong result)
// Missing assignment of result to output element
}
The problem: You don't have a statement that actually assigns the result to the paragraph marked with ID "p", instead you are modifying a variable.
Furthermore, since you are retrieving strings from the input fields, the addition is in reality a concatenation, producing a false result (num1.value and num2.value are needed to access the actual values). I'd also suggest converting things to an integer - parseInt does the trick here.
There are several errors in your code, will try to address them one by one:
The <button> by default is type="submit" which when pressed refreshes the whole page, not the intended behaviour. To fix it just need to add type="button", which makes it behabe like a button that by itself does nothing.
The result of p=x+y, you are doing nothing with it. p is just a variable containing the result of the operation, but you need then to insert it inside the <p> tag for it to show up. Adding this at the end of your answer() function should fix it: p1.innerHTML = p;.
The <input> values, those are stored in the value property instead of the innerHTML. So it should look like this var x=num1.value; and var y=num2.value;.
The "sum", in JavaScript the + operator can be used both to add numerical values and to concatenate strings, and the engine chooses what to do guessing by the type of the values you are using, in your case strings. Because even if you type 1 in the input, retrieving it later with .values will return it as a string. You have to cast it back to a number to get the desired result. Just doing this is enought var x=Number(num1.value); and var y=Number(num2.value);.
And that's all.
Here you have your code with the fixes applied.
<html>
<!DOCTYPE HTML>
<meta charset="UTF-8" name="viewport" content="width=device-width">
<head>
<title>Calculator</title>
</head>
<body>
<h2>Enter in the values you want to add</h2>
<form>
<input id="num1" name="num1" type="number"> //value one
</br>
<input id="num2" name="num2" type="number"> //value two
<button type="button" id="calculate">Calculate</button> //Click to calculate
</form>
<p id="p">The answer will show here</p>
<script>
var p1=document.getElementById("p");
var p=p1.innerHTML;
var calc=document.getElementById("calculate");
calc.addEventListener("click", answer); //When the button is clicked it calls the function answer()
function answer() {
var num1=document.getElementById("num1");
var num2=document.getElementById("num2");
var x=Number(num1.value);
var y=Number(num2.value);
p=x+y; //print the sum of the two values, inside of the p tag
p1.innerHTML = p;
}
</script>
</body>
Sorry for the lengthy answer but tried to attack each error by itself and it's explanation as clear and simple as I can do.
p = p1.innerHTML
copies the contents of your paragraph into the variable p.
So your
p = x+y
merely assigns a new value to your variable p and doesn't change the innerHTML of your paragraph.
Try
p1.innerHTML = (x + y) + ''; // + '' converts the result of x + y to a string
You should also use '.value' instead of '.innerHTML' to get the contents of your inputs and then convert them to numbers with parseInt() before adding them.
There were quite a few issues; you can't copy the innerHTML of a p and then assign it a value. You must convert the input values to integers in order to add them. With inputs you can ask for their "value" rather than innerHTML.
<html>
<!DOCTYPE HTML>
<meta charset="UTF-8" name="viewport" content="width=device-width">
<head>
<title>Calculator</title>
</head>
<body>
<h2>Enter in the values you want to add</h2>
<form>
<input id="num1" name="num1" type="number"> //value one
</br>
<input id="num2" name="num2" type="number"> //value two
<button id="calculate">Calculate</button> //Click to calculate
</form>
<p id="p">The answer will show here</p>
<script>
var p1=document.getElementById("p");
var calc=document.getElementById("calculate");
calc.addEventListener("click", answer); //When the button is clicked it calls the function answer()
function answer(e) {
e.preventDefault();
var num1=document.getElementById("num1");
var num2=document.getElementById("num2");
var x=parseInt(num1.value, 10);
var y=parseInt(num2.value, 10);
p1.innerHTML = x+y; //print the sum of the two values, inside of the p tag
}
</script>
</body>
</html>
hi so i am new to javascript and i am trying to make a simple calculator using HTML and js. However i have run into a problem where i press the button to calculate the answer and it wont do anything. I tried it in an online ide and it just gave me the wrong answer. here is the code can anyone help. thanks--
<!DOCTYPE html>
<html>
<head>
<title>calculator</title>
<script type="text/javascript">
document.getElementById("equals").onclick = function() {
var answer = parseInt(document.getElementById('number_1').value)+ parseInt(document.getElementById('number_1').value);
document.getElementById('answer').innerHTML = answer;
};
</script>
</head>
<body>
<input type="text" name="number_1" id = "number_1">
<p>+</p>
<input type="text" name="number_2" id = "number_2">
<input type="submit" name="equals" id = "equals" value="=">
<p id = "answer"></p>
</body>
</html>
forms including onClick conditions without GET/POST methods , generally use button .
<input type="button" name="equals" id="equals" value="=">
I guess you are adding same variables twice ?
var answer = parseInt(document.getElementById('number_1').value)+ parseInt(document.getElementById('number_2').value);
You're adding the value from the same input twice and you have to set the event handler after the button is created, .
<body>
<input type="text" name="number_1" id = "number_1">
<p>+</p>
<input type="text" name="number_2" id = "number_2">
<input type="submit" name="equals" id = "equals" value="=">
<p id = "answer"></p>
<script type="text/javascript">
document.getElementById("equals").onclick = function() {
var answer = parseInt(document.getElementById('number_1').value)+ parseInt(document.getElementById('number_1').value);
document.getElementById('answer').innerHTML = answer;
};
</script>
</body>
The main problem is you are adding the event click to element equals, but in these moment, element equals doesn't exists.
wrap your document.getElementById into window.onload function to say javascript: "when all the document finish to load, add the event click to element equals"
try this:
window.onload = function () {
document.getElementById("equals").onclick = function() {
var answer = parseInt(document.getElementById('number_1').value, 10)+ parseInt(document.getElementById('number_2').value, 10);
document.getElementById('answer').innerHTML = answer;
};
}
Another important thing I have added ,10 to your parseint, this is to make sure that the conversion is to a number into decimal mode
"The parseInt() function parses a string and returns an integer.
The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.
If the radix parameter is omitted, JavaScript assumes the following:
If the string begins with "0x", the radix is 16 (hexadecimal)
If the string begins with "0", the radix is 8 (octal). This feature is deprecated
If the string begins with any other value, the radix is 10 (decimal)"
Source: parseInt use
i fixed it now i had to wrap my code in a window.onload
<!DOCTYPE html>
<html>
<head>
<title>calculator</title>
<script type="text/javascript">
window.onload = function(){
document.getElementById("equals").onclick = function() {
var answer = parseInt(document.getElementById('number_1').value)+ parseInt(document.getElementById('number_2').value);
document.getElementById('answer').innerHTML = answer;
};
};
</script>
</head>
<body>
<input type="text" name="number_1" id = "number_1">
<p>+</p>
<input type="text" name="number_2" id = "number_2">
<button id = "equals">=</button>
<p id = "answer"></p>
</body>
</html>
I want to print variables in the same paragraph but on different lines. I was using this:
<p id="demo1"></p><p id="demo2"></p><p id="demo3"></p>
<button type="button" onclick="myFunction()">Try It!</button>
<script>
function myFunction()
{
var lastname="Doe";
var age=30;
var job="carpenter";
document.getElementById("demo1").innerHTML=lastname;
document.getElementById("demo2").innerHTML=age;
document.getElementById("demo3").innerHTML=job;
}
</script>
but it prints each value in a new paragraph. I tried changing to classname instead but I'm doing something wrong. Help me please. TY.
<p class="demo1, demo2, demo3"></p>
<button type="button" onclick="myFunction()">Try It!</button>
<script>
function myFunction()
{
var lastname="Doe";
var age=30;
var job="carpenter";
document.getElementByClassName("demo1").innerHTML=lastname;
document.getElementByClassName("demo2").innerHTML=age;
document.getElementByClassName("demo3").innerHTML=job;
}
</script>
Also can you use
document.getElementById("demo1").innerHTML=lastname;
and more then one id and value at then end? Something like this?
document.getElementById("demo1,demo2,demo3").innerHTML=lastname,age,job;
How can you read that correctly, I know the above not valid, but what is the correct method to do it?
Ty
Jared Moore
<p id="demo1"></p>
<button type="button" onclick="myFunction()">Try It!</button>
<script>
function myFunction()
{
var lastname="Doe";
var age=30;
var job="carpenter";
var concat = lastname + '<br />' + age + '<br />' + job
document.getElementById("demo1").innerHTML=concat;
}
</script>
The reason that the three parts are in three different paragraphs is that you have three p elements. If you want all the values to be in the same paragraph, you should use an inline element, such as span. This is what it would look like:
<p><span id="demo1"></span><span id="demo2"></span><span id="demo3"></span></p>
By the way, using innerHTML is asking for someone to hack your site; if your real code looks anything like this:
element.innerHTML = userSuppliedData
then anyone can run whatever JavaScript they want on your page by passing this:
<script type="text/javascript">
alert('All your site are belong to us.');
</script>
This is known as cross-site scripting, XSS. Instead, do this:
element.appendChild(document.createTextNode(userSuppliedData))