Javascript: Writing HTML dynamically via innerHTML - javascript

Im not sure why I cannot dynamically write to the paragraph element. I've even tried with just a string to no avail. What am I doing wrong here? Im guessing the default behavior is to POST because that's all that happens, even though I'm not telling it to do it.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
<!--
function submit() {
var fName = "";
var lName = "";
var eLevel = "";
fName = document.person.elements["fName"].value;
lName = document.person.elements["lName"].value;
eLevel = document.person.elements["eLevel"].value;
var result = fName + " " + lName + "<br>" + eLevel;
document.getElementById("result").innerHTML = result;
};
//-->
</script>
</head>
<body>
<form action="" id="person">
Please fill in all fields.<br /><br />
<fieldset><legend>Name:</legend>
First: <input type="text" id="fName" name="fName" /><br /><br />
Last:
<input type="text" id="lName" name="lName" />
</fieldset>
<br />
<fieldset>
<legend>Education:</legend>
Highest Level:
<input list="eLevels" name="eLevel" />
<datalist id="eLevels">
<option value="High School">
<option value="Associate Degree">
<option value="Bachelors Degree">
<option value="Graduate Degree">
</datalist>
</fieldset>
<br /><button value="click" onclick="submit()">click</button>
</form>
<p id="result"></p>
</body>
</html>

You need to preventDefault on the form submit, this way your code can execute.
function submit(event) {
event.preventDefault();
var fName = "";
var lName = "";
var eLevel = "";
fName = document.person.elements["fName"].value;
lName = document.person.elements["lName"].value;
eLevel = document.person.elements["eLevel"].value;
var result = fName + " " + lName + "<br>" + eLevel;
document.getElementById("result").innerHTML = result;
};
For the event parameter you will need to pass it in the onClick() event
<button value="click" onclick="submit(event)">click</button>

Related

JavaScript Error Finding the error on why my qty of items *cost of items won't give me a final answer

Can Someone help me? so my code allows me to send out an alert box when I run my system; first name, last name, street address, city, state, zip, something you want to buy and some type of amount. It runs but then it doesn't display the final amount of the (qty* cost of the item) at the end.
Am I missing something? how can I get it working?
Once I have the website I have no error, when I run it and it reaches the end I receive an error (Uncaught TypeError: Cannot set property 'value' of null) this line
if (document.getElementById("txtPurchase").value= "Gameboy"){
and <p><input type="button" value="Go!" name="btnSubmit" onclick="ordering()" ></p>
(Uncaught TypeError: Cannot set property 'value' of null
at ordering (line:35)
at HTMLInputElement.onclick (line:85)
ordering (line:35)
onclick (line:85)
<!DOCTYPE>
<html lang="en">
<head>
<meta charset="utf-8" />
<title> Confirmations on orders</title>
</head>
<body>
<script type="text/javascript">
function ordering() {
var firstName;
firstName = document.practiceForm.txtFirstName.value;
alert(firstName);
var lastName;
lastName = document.practiceForm.txtLastName.value;
alert(lastName);
var streetAddress;
streetAddress = document.practiceForm.txtStreetAddress.value;
alert(streetAddress);
var city;
city = document.practiceForm.txtCity.value;
alert(city);
var state;
state = document.practiceForm.txtState.value;
alert(state);
var zip;
zip = document.practiceForm.txtZip.value;
alert(zip);
if (document.getElementById("txtPurchase").value = "Gameboy") {
var gameboyPrice = 25;
var gameboyQuantity = document.getElementsById("quantity").value;
var gameboyTotal = gameboyPrice * gameboyQuantity;
alert("total: $" + gameboyTotal);
} else if (document.getElementById("txtPurchase").value = "DSI") {
var dsiPrice = 50;
var dsiQuantity = document.getElementsById("quantity").value;
var dsiTotal = dsiPrice * dsiQuantity;
alert("total: $" + dsiTotal);
} else if (document.getElementById("txtPurchase").value = "WII") {
var wiiPrice = 75;
var wiiQuantity = document.getElementsById("quantity").value;
var wiiTotal = wiiPrice * wiiQuantity;
alert("total: $" + wiiTotal);
}
}
</script>
<form name="practiceForm">
<p>First Name: <input type="text" name="txtFirstName"></p>
<p>Last Name: <input type="text" name="txtLastName"></p>
<p>Street Address: <input type="text" name="txtStreetAddress"></p>
<p>City: <input type="text" name="txtCity"></p>
<p>State: <input type="text" name="txtState"></p>
<p>Zip: <input type="text" name="txtZip"></p>
<p>What do you want to purchase today?:
<select id="txtPurchase">
<option value="Gameboy">Gameboy $25 each</option>
<option value="DSI">DSI $50 each</option>
<option value="WII">Wii $75 each</option>
</select>
</p>
<p>How much would you like to buy?: <input type="number" id="quantity"></p>
<p><input type="button" value="Go!" name="btnSubmit" onclick="ordering()"></p>
</form>
</body>
</html>
Use == instead of = in if conditions
And
In one place you use getElementsById("quantity")
Instead use getElementById("quantity") //No 's'
So your script tag should look like
<!DOCTYPE>
<html lang="en">
<head>
<meta charset="utf-8" />
<title> Confirmations on orders</title>
</head>
<body>
<script type="text/javascript">
function ordering() {
var firstName;
firstName = document.practiceForm.txtFirstName.value;
alert(firstName);
var lastName;
lastName = document.practiceForm.txtLastName.value;
alert(lastName);
var streetAddress;
streetAddress = document.practiceForm.txtStreetAddress.value;
alert(streetAddress);
var city;
city = document.practiceForm.txtCity.value;
alert(city);
var state;
state = document.practiceForm.txtState.value;
alert(state);
var zip;
zip = document.practiceForm.txtZip.value;
alert(zip);
if (document.getElementById("txtPurchase").value == "Gameboy") {
var gameboyPrice = 25;
var gameboyQuantity = document.getElementById("quantity").value;
var gameboyTotal = gameboyPrice * gameboyQuantity;
alert("total: $" + gameboyTotal);
} else if (document.getElementById("txtPurchase").value == "DSI") {
var dsiPrice = 50;
var dsiQuantity = document.getElementsById("quantity").value;
var dsiTotal = dsiPrice * dsiQuantity;
alert("total: $" + dsiTotal);
} else if (document.getElementById("txtPurchase").value == "WII") {
var wiiPrice = 75;
var wiiQuantity = document.getElementsById("quantity").value;
var wiiTotal = wiiPrice * wiiQuantity;
alert("total: $" + wiiTotal);
}
}
</script>
<form name="practiceForm">
<p>First Name: <input type="text" name="txtFirstName"></p>
<p>Last Name: <input type="text" name="txtLastName"></p>
<p>Street Address: <input type="text" name="txtStreetAddress"></p>
<p>City: <input type="text" name="txtCity"></p>
<p>State: <input type="text" name="txtState"></p>
<p>Zip: <input type="text" name="txtZip"></p>
<p>What do you want to purchase today?:
<select id="txtPurchase">
<option value="Gameboy">Gameboy $25 each</option>
<option value="DSI">DSI $50 each</option>
<option value="WII">Wii $75 each</option>
</select>
</p>
<p>How much would you like to buy?: <input type="number" id="quantity"></p>
<p><input type="button" value="Go!" name="btnSubmit" onclick="ordering()"></p>
</form>
</body>
</html>
var dsiQuantity=document.getElementsById("quantity").value;
you have a typo mistake here. Change it to
var dsiQuantity=document.getElementById("quantity").value;
Two things you need to change
1. in if condition - put == in place of =
2. for numeric value you need to parse them into proper number (i.e. int or float)
<!DOCTYPE>
<html lang="en">
<head>
<meta charset="utf-8" />
<title> Confirmations on orders</title>
</head>
<body>
<script type="text/javascript">
function ordering() {
var firstName;
firstName = document.practiceForm.txtFirstName.value;
console.log(firstName);
var lastName;
lastName = document.practiceForm.txtLastName.value;
console.log(lastName);
var streetAddress;
streetAddress = document.practiceForm.txtStreetAddress.value;
console.log(streetAddress);
var city;
city = document.practiceForm.txtCity.value;
console.log(city);
var state;
state = document.practiceForm.txtState.value;
console.log(state);
var zip;
zip = document.practiceForm.txtZip.value;
console.log(zip);
var purchase = document.getElementById("txtPurchase").value;
// parse value in Float type data.
var qty = parseFloat(document.getElementById("quantity").value);
// USE == for comparison
if (purchase == "Gameboy") {
var gameboyPrice = 25;
var gameboyTotal = gameboyPrice * qty;
alert("total: $" + gameboyTotal);
} else if (purchase == "DSI") {
var dsiPrice = 50;
var dsiTotal = dsiPrice * qty;
alert("total: $" + dsiTotal);
} else if (purchase == "WII") {
var wiiPrice = 75;
var wiiTotal = wiiPrice * qty;
alert("total: $" + wiiTotal);
}
}
</script>
<form name="practiceForm">
<p>First Name: <input type="text" name="txtFirstName"></p>
<p>Last Name: <input type="text" name="txtLastName"></p>
<p>Street Address: <input type="text" name="txtStreetAddress"></p>
<p>City: <input type="text" name="txtCity"></p>
<p>State: <input type="text" name="txtState"></p>
<p>Zip: <input type="text" name="txtZip"></p>
<p>What do you want to purchase today?:
<select id="txtPurchase">
<option value="Gameboy">Gameboy $25 each</option>
<option value="DSI">DSI $50 each</option>
<option value="WII">Wii $75 each</option>
</select>
</p>
<p>How much would you like to buy?: <input type="number" id="quantity"></p>
<p><input type="button" value="Go!" name="btnSubmit" onclick="ordering()">
</p>
</form>
</body>
</html>

How to set paragraph to textbox text

Let us say I have an HTML form, with two textboxes, I want to add the two numbers in the two textboxes and display the result in a paragraph. How can I do that?
Change paragraph according to textbox is what I can't find!
Very simple:
document.getElementById('sum').onsubmit = add;
function add(e) {
e.preventDefault();
var num1 = document.getElementById('num1').value;
var num2 = document.getElementById('num2').value;
var result = 'Result: ' + String(parseInt(num1) + parseInt(num2));
var p = document.getElementById('result');
p.innerHTML = result;
}
<form id="sum">
<label for="num1">First number:</label>
<br />
<input type="text" id="num1" />
<br />
<label for="num1">Second number:</label>
<br />
<input type="text" id="num2" />
<br />
<input type="submit" value="Add" />
</form>
<p id="result">Result:</p>
In the html we have a form with 3 inputs, 2 are type text and one is type submit. and also a paragraph.
In the javascript we assign to the form's onsumbit event the function add(), in the function we prevent the default so the form wont refresh the page, then we get the 2 values that were inputed, create a string that would contain the sum of those values and set the paragraph's innerHTML to it.
Create a calculator function and then you can fire it on keyup or you can assign it to a button if you'd like.
function calcTotal(){
var inputs = document.getElementsByTagName('input'),
result = 0;
for(var i=0;i<inputs.length;i++){
if(parseInt(inputs[i].value))
result += parseInt(inputs[i].value);
}
document.getElementById('total').innerHTML = 'Total: ' + result;
}
<form>
<input onkeyup="calcTotal()" type="text" />
<input onkeyup="calcTotal()" type="text" />
</form>
<p id="total"></p>
follow bellow JS code:
<html>
<head>
<title>Sum Two Number</title>
<script language="javascript">
function addNumbers()
{
var val1 = parseInt(document.getElementById("value1").value);
var val2 = parseInt(document.getElementById("value2").value);
if(val1 !== "" && val2 !== "") {
var result = val1 + val2;
document.getElementById('result').innerHTML = result;
}
}
</script>
</head>
<body>
value1 = <input type="text" id="value1" name="value1" value="0" onkeyup="javascript:addNumbers()"/>
value2 = <input type="text" id="value2" name="value2" value="0" onkeyup="javascript:addNumbers()"/>
<p>Answer = <span id="result"></span></p>
</body>
</html>
In this example, you have a form with 2 input. When you press on a button, the value of those 2 input is added inside a paragraph.
Hope this help.
function addInputContentToParagraph() {
var txtValue1 = document.getElementById('textbox1').value;
var txtValue2 = document.getElementById('textbox2').value;
document.getElementById('para').innerHTML = txtValue1 + ' ' + txtValue2;
}
a {
cursor:pointer;
border:1px solid #333;
padding:4px;
margin:10px;
display:inline-block;
}
<form id="myForm" name="myForm">
<input type="text" name="textbox1" id="textbox1" value="1">
<input type="text" name="textbox2" id="textbox2" value="2">
</form>
<a onclick="addInputContentToParagraph();">Add Input Values to Paragraph</a>
<p id="para"></p>

Beginner Javascript Advice

I'm new to Javascript and I can't understand why my code is not printing. I take in user input and it is supposed to print out to the textbox; can anyone help?
Forgive my ignorance, I'm a complete newbie with this.
Here's my code:
var $ = function(){
return document.getElementById(arguments[0]);
}
var protoStudent = {
college: "Athlone Institute of Technology",
course: "BSc (Hons) Software Design (Cloud computing)"
}
var createStudent = function(id, name, age){
var student = object.create(protoStudent);
student.id = id;
student.name = name;
student.age = age;
student.showDetails = function(){
return this.id + "\t" + this.name + "\t" + this.age + "\n";
}
return student;
}
var studentArray = [];
var addStudent = function(){
var id = $("studentID"). value;
var name = $("studentName").value;
var age = $("studentAge").value;
student = new createStudent(id, name, age);
studentArray[studentArray.length] = student;
showStudent();
}
var showStudent = function(){
var string = "ID" + "\t" + "Name" + "\t" + "Age" + "\n";
for (var i in studentArray){
string += studentArray[i].showDetails();
}
$("output").value = string;
}
window.onload = function(){
$("add").onclick = addStudent;
}
The html is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Student Register</title>
<link rel="stylesheet" type="text/css" href="StudentRegister.css" />
<script type="text/javascript" src="StudentRegister.js"></script>
<script type="text/javascript" src="shortcuts.js"></script>
</head>
<body>
<div id="content">
<h1>Student Register</h1>
<label for="studentID">Student ID:</label>
<input type="text"
id="studentID"
value="enter student ID here"
onfocus="this.value=''" /><br />
<label for="studentName">Student name:</label>
<input type="text"
id="studentName"
value="enter student name here"
onfocus="this.value=''" /><br />
<label for="studentAge">Student age:</label>
<input type="text"
id="studentAge"
value="enter student age here"
onfocus="this.value=''" /><br />
<br />
<label> </label>
<input type="button"
id="add"
value="Add" /><br />
<textarea id="output" rows="10" cols="60"></textarea>
</div>
</body>
</html>
When I tested your code the browser immediatly gave me this error:
Uncaught ReferenceError: object is not defined. test.php Line 15
Looking at line 15, you have:
var student = object.create(protoStudent);
However, as a case sensitive language you need:
var student = Object.create(protoStudent);
Javascript does not recognize your call to 'object' because only 'Object' is recognized as having the create method.
I tested, and this was working for me.
EDIT: On further reflection, you should check out jQuery so you don't have to declare $ for yourself.

Replace innerhtml on form submit with javascript

I want to have a form that asks the user their name, then welcomes them to the website with that name without redirecting to a different page or reloading. So basically replace a form with "Welcome NAME" after submit is clicked.
My code:
<div id="welcomeText">
<form onsubmit="changeText()" method="post">
Name: <input type="text" name="fname">
<input type="submit">
</form>
</div>
<script>
function changeText() {
var name = document.getElementById(welcomeForm).fname.value;
var welcome = "Welcome, " + name;
document.getElementById("welcomeText").innerHTML = welcome;
}
</script>
You need to give a name to the form before trying to access it, something like this:
//create the name attribute for the form
<form onsubmit="changeText()" method="post" name="myForm">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<script>
function changeText() {
//access myForm using document object
var name = document.name.fname.value;
var welcome = "Welcome, " + name;
document.getElementById("welcomeText").innerHTML = welcome;
}
</script>
<div id="welcomeText">
<form onsubmit="changeText()" method="post" id="welcomeForm">
Name: <input type="text" name="fname">
<input type="submit">
</form>
</div>
<script>
function changeText() {
var name = document.getElementById("welcomeForm").fname.value;
var welcome = "Welcome, " + name;
document.getElementById("welcomeText").innerHTML = welcome;
}
</script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div id="welcomeText">
Name: <input type="text" name="fname" id="name">
<input id="submit" type="submit" onclick="changeText()" onsubmit="changeText()">
</div>
<script>
function changeText() {
var name = document.getElementById("name").value;
var welcome = "Welcome, " + name;
document.getElementById("welcomeText").innerHTML = welcome;
document.getElementById("name").style.display = "none";
document.getElementById("submit").style.display = "none";
}
</script>
</body>
</html>
Try this it will display "welcome user" and also make button and input disappear. In this case you don't even need a form. You can access the name directly from the input without ever submitting the form.
Here we are:
<div id="welcomeText">
<form id="myform" method="post">
Name: <input type="text" name="fname">
<input type="submit">
</form>
</div>
<script>
var form = document.getElementById("myform");
form.addEventListener('submit', function (e) {
e.preventDefault(); // This will prevent submitting the form
var name = form.fname.value;
var welcome = "Welcome, " + name;
document.getElementById("welcomeText").innerHTML = welcome;
});
</script>

How to show input (name + value) in textarea?

I'm working on this project where I need to have the value of a textarea change when one of the input values in the same form changes.
HTML:
<form id="form" action="" method="">
<textarea readonly class="overview"></textarea>
<input type="text" class="add" name="product1" />
<input type="text" class="add" name="product2" />
<input type="text" class="add" name="product3" />
<input type="text" class="add" name="product4" />
</form>
The customer is allowed to change the input.class.
The textarea-value should change whenever one of the inputs changes.
The textarea should show something like:
3 x product1
1 x product3
4 x product4
Anybody got an idea?
Thanks in advance,
Joel
<textarea readonly class="overview" id="mytxtarea"></textarea>
$("#product1").blur(function(){
if($("#product1").val()!='')
{
$("#mytxtarea").val('test value');
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Test</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#form .add').on('keyup', function(){
console.log('test');
var string1 = $('#form .product1').val() + ' x product1\n';
var string2 = $('#form .product2').val() + ' x product2\n';
var string3 = $('#form .product3').val() + ' x product3\n';
var string4 = $('#form .product4').val() + ' x product4';
$('#form textarea').val(string1 + string2 + string3 + string4);
});
});
</script>
</head>
<body>
<form id="form" action="" method="">
<textarea readonly class="overview"></textarea>
<input type="text" class="add product1" name="product1" />
<input type="text" class="add product2" name="product2" />
<input type="text" class="add product3" name="product3" />
<input type="text" class="add product4" name="product4" />
</form>
</body>
</html>
$(".add").keyup(function () {
var app=""
$(".add").each(function () {
if( $(this).val() ) {
var value=$(this).val();
var name=$(this).attr('name');
app +=value+"*"+name+ "\n" ;
}
});
$(".overview").text(app);
});
Watch this.
Hope this will give you some solution.
This will do what you want...
$("input.add").keyup(function() {
var msg = "";
$("input.add").each( function() {
if( $(this).val() ) {
msg += $(this).val() + "x " + $(this).attr("name") + "\n";
}
});
$("textarea.overview").text(msg)
});
I used this with your HTML here: http://jsfiddle.net/XYXpp/
$('input').keyup(function () {
var inputedValue = $(this).val();
var name = $(this).attr('name');
$(".overview").text(inputedValue+name);
});
var fd = new FormData()
fd.append('csrfmiddlewaretoken', document.getElementsByName('csrfmiddlewaretoken')[0].value)
fd.append('field_name', $("input[name='field_name']").serialize())
will return
['field_name=9&field_name=15&field_name=10']
you will then have to parse the info in your view

Categories