I'm trying to learn Javascript and I feel like I have a decent grasp on the fundamentals but I am having problems making it do things that i want .. for example.. I am trying to create a simple form in html that calculates the sum of 2 numbers.. here is my html and javascript:
<head>
<script type="text/javascript">
function adder(a,b) {
var a = document.getElementById('firstNum').value;
var b = document.getElementById('secondNum').value;
var numbers = new Array(a,b);
var sum = 0;
for (i=0; i < numbers.length; i++) {
sum += parseInt(numbers[i]);
}
//this part i need help with
document.getElementById('answer').write("First Number: " + a + " plus Second Number: " + b + " is " + sum).value; //this part i need help with
</script>
</head>
<body>
<form id="additionForm">
A + B = C : <input type="text" id="firstNum" placeholder="A">
+ <input type="text" id="secondNum" placeholder="B">
<input type="button" id="addBtn" value="Add" onClick="adder();">
= <input type="text" id="answer" placeholder="C">
</form>
</body>
My problem is that i don't know how to get the javascript to overwrite the value attribute for my form input id=answer .. or if i'm supposed to be using Jquery instead .. thanks in advance.
function adder() {
var a = parseInt( document.getElementById('firstNum').value, 10);
var b = parseInt( document.getElementById('secondNum').value, 10);
var sum = a + b;
//this part i need help with
document.getElementById('answer').value = "First Number: " + a + " plus Second Number: " + b + " is " + sum).value; //this part i need help with
}
If you want to modify an input field in javascript, you can simply set the value attribute:
document.getElementById('answer').value = "First Number: " + a + " plus Second Number: " + b + " is " + sum;
Related
For example, there is a page like below.
<html>
<head>
<title>Variables!!!</title>
<script type="text/javascript">
var lookatthis = 11;
var one = 22;
var two = 3;
var add = one + two;
var minus = one - two;
var multiply = one * two;
var divide = one/two;
document.write("First No: = " + one + "<br />Second No: = " + two + " <br />");
document.write(one + " + " + two + " = " + add + "<br/>");
document.write(one + " - " + two + " = " + minus + "<br/>");
document.write(one + " * " + two + " = " + multiply + "<br/>");
document.write(one + " / " + two + " = " + divide + "<br/>");
</script>
</head>
<body>
</body>
</html>
I want to assign the javascript variable "lookatthis" on debug console.
//apologise for my ambiguous question. I would rather say,
"I want to assign new value to variable "lookatthis" on this web-page using console on explorer."
Thank you for your kind teaching.)
Open debug console and write there:
lookatthis = 20
But this get you nothing
You can use the log method:
console.log(lookatthis);
Anywhere in your script block after your initial assignment of lookatthis, you can write the value to the console with the command:
console.log(lookatthis);
You achieve it by using prompt function
var lookatthis = prompt('Type the lokaltthis value');
If what you want is to be able to 'set' the value of lookatthis, you can use an input and using jquery or pure js get the value of the input and assign it to 'lookatthis'.
Edit: You can also use in the chrome console: lookatthis=25
but as your script loads when page loads, changes will not be shown but the value will be changed
So I have to use javascript and html to make a mad lib. I am asking the user to enter values and then hit the button and it is supposed to generate a story using the values they entered.
Here is my HTML:
<ul>
<li>Your Name: <input type="text" id="name"></li>
<li>Adjective: <input type="text" id="adjective"></li>
<li>State: <input type="text" id="state"></li>
<li>Animal: <input type="text" id="animal"></li>
<li>Month: <input type="text" id="month"></li>
<li>Adjective: <input type="text" id="adjective2"></li>
<li>Animal: <input type="text" id="animal2"></li>
<li>Object: <input type="text" id="object"></li>
</ul>
<button id="ready-button">Ready</button>
<div id="story"></div>
<script>
function madLib() {
var storyDiv = document.getElementById("story");
var adjective = document.getElementById("adjective").value;
var noun = document.getElementById("noun").value;
var state = document.getElementById("state").value;
var animal = document.getElementById("animal").value;
var month = document.getElementById("month").value;
var adjective2 = document.getElementById("adjective2").value;
var animal2 = document.getElementById("animal2").value;
var object = document.getElementById("object").value;
storyDiv.innerHTML ="One day, " + name + " was in the backwoods of " + state + " riding their pet " + animal + " it wasn't often that " + name + " got the chance to do this so they always made the most of their adventure. Usually, it was a fun experience until that one day in " + month + " they were minding their own business when all of the sudden the " + adjective2 + " " + animal2 + " jumped out from behind a small " + object + ". " + name + " could not beieve what they were seeing.";
}
var readyButton = document.getElementById('ready-button');
readyButton.addEventListener('click', madLib);
</script>
It seems that you got "noun" mixed up with "name" when grabbing the values for your story.
You have <input type="text" id="name"></li> and you use the name variable in your story a few times, but in the madLib function you have
var noun = document.getElementById("noun").value;
//document.getElementById("noun") will be undefined because there is no "noun element"
which should probably be
var name = document.getElementById("name").value;
I've been struggling with this for around an hour now and rewrote it about three different times and I can't for the life of me figure out what the issue is, regardless of what is entered, everything besides for the name field will return a value, however the name will just return undefined. I've gone over this so many times, I've copy+pasted+modified the working ones, there's not a single typo that I can find... What is going on here?
Item Name: <input type="text" id="item_name" placeholder="Enter a price..."/> </br>
Item Price: <input type="text" id="item_price" placeholder="Enter a price..."/> </br>
Item Description: <input type="text" id="item_description" placeholder="Enter a description..."/> </br>
Item Image(link): <input type="text" id="item_image" placeholder="Enter a image link..."/> </br>
rsid: <input type="text" id="rs_item_id" placeholder="Enter a item id..."/> </br>
rsam: <input type="text" id="rs_item_amount" placeholder="Enter a item amount..."/> </br>
<button id="update">Update item</button>
<script>
var name = document.getElementById("item_name");
var price = document.getElementById("item_price");
var desc = document.getElementById("item_description");
var img = document.getElementById("item_image");
var rsid = document.getElementById("rs_item_id");
var rsam = document.getElementById("rs_item_amount");
var button = document.getElementById("update");
button.addEventListener("click", function() {
alert("Name = " + name.value + "\n"
+ "Price = " + price.value + "\n"
+ "Desc = " + desc.value + "\n"
+ "Img = " + img.value + "\n"
+ "rsid = " + rsid.value + "\n"
+ "rsam = " + rsam.value + "\n");
});
</script>
The problem is that because you make them all global variables the name one clashes with the window.name property.
Either using a different variable name, or creating a closure will work
Put name, price, desc, img, rsid, rsam inside event handler.
var button = document.getElementById("update");
button.addEventListener("click", function() {
var name = document.getElementById("item_name");
var price = document.getElementById("item_price");
var desc = document.getElementById("item_description");
var img = document.getElementById("item_image");
var rsid = document.getElementById("rs_item_id");
var rsam = document.getElementById("rs_item_amount");
alert("Name = " + name.value + "\n"
+ "Price = " + price.value + "\n"
+ "Desc = " + desc.value + "\n"
+ "Img = " + img.value + "\n"
+ "rsid = " + rsid.value + "\n"
+ "rsam = " + rsam.value + "\n");
});
Demo: http://jsbin.com/fivos/1/edit?html,output
I created a button with JScript that adds textareas (questions) one below another onClick. I'm having a trouble in adjusting a function that will change the name of the textareas depending on the number of question (variable n).
So, for the question 1, I want to have textarea name="question1" ...
Is there any other solution? Mine is not working :(
View code on jsfiddle
<input type="submit" value="ADD" onClick="add();">
<div id="new"></div>
script.js
n=1;
function add() {
if(1==1){
document.getElementById('new').innerHTML += '<div>' + n + '. Question: <br/><textarea name="question[n]" rows="4" cols="50"></textarea><br/></div>';
n++;
}}
You almost had it.
n=1;
function add() {
document.getElementById('new').innerHTML += '<div>' + n + '. Question: <br/><textarea name="question'+n+'" rows="4" cols="50"></textarea><br/></div>';
n++;
}
Updated fiddle: http://jsfiddle.net/5FJ4a/2/
Can make your brain happier and debugging easier by splitting up long concatenated strings.
var n=1,
container,
start, middle, end, out;
function add() {
container = document.getElementById('questions');
start = '<div>' + n + '. Question: <br/>';
middle = '<textarea name="question'+n+'" rows="4" cols="50">';
end = '</textarea><br/></div>';
out = start + middle + end;
container.innerHTML += out;
n++;
}
Alternate fiddle: http://jsfiddle.net/5FJ4a/4/
document.getElementById('new').innerHTML += '<div>' + n + '. Question: <br/><textarea name="question'+n+'" rows="4" cols="50"></textarea><br/></div>';
I try to build an register form. This register form as text box called "address1" and near it a button called "Add Address". The function of the button - it adds text box for more addresses. the button near the previous address boxes changes to "Remove" which remove the address box and the button. The problem is: I have to set the text boxes in order - 1,2,3,... - I have to change their names and id's. For example - if I remove addressbox number 4 (name, id="address4") then all the next text boxes's names and id's should decrease by 1. I try to do this in for loop. This is hard to explain so I just give you the code. Try in your VS to write for example 'document.getElementById("address"+n).' and you'll see that you even don't see in the list you get that you can write after the dot id or name or value. I realized it is because there is a variable in this is the problem I think. Now here's the code:
<html>
<head>
<title>Untitled Page</title>
<script type="text/javascript">
var n1 = 1; //counting the buttons and divs. doesn't decrease.
//In another words - it counts the number of calls to Add()
var n3 = 1; //counting the address text fields.
//It being reduced and increased so that it will represent the exact number of text fields
function Add() {
n1++;
n3++;
s1 = "<div id='div" + n1 + "'>";
s1 += "Address <input type='text' name='address" + n3 + "' id='address" + n3 + "' />";
s1 += "<input type='button' name='add" + n1 + "' id='add" + n1 + "' value='Add Branch' onclick='Add();' /><br />";
s1 += "</div>";
var n2 = n1 - 1;
document.getElementById('div' + n2).insertAdjacentHTML('afterEnd', s1);
document.getElementById('add' + n2).onclick = function () { Remove(n2, (n3-1)); };
document.getElementById('add' + n2).value = 'Remove';
}
function Remove(nn1, nn2) { //nn1 - div number to remove. nn2 - the address field number in this div
var parent = document.getElementById('barcode');
var child = document.getElementById('div' + nn1);
parent.removeChild(child);
for (nn2 += 1; nn2 <= n3; nn2++) {
var n2 = nn2 - 1; //nn2 - current address text field. n2 - the new number for the address field
document.getElementById('address' + nn2).setAttribute('name', 'address' + n2);
document.getElementById('address' + nn2).setAttribute('id', 'address' + n2);
document.getElementById('address' + n2).setAttribute('value', 'address' + n2);
// try: document.getElementById('address' + nn2).name='address'+n2. doesn't work (for me)
}
n3--;
}
var check = false;
</script>
</head>
<body>
<form name='barcode' id='barcode' action="" >
<div id='div1'>
Address <input type='text' name='address1' id='address1' />
<input type='button' name='add1' id='add1' value='Add Branch' onclick='Add();' /><br />
</div></form>
</body>
</html>
Sorry for the disorder :) I keeped in this code only what linked to the address field and I added comments.
Thanks very much!
edit:
I forgot that you don't see the bug in this code because I already tried to fix it. Before I changed the code it ordered all the divs, text fields and add/remove buttons so all the exsisting items will always be numbered in order (1, 2, 3, ...).
The problem in the following code can be seen if you click 2 times add button, then you remove the first address field and then you click the add button again.
<html>
<head>
<script type="text/javascript">
var n1 = 1;
function Add() {
n1++;
s1 = "<div id='div" + n1 + "'>";
s1 += "Address <input type='text' name='address" + n1 + "' id='address" + n1 + "' />";
s1 += "<input type='button' name='add" + n1 + "' id='add" + n1 + "' value='Add Branch' onclick='Add()' /><br />";
s1 += "</div>";
var n2 = n1 - 1;
document.getElementById('div' + (n2)).insertAdjacentHTML('afterEnd', s1);
document.getElementById('add' + (n2)).onclick = function () { Remove(n2); };
document.getElementById('add' + (n2)).value = 'Remove';
}
function Remove(n) {
var parent = document.getElementById('barcode');
var child = document.getElementById('div' + n);
parent.removeChild(child);
for (n += 1; n <= n1; n++) {
var n2 = n1 - 1;
document.getElementById('add' + n).onclick = function () { Remove(n2); };
document.getElementById('address' + n).setAttribute('name', 'address' + n2);
document.getElementById('add' + n).setAttribute('name', 'add' + n2);
document.getElementById('address' + n).setAttribute('id', 'address' + n2);
document.getElementById('add' + n).setAttribute('id', 'add' + n2);
document.getElementById('div' + n).setAttribute('id','div' + n2);
}
n1--;
document.getElementById('add' + n1).onclick = function () { Add() };
}
</script>
</head>
<body>
<form name='barcode' id='barcode' action="" >
<div id='div1'>
Address <input type='text' name='address1' id='address1' />
<input type='button' name='add1' id='add1' value='Add Branch' onclick='Add();' /><br />
</div>
</form>
</body>
</html>
I think you are working a bit too hard to maintain the order of the addresses and i don't see a general reason to do it (if you have one, please add it to your question).
If you add the inputs with a unique index like you are doing, they will always be different and ordered.
Here's what you can do:
Pass the event caller to the functions Add and Remove and inside you can make the changes you want to those elements.
For example your Remove function (that you would call with Remove(this);) would look like this:
function Remove(callerButton) {
var parent = document.getElementById('barcode');
var child = callerButton.parentNode;
// child is the DIV you want to remove
parent.removeChild(child);
n3--;
}
This way you wouldn't need to do all the sorting you are doing right now.
At the end you can access all the remaining elements with:
var addresses = document.getElementById("barcode").getElementsByTagName("input");
for(var i = 0; i < addresses.length; i++) {
if(addresses[i].type == "text") {
// I'm printing them in the console, you can do with it whatever you like
// If you want to exclude the one with "Add Branch in front of it you can validate for address+n1
console.log("Element.id : " + addresses[i].id + " - Element.value: "+ addresses[i].value );
}
}
I added a jsFiddle with these changes (added a submit button to show the remaining fields in the form).
See if it solves your problem.