how to have a userinput be ".pushed" into an array - javascript

I would like the user to be able to add a url into the box submit it and then it will be in the array and be displayed in order. I would like this to be able to happen as many times as they click submit.
this is where I am but it searches my computer for the url rather than the web.
<!DOCTYPE html>
<html>
<head>
<title>images</title>
</head>
<body>
<input type="text" id="user_input" />
<button onClick="add()">ADD</button>
<img id="light" width="10%">
<button onclick="colourChange()">Click Me To Cycle Through The Colours</button>
<script>
var x=1
var user = document.getElementById("user_input");
var colour = ["red.gif", "amber1.gif", "green.gif", "amber1.gif"];
document.getElementById("light").src = colour[0];
function add(){
colour.push(user);
}
function colourChange(){
document.getElementById("light").src = colour[x];
x += 1;
if (x == colour.length ) x = 0
}
</script>
</body>
</html>

If you want this to be reset when user reloads the page, you don't need to use a form.
<input type="text" id="user_input" />
<button onClick=add()>ADD</button>
And your add function
function add(){
var newVal = document.getElementById('user_input').value;
fruits.push(newVal); //assuming your array is named fruits, I can't see in your code where you have defined it.
}

Replace your add function with
var imageInput = document.querySelector("input[name=url]");
function add(evnt){
evnt.preventDefault();
colour.push(imageInput.value);
return false;
}

First you need to declare the array before you try to push it.
var fruits = [];
and then in your add function, get the url element and push to the array you declared previously. It's convenient if you give the element an id.
function add() { fruits.push(document.getElementById('url').value); }
<!DOCTYPE html>
<html>
<head>
<title>images</title>
</head>
<body>
<form id="user">
insert an image URL to add to cycle: <input type="text" id="url" name="url"><br>
<button onclick="add()">ADD</button>
</form>
<img id="light" width="10%">
<button onclick="colourChange()">Click Me To Cycle Through The Colours</button>
<script>
var x = 1;
var colour = ["red.gif", "amber1.gif", "green.gif", "amber1.gif"];
var fruits = [];
document.getElementById("light").src = colour[0];
var url = document.getElementById('url');
function add(){
fruits.push(url.value);
}
function colourChange(){
document.getElementById("light").src = colour[x];
x += 1;
if (x == colour.length ) x = 0
}
</script>
</body>
</html>

Add into from tag onsubmit="return false" and see add() function which is mentioned in below line.
var x=1
var colour = ["red.gif", "amber1.gif", "green.gif", "amber1.gif"];
document.getElementById("light").src = colour[0];
function add(){
var newVal = document.getElementById('url').value;
colour.push(newVal);
document.getElementById('url').value = '';;
}
function colourChange(){
document.getElementById("light").src = colour[x];
x += 1;
if (x == colour.length ) x = 0
}
<!DOCTYPE html>
<html>
<head>
<title>images</title>
</head>
<body>
<form id="user" onsubmit="return false">
insert an image URL to add to cycle: <input type="text" name="url" id="url"><br>
<input type="submit" value="Submit" onclick="add()">
</form>
<img id="light" width="10%">
<button onclick="colourChange()">Click Me To Cycle Through The Colours</button>
</body>
</html>

Related

live update value if checkbox is checked or not

I am trying to update a textbox based on whether or not a checkbox is checked or not. Thanks to this post I got a text box working fine, but I can't get a checkbox to update the value. What am I missing?
<html>
<head>
<title>sum totals</title>
<script type="text/javascript">
function calculate(t){
var j = document.getElementById("output");
var rege = /^[0-9]*$/;
if ( rege.test(t.tons.value) ) {
var treesSaved = t.tons.value * 17;
j.value = treesSaved;
}
else
alert("Error in input");
}
$('input[name="selectedItems1"]').click(function(){
var j = document.getElementById("output");
if (this.checked) {
j.value=j.value+300
}else{
j.value=j.value-300
}
});
</script>
</head>
<body>
<form>
<input type="text" placeholder="Tons" id="tons" onkeyup="calculate(this.form)"/>
<br />
<input type="checkbox" name="selectedItems1" value="val1" />I have a car
<br/>
<input type="text" id="output" value="Output" />
</form>
</body>
</html>
Place the <script> tag after <form>
Reason:
When the html page loads, it'll be interpreted line by line. When it come to click(), jQuery will try to find the element input[name="selectedItems1"] which won't be loaded into the DOM at that time. So, jQuery won't attach the click() event handle to that checkbox. That's the reason why your code didn't work.
Try this :
<html>
<head>
<title>sum totals</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script><!-- load jquery -->
<script type="text/javascript">
function calculate(){
var j = document.getElementById("output");
var rege = /^[0-9]*$/;
var tons = $('#tons').val();
if ( rege.test(tons) ) {
val = parseInt(tons);
var treesSaved = val * 17;
if($('input[name="selectedItems1"]').is(":checked"))
{
treesSaved = treesSaved +300;
}
else
{
treesSaved = treesSaved -300;
}
if(isNaN(treesSaved))
j.value=0
else
j.value=treesSaved;
}
else
alert("Error in input");
}
$(function(){
$('input[name="selectedItems1"]').change(function(){
calculate();
});
});
</script>
</head>
<body>
<form>
<input type="text" placeholder="Tons" id="tons" onkeyup="calculate()"/>
<br />
<input type="checkbox" name="selectedItems1" value="val1" />I have a car
<br/>
<input type="text" id="output" value="Output" />
</form>
</body>
</html>

Create an HTML form with one field and button

I'm new in coding , there is a question that someone gave me and I can't find the right answer , this is the question :
Create an HTML form with one field and button.On button click,get the input,and return the sum of the previous value and the current input value.The value is 0 and input is 5->output is 5,then value is 5,input is 6-> output is 11 and etc.
I tried few things nothing even close ,
if someone can give me the answer Ill be much appreciated , thanks.
There you go, but you should try doing it yourself. it's pretty easy to google things like "on button click" etc.
var total = 0;
$('.js_send').click(function(){
total += parseInt($('.number').val());
$('.total').html(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" value="0" class="number"/>
<input type="button" value="send" class="js_send"/>
<div class="total">0</div>
Here's a JQuery free version
var oldInput = 0,
newInput,
outPut;
document.querySelector("#showSum").onclick = function() {
newInput = parseInt(document.querySelector("#newInput").value),
outPut = newInput + oldInput,
oldInput = outPut,
document.querySelector("#result").innerHTML = outPut;
};
#result {
width: 275px;
height: 21px;
background: #ffb6c1;
}
<input type="number" value="0" id="newInput">
<button id="showSum">Show Results</button>
<br>
<div id="result"></div>
Here is the solution to your problem. Put all below code into a html file and name it as index.html, then run the html page.
<html>
<head>
<title></title>
</head>
<body>
Output : <label id="output">0</label>
<form method="get" action="index.html">
Your Input: <input type="text" id="TxtNum"/>
<input type="hidden" id="lastvalue" name="lastvalue" />
<input type="submit" onclick="return doSum();" value="Sum" />
</form>
<script>
//- get last value from querystring.
var lastvalue = getParameterByName('lastvalue');
if (lastvalue != null) {
document.getElementById("lastvalue").value = lastvalue;
document.getElementById("output").innerHTML = lastvalue;
}
/*
* - function to calculate sum
*/
function doSum() {
var newvalue = 0;
if(document.getElementById("TxtNum").value != '')
newvalue = document.getElementById("TxtNum").value;
var lastvalue = 0;
if(document.getElementById("lastvalue").value != '')
lastvalue = document.getElementById("lastvalue").value;
document.getElementById("lastvalue").value = parseInt(newvalue) + parseInt(lastvalue);
output = parseInt(newvalue) + parseInt(lastvalue);
}
/*
* - function to get querystring parameter by name
*/
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
</script>
</body>
</html>
If you are doing it in server side, You could have a static variable and update it on button click. More like
public static int prevValue;
public int buttonclick(.....){
int sum = textboxValue + prevValue;
prevValue = textboxValue;
return sum;
}
here is your solution
<script type="text/javascript">
var sum=0;
function summ()
{
localStorage.setItem("value",document.getElementById("text").value);
var v=localStorage.getItem("value");
sum=sum+parseInt(v);
alert(sum);
}
</script>
<html>
<input id="text">
<button id="submit" onclick="summ()">sum</button>
</html>
It will be pretty easy.
Created CodePen
http://codepen.io/anon/pen/eJLNXK
function getResult(){
var myinputValue=document.getElementById("myinput").value;
var resultDiv=document.getElementById("result");
if(myinputValue && !isNaN(myinputValue)){
resultDiv.innerHTML=parseInt(myinputValue) + (resultDiv.innerHTML ? parseInt(resultDiv.innerHTML) : 0);
}
}
<input type="text" id="myinput">
<button id="btngetresult" onclick="getResult()">GetResult</button>
<p>
Result:
<div id="result"></div>
<!doctype html>
<html lang="en">
<head>
<title>Document</title>
<script type="text/javascript">
function sum() {
var t1 = parseInt(document.getElementById("t1").value);
var t2 = parseInt(document.getElementById("pre").value);
document.getElementById("result").innerHTML = t1+t2;
document.getElementById("pre").value = t1;
}
</script>
</head>
<body>
<div>
<form method="get" action="">
<input type="text" name="t1" id="t1">
<input type="button" value="get sum" name="but" onclick="sum()">
<input type="hidden" name="pre" id="pre" value="0">
</form>
</div>
<div id="result"></div>
</body>
</html>

Trying to get the result of javascript function using innerHTML

I have a simple program that takes in an input and then should show that input multiplied up to 100. I am new to this, but have tried to get it to work before posting here. I have the link to the program that I am referring to.
I want the result to be shown, but I cannot figure out why it is not showing.
You can see what I have below. I think I do not have the html and javascript hooked up properly.
Here is my html:
<body>
<input type="number" id="NumToBMultiplied" class="value" placeholder="Enter an integer" />
<input type='submit' id='RunProg' class='button' />
<p> id='result'</p>
</body>
Here is my Javascript:
h = document.getElementByID('NumToBMultiplied');
var result = document.getElementbyID('RunProg').addEventListener('click', function () {
for (i = 0; i < 100; i++)
return i * h;
}
});
document.getElementByID('result').innerHTML = result;
http://jsbin.com/wayejequxu/1/edit?html,js,output
Any help is appreciated!
From how I understand your code, you are wanting to multiply the input 100 times, then output that into a HTML tag. The result in your example is not being added to the result paragraph as it isn't in the loop.
HTML
This is changed only slightly. Notice the onClick="solve()" to the button instead of adding an event listener.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<input type="number" id="NumToBMultiplied" class="value" placeholder="Enter an integer"/>
<input type="submit" id="RunProg" onClick="solve()" class="button"/>
<p id="result"> </p>
</body>
</html>
Javascript
I've added a line break after each result of the for loop so the result is easier to read. And the output is cleared before a new solve() is run.
var output = document.getElementById("result");
function solve() {
var input = document.getElementById("NumToBMultiplied").value;
output.innerHTML = "";
for(i=0; i < 100; i++) {
output.innerHTML += i * input + "<br/>";
}
}
Result here: http://jsbin.com/foduyofewi/1/
You need to store your result in variable inside a callback and set innerHTML also in callback:
document.getElementById('RunProg').addEventListener("click", function() {
var result = 1;
var input = +h.value;
for (var i = 1; i < 100; i++) {
result *= i * input;
}
document.getElementById("result").innerHTML = result;
});
DEMO
Pure Javascript version:
function multiply(x) {
var result = document.getElementById('result');
result.innerHTML = x.value * 100;
}
<input type="number" id="NumToBMultiplied" class="value" onchange="multiply(this)" placeholder="Enter an integer"/>
<p id="result"></p>
This is the jQuery version:
$(document).ready(function() {
$('#NumToBMultiplied').on('change',function(){
$('#result').text($(this).val()*100);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="NumToBMultiplied" class="value" placeholder="Enter an integer"/>
<p id="result"></p>
Just some modification to your code to remove some of the typos and errors. I'm not sure you can return the result like how you have done it, a more traditional approach is shown below.
Full code
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="number" id="NumToBMultiplied" class="value" placeholder="Enter an integer" />
<input type='submit' id='RunProg' class='button' />
<p id='result'> </p>
</body>
<script>
h = document.getElementById('NumToBMultiplied').value;
document.getElementById('RunProg').addEventListener('click', function () {
for (i = 0; i < 100; i++){
var result = h*i;
}
document.getElementById('result').innerHTML = result;
});
</script>
</html>

Retrieve user input not working?

So my dilemmna is that I don't know how to record what the user inputs. (my goal as of now is to simply print what the user enters in an input box, not to add the numbers)
var x = document.getElementById('textboxone').value;
Why isn't this working?
<!DOCTYPE html>
<html>
<head>
<link href="cssFiles/ttt.css" rel="stylesheet" type="text/css"></link>
<script Language ="JavaScript">
//create skeleton divs
function createDivs () {
var s;
s = '<div class="simplebox" id="divBody">Bla 3 bla</div>';
document.write(s);
}
//create body skeleton
function createBodyDivs (sID) {
var s;
s = '<div class="smallerbox" id="divInput">';
s += '<div id="textboxone"><span>Add <input type="text" ></input></span></div>';
s += '<div id="textboxtwo"><span>To <input type="text" ></input></span></div>';
s += '<div id= style="margin-top: 100px;"><span> Click here to find the answer! <input type="button" value = "Answer Generator" OnClick="(this.form)"></input></span></div>';
var oDiv = document.getElementById(sID);
oDiv.innerHTML = s;
}
//adding the two numbers from input boxes
function addnumbers(form){
var x = document.getElementById('textboxone').value;
alert(x)
}
</script>
</head>
<body>
<script Language ="JavaScript">
createDivs();
createBodyDivs('divBody');
</script>
</body>
</html>
Check out AngularJS my friend! :)
JSFIddle Demo
<div ng-app="">
<input type="text" ng-model="data.message" />
<h1>{{data.message}}</h1>
<div class="{{data.message}}"></div>
</div>
using: https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.min.js
I've quickly checked the code and first of all you input button will not trigger addNumbers(form) since the onclick of the input doesn't point of that function.
Then for the function itself, document.getElementById('textboxone').value returns undefined because the actual value you want is in the <input> and not in the <div id="textboxone">
So if you have you're createBodyDivs function modified so that the id where on the input, then this document.getElementById('textboxone').value would actually return the correct value.
function createBodyDivs (sID) {
var s;
s = '<div class="smallerbox" id="divInput">';
s += '<div><span>Add <input type="text" id="textboxone" ></input></span></div>';
s += '<div><span>To <input type="text" id="textboxtwo" ></input></span></div>';
s += '<div id= style="margin-top: 100px;"><span> Click here to find the answer! <input type="button" value = "Answer Generator" OnClick="(this.form)"></input></span></div>';
var oDiv = document.getElementById(sID);
oDiv.innerHTML = s;
}
For the click binding, you button should be the following for it to work:
<input type="button" value = "Answer Generator" OnClick="addnumbers()"></input>

DOM event clearing text values

I'm writing a JS code to calculate a final grade given some individual grades and output the result in the html page but when I trigger the event and function it outputs a wrong answer for a split second then immediately disappears along with the values entered into the text box.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Problem 2</title>
<script src="grades.js" type="text/javascript"></script>
</head>
<body>
<h1>Grade Calculator</h1>
<form id ="myForm">
<div id="assignments">
HW <input type="text" size="1"/> / <input type="text" size="1"/><br/>
HW <input type="text" size="1"/> / <input type="text" size="1"/><br/>
HW <input type="text" size="1"/> / <input type="text" size="1"/>
</div>
<div>
<input type="checkbox" /> Curve +5?
</div>
<div id="resultsarea">
<p>
<!--add buttons here -->
<button id="comp">Compute</button>
<button id="clr">Clear</button>
</p>
<!-- add results here -->
</div>
</form>
</body>
</html>
JS:
window.onload = pageLoad;
function pageLoad()
{
var cbutton = document.getElementById("comp");
cbutton.onclick = compute;
}
function compute()
{
var values = document.getElementsByTagName("input");
var marks = 0;
var total = 0;
for (var i=0; i < values.length; i++)
{
if(values[i].type == "text")
{
if (i%2 == 0)
marks += parseInt(values[i].value);
else
total += parseInt(values[i].value);
}
}
var result = Math.round(marks/total);
document.writeln(result);
}

Categories

Resources