document.write form element value. test java script function - javascript

I am trying to test a java script function the purpose of the function is to get the value of a user selected form element. Specifically a radio button. my goal is to use this function in another function to calculate a price total. But for now, I just want to make sure this function returns the value of the selected radio button.
<html>
<head>
</head>
<body>
<form name="testForm">
<legend>Calculate your square feet</legend>
</br>
<label> What size plants are you starting with ? </label>
</br>
</br>
<input type="radio" name="plantType" value="16"/>Seeds, havn't started yet</label>
</br>
<input type="radio" name="plantType" value="16"/> Seedlings, less than 2ft high</label>
</br>
<input type="radio" name="plantType" value="32"/> Juvenile, 2 - 4ft high</label>
</br>
<input type="radio" name="plantType" value="64"/> Adult, 4ft or higher</label>
</br>
</form>
<script type="text/javascript">
var plant_name = new Array();
plant_name[16] = 16;
plant_name[16] = 16;
plant_name[32] = 32;
plant_name[32] = 64;
function getPlantSize() {
var plantSize = 0;
var theForm = document.testForm;
var selectedPlant = theForm.plantType;
for (var i = 0; i < plantType.length; i++)
{
if (plantType[i].checked)
{
plantSize = plant_name.[selectedPlant[i].value];
break;
}
document.write (plantSize);
}
}
</script>
</body>
</html>

Related

This calculator using form submission to satisfy variables isn't working

I am attempting to make a calculator in order to... well, calculate something. Anyway, I am trying to make 4 variables be set too 4 user inputs by using form submission. However, no matter what I do, I can't get the variables to get set. Help would be appreciated!
<!DOCTYPEhtml>
<html>
<head>
<title>NatHisCalc</title>
</head>
<body>
<h1><center><b><p>Test</p></b></center></h1>
<center><b><p id='output'>loading...</p></b></center>
<center><b><p id='output2'>loading...</p></b></center>
<center><b><p id='output3'>loading...</p></b></center>
<center><b><p id='output4'>loading...</p></b></center>
<form id="a" action="/action_page.php">
Input X <input type="number" name="x"><br><br>
<input type="button" onclick="calc()" value="Submit">
</form>
<form id="a" action="/action_page.php">
Input X <input type="number" name="y"><br><br>
<input type="button" onclick="calc()" value="Submit">
</form>
<form id="a" action="/action_page.php">
Input X <input type="number" name="a"><br><br>
<input type="button" onclick="calc()" value="Submit">
</form>
<form id="a" action="/action_page.php">
Input X <input type="number" name="b"><br><br>
<input type="button" onclick="calc()" value="Submit">
</form>
<script>
function calc() {
var x = document.getElementById("x").submit();
var y = document.getElementById("y").submit();
var a = document.getElementById("a").submit();
var b = document.getElementById("b").submit();
var u = (0.101*(y/100))*(480000*(a/100))
var j = (0.581*(x/100))*(120000*(b/100))
if (x > 150 || x < 50) {
window.alert('Hold on... Those inputs will result in an unreasonable output. You can click ');
}
var preresult = j + u;
if (preresult < 177000) {
document.getElementById('output').innerHTML = 'Test';
} else {
document.getElementById('output').innerHTML = 'Test1';
}
if (u > 179999) {
document.getElementById('output').innerHTML = 'Test2';
}
document.getElementById('output2').innerHTML = 'Test3' + j;
document.getElementById('output3').innerHTML = 'Test4 ' + u;
document.getElementById('output4').innerHTML = 'Test5 ' + preresult;
}
</script>
</body>
</html>
Looked into your code, it seems that you have made things way too much complicated that it should be. First of all, you don't call submit function on the input to get the value of it. If you want to get the value of x then you just access the value property like this document.getElementById("x").value. Secondly, you really don't need four buttons, all you need to do is ONE button that submits the form and adding required on input fields makes the browser not submit the form until all forms are filled. Last of all, id attribute needs to be unique across your page. You have both form and input field as id a which is unacceptable. It will show no error but get you in sorts of trouble. You can see what I did here, where I prevented the form from being submitted upon the button click and simply called the calc function to perform the calculation.
<!DOCTYPEhtml>
<html>
<head>
<title>NatHisCalc</title>
</head>
<body>
<h1><center><b><p>Test</p></b></center></h1>
<center><b><p id='output'>loading...</p></b></center>
<center><b><p id='output2'>loading...</p></b></center>
<center><b><p id='output3'>loading...</p></b></center>
<center><b><p id='output4'>loading...</p></b></center>
<form onsubmit="event.preventDefault(); calc();" action="/action_page.php">
Input X <input type="number" id="x" required><br><br>
Input Y <input type="number" id="y" required><br><br>
Input A <input type="number" id="a" required><br><br>
Input B <input type="number" id="b" required><br><br>
<input type="submit" value="Submit">
</form>
<script>
function calc() {
var x = document.getElementById("x").value;
var y = document.getElementById("y").value;
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
var u = (0.101*(y/100))*(480000*(a/100))
var j = (0.581*(x/100))*(120000*(b/100))
if (x > 150 || x < 50) {
window.alert('Hold on... Those inputs will result in an unreasonable output. You can click ');
}
var preresult = j + u;
if (preresult < 177000) {
document.getElementById('output').innerHTML = 'Test';
} else {
document.getElementById('output').innerHTML = 'Test1';
}
if (u > 179999) {
document.getElementById('output').innerHTML = 'Test2';
}
document.getElementById('output2').innerHTML = 'Test3' + j;
document.getElementById('output3').innerHTML = 'Test4 ' + u;
document.getElementById('output4').innerHTML = 'Test5 ' + preresult;
}
</script>
</body>
</html>

How to count the number of checkboxes checked using an array

I'm trying to get the number of checkBoxes checked with using the information from an array but I keep getting undefined. I have to use an array, a switch, and must be in JavaScript for this project. I can't use any other programming Language.
How can I get my function to correctly add the checked boxes?
I am also not sure on how I could implement a switch into this function.+
Please help, I've been working on this for about 4 hours, searching everywhere to find a helpful answer.
My HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Project</title>
</head>
<body>
<form id="frmCareer" method="get" action="prjFormEvent.js">
<table id="tblCareer">
<th>Directions: Check of the items you think you would enjoy in each section.<br /> Mark as many items that apply.</th>
<tr><td><strong><label id="lblRealistic">
"R" Section</label></strong>
<div id="realisticTotal"></div>
<br />
<input type="checkbox"
name="chkRealistic"
onclick="getRealistic()"
value="chkRealistic1">Repair a car
<br />
<input type="checkbox"
name="chkRealistic"
onclick="getRealistic()"
value="chkRealistic2">Do wood working
<br />
<input type="checkbox"
name="chkRealistic"
onclick="getRealistic()"
value="chkRealistic3">Refinish furniture
<br />
<input type="checkbox"
name="chkRealistic"
onclick="getRealistic()"
value="chkRealistic4">Explore a forest
<br />
</tr></td>
</table><!--End of tblWhichCareer-->
</form><!--End of frmWhichCareer-->
</body>
</html>
My JavaScript
Global Variables
var getCareer = new Array();
getCareer["chkRealistic1"] = 1;
getCareer["chkRealistic2"] = 1;
getCareer["chkRealistic3"] = 1;
getCareer["chkRealistic4"] = 1;
function getRealistic()
{
var rTotal = 0;
var selectedRealistic = document.forms["frmCareer"]["chkRealistic"];
rTotal = getCareer[selectedRealistic.value]
document.getElementById("lblRealistic").innerHTML = rTotal+ "/9 Checked"
}//End of function getRealisticCareer()
You missed the fact that this line
var selectedRealistic = document.forms["frmCareer"]["chkRealistic"];
returns an array of checkboxes with the name chkRealistic (in your example, all four of them).
Instead of assigning the result of the getCareer function to rTotal, you should iterate through the array of HTMLInput in selectedRealistic checking for the .checked property.
var rTotal = 0;
var selectedRealistic = document.forms["frmCareer"]["chkRealistic"];
for (var sel = 0; sel < selectedRealistic.length; sel++)
{
if (selectedRealistic[sel].checked)
rTotal += getCareer[selectedRealistic[sel].value]
}
document.getElementById("lblRealistic").innerHTML = rTotal+ "/9 Checked"
You can check a running example here: http://codepen.io/pabloapa/pen/jPNPNg
Try using:
document.getElementById("lblRealistic").innerHTML = document.querySelectorAll('input[name="chkRealistic"]:checked').length + "/9 Checked";
Try this:
function getRealistic()
{
var rTotal = 0;
for(i=0; i<document.forms[0].chkRealistic.length; i++){
if(document.forms[0].chkRealistic.item(i).checked){
rTotal++;
}
}
document.getElementById("lblRealistic").innerHTML = rTotal+ "/9 Checked"
}
Here try this also on Plunker: http://plnkr.co/edit/085ZtojBgvumktHwQSGf?p=preview
<form id="frmCareer" method="get" action="prjFormEvent.js">
<table id="tblCareer">
<tr>
<th>Directions: Check of the items you think you would enjoy in each section.
<br />Mark as many items that apply.</th>
</tr>
<tr>
<td><strong><label id="lblRealistic">
"R" Section</label></strong>
<div id="realisticTotal"></div>
<br />
<input type="checkbox" name="chkRealistic" onchange="getRealistic(this)" value="chkRealistic1">Repair a car
<br />
<input type="checkbox" name="chkRealistic" onchange="getRealistic(this)" value="chkRealistic2">Do wood working
<br />
<input type="checkbox" name="chkRealistic" onchange="getRealistic(this)" value="chkRealistic3">Refinish furniture
<br />
<input type="checkbox" name="chkRealistic" onchange="getRealistic(this)" value="chkRealistic4">Explore a forest
<br />
</td>
</tr>
</table>
<!--End of tblWhichCareer-->
</form>
<!--End of frmWhichCareer-->
<script language="JavaScript">
var getCareer = new Array();
getCareer["chkRealistic1"] = 0;
getCareer["chkRealistic2"] = 0;
getCareer["chkRealistic3"] = 0;
getCareer["chkRealistic4"] = 0;
function getRealistic(cbox) {
var rTotal = 0;
var key = cbox.value;
getCareer[key] = cbox.checked ? 1 : 0;
for (var key in getCareer) {
rTotal += getCareer[key];
}
document.getElementById("lblRealistic").innerHTML = rTotal + "/9 Checked"
} //End of function getRealisticCareer()
</script>

Cannot update score

I was trying to make a content score as a class assignment.
Assume : (The user sees a URL and then select the checkboxes that are assigned to issues . Each issue is assigned a score in a array.)
Whats working :
Individual checks are registered with their respective scores being displayed
Whats not working :
Can someone help me to update the score ( as the user checks the checkbox or unchecks).
I am assuming in future if i want to increase the issues I will be able to do that since it is in an array. (am i right)
(my week 4 in JS)
//Set up an array with the respective score
var code = new Array();
code["v1"] = 1;
code["v2"] = 2;
code["v3"] = 3;
code["v4"] = 5;
// As the user selects the checkbox I want to keep on adding the score and as the user unchecks I want to recalculate and display.
function getvalueScore() {
var score = 0;
//Get a reference to the form
var theForm = document.forms["contentForm"];
//Get a reference to the score from the "ContentForm"
var contentScore = theForm.elements["contentScore"];
// loop through each check box
for (var i = 0; i < contentScore.length; i++) {
//if the radio button is checked
if (contentScore[i].checked) {
// I want to calculate and keep updating the score
score = code[contentScore[i].value];
}
}
//return score
return score;
}
function calculateTotal() {
//calculation for final score
var scoreCard = getvalueScore();
//display the result
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'block';
divobj.innerHTML = "Your Content Score is " + scoreCard;
}
function hideTotal() {
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'none';
}
<!DOCTYPE html>
<html>
<head>
<title>Content Score</title>
<meta charset="utf-8">
<script src="formcalculations.js"></script>
</head>
<body onload='hideTotal()'>
<div id="wrap">
<form action="" id="contentForm" onsubmit="return false;">
<div>
<div class="cont_order">
Content Score</br>
<label>Please select the issues you see on the page to calculate the content score</label>
</br>
<label class='radiolabel'>
<input type="checkbox" name="contentScore" value="v1" onclick="calculateTotal()" />No content value</label>
<br/>
<label class='radiolabel'>
<input type="checkbox" name="contentScore" value="v2" onclick="calculateTotal()" />Mediocre content value</label>
<br/>
<label class='radiolabel'>
<input type="checkbox" name="contentScore" value="v3" onclick="calculateTotal()" />Obsolete content</label>
<br/>
<label class='radiolabel'>
<input type="checkbox" name="contentScore" value="v4" onclick="calculateTotal()" />Irrelevant content</label>
<br/>
<br/>
<br/>
<div id="totalPrice"></div>
</div>
</div>
</form>
</div>
<!--End of wrap-->
</body>
</html>
In your code you assign last selected checkbox to score variable, so the only thing you need to do is to sum the scores with:
score += code[contentScore[i].value];

EDITED: I'm having issues with a button and its function

-----EDITED-----
The story is not being presented properly, again, due to code error. Need fresh eyes!
function story()
{
//collect the users input data
var transport = "";
var name = document.getElementsByName("name")[0].value
var title = document.getElementsByName("title")[0].value
var noun = document.getElementsByName("noun")[0].value
var num1 = document.getElementsByName("num1")[0].value
var num2 = document.getElementsByName("num2")[0].value
var travelmeasure = document.getElementsByName("measureravel").value
//write new html to the page to display the story
document.write("<h1>"+title+"</h1>");
document.write("<p>Once upon a time,</p>");
document.write("<p>"+name+" was trying to make their way to "+noun+" in a "+transport+".</p>");
document.write("<p>Unfortunately "+name+" didn't realise how far away "+houn+" really was.</p>");
document.write("<p>The assumption was "+num1+" "+measuretravel+" when really is turned out to be "+num2+" "+measuretravel+".</p>");
document.write("<p>Thankfully "+name+" likes to travel.</p>");
document.write("<p>THE END</p>");
}
-----ORIGINAL-----
Before adding the "story" function and the "continue" button, this page was running smoothly. What I am trying to do is have the users input variables be applied to the story I wrote in a new HTML page.
I'm assuming its probably just code error but I can't seem to see it.
<html>
<head>
<title>a4_part4</title>
<script type="text/javascript">
//<![CDATA[
function storytime()
{
//displays alert
alert("Welcome to an Interactive Story Spot.");
}
function confirm()
{
var spaceship = document.getElementsByName("transport")[0].value;
var ducatti = document.getElementsByName("transport")[1].value;
var ferrari = document.getElementsByName("transport")[2].value;
var jet = document.getElementsByName("transport")[3].value;
var train = document.getElementsByName("transport")[4].value;
var transport = "";
var name = document.getElementsByName("name")[0].value
var title = document.getElementsByName("title")[0].value
var noun = document.getElementsByName("noun")[0].value
var num1 = document.getElementsByName("num1")[0].value
var num2 = document.getElementsByName("num2")[0].value
var miles = document.getElementsByName("measuretravel")[0].value
var kms=document.getElementsByName("measuretravel")[1].value;
var travelmeasure = document.getElementsByName("measureravel").value
//determine which mode of transportation was chosen
if (document.getElementsByName("transport")[0].checked)
{
transport = spaceship;
}
else if (document.getElementsByName("transport")[1].checked)
{
transport = ducatti;
}
else if (document.getElementsByName("transport")[2].checked)
{
transport = ferrari;
}
else if (document.getElementsByName("transport")[3].checked)
{
transport = jet;
}
else if (document.getElementsByName("transport")[4].checked)
{
transport = train;
}
//determine which measure of travel was chosen
if (document.getElementsByName("measuretravel")[0].checked)
{
miles = "+num1+" + "+num2+" * 1.60934
measuretravel = miles;
}
else if (document.getElementsByName("measuretravel")[1].checked)
{
measuretravel = kms;
}
//display alert
alert ("Hello, "+name+", your story values are "+title+", "+transport+", "+noun+", "+num1+", "+num2+", and "+measuretravel+" ");
}
function story()
{
//collect the users input data
{
var transport = "";
var name = document.getElementsByName("name")[0].value
var title = document.getElementsByName("title")[0].value
var noun = document.getElementsByName("noun")[0].value
var num1 = document.getElementsByName("num1")[0].value
var num2 = document.getElementsByName("num2")[0].value
var travelmeasure = document.getElementsByName("measureravel").value
//write new html to the page to display the story
document.write("<h1>"+title+"</h1>");
document.write("<p>Once upon a time,</p>");
document.write("<p>"+name+" was trying to make their way to "+noun+" in a "+transport+".</p>");
document.write("<p>Unfortunately "+name+" didn't realise how far away "+houn+" really was.</p>")
document.write("<p> The assumption was "+num1+" "+measuretravel+" when really is turned out to be "+num2+" "+measuretravel+".</p>")
document.write("<p> Thankfully "+name+" likes to travel.<p>")
document.write("<p>THE END</p>");
}
//]]>
</script>
</head>
<body>
<form id="storyform" action="">
<h1>Create Your Own Story</h1>
<p style="font-weight:bold;"> Your Name
<input type="text" name="name" id="name" value="Jane Doe">
</p>
<p style="font-weight:bold;"> Story Title
<input type="text" name="title" id="title" value="Enter Story Title Here">
</p>
<p style="font-weight:bold;">Choose A Mode Of TRANSPORTATION</p>
<input type="radio" name="transport" id="transport" value="spaceship" checked="checked"> Spaceship
<br>
<input type="radio" name="transport" id="transort1" value="ducati"> Ducati
<br>
<input type="radio" name="transport" id="transport2" value="ferrari"> Ferrari
<br>
<input type="radio" name="transport" id="transport3" value="jet"> Jet
<br>
<input type="radio" name="transport" id="transport4" value="train"> Train
<br>
<br>
Enter a NOUN <input type="text" name="noun" id="noun" value="Paris" onclick=""/>
<br>
Enter a NUMBER <input type="text" name="num1" id="num1" value="1" checked="checked" onclick=""/>
<br>
Enter Another NUMBER <input type="text" name="num2" id="num2" value="2" onclick=""/>
<p style="font-weight:bold;">Choose a means of MEASURING TRAVEL</p>
<input type="radio" name="measuretravel" id="measuretravel1" value="miles"> Miles
<br>
<input type="radio" name="measuretravel" id="measuretravel2" value="kms" checked="checked"> Kilometers
<br>
<br>
<br>
<p>Please confirm before you continue<p>
<input type="reset" value="Clear Form">
<input type="button" value="Story Time!" onclick="storytime();">
<input type="button" value="Confirm" onclick="confirm();">
<input type="button" value="Continue" onclick="story();">
</form>
</body>
</html>
it looks like there's a rogue curly brace in your Story function
This is what your function looks like right now
function story()
{
//collect the users input data
{
...
}
It's not even registering your function because you have a syntax error. You can either remove that second { or you can add a } to close it. I would do the former.
You're missing a closing "}". You have a "{" for your story function and another after "//collect the users input data", but only one closing "}"

How to confirm a radio button selection with an alert box

So i have this code:
<html>
<head>
<title>Form</title>
<script type="text/javascript">
function showConfirmationDialog() {
var textbox = document.getElementById('textbox');
var location = document.getElementById('location');
alert('You chosen:'+'\n'+'\n'+'Name: '+textbox.value +'\n'+'Address: ' +location.value+'\n');
}
function formfocus() {
document.getElementById('textbox').focus();
}
window.onload = formfocus;
var option;
</script>
</head>
<body>
Your name:
<input type="text" name="FirstName" id="textbox" <br><br/>
Your Address:
<input type="text" name="address" id="location" <br></br><br></br>
Choose your location:
<form name="Radio" id="destination" action="">
Bristol:
<input type="radio" name="selection" value="bristol" onClick="option=0">
London:
<input type="radio" name="selection" value="london" onClick="option=1">
Birmingham:
<input type="radio" name="selection" value="birmingham" onClick="option=2" />
</form>
<br></br> Click:
<input type="button" value="Submit" onclick="showConfirmationDialog();" /><br></br>
</body>
</html>
... This code basically represents a form for a user to fill in and at the end select one of three option provided via the radio buttons. What I wanted to find out was that how do I get the selection from one radio button which the user will need to select, displayed within the alert box after they press submit.
Something like this...
function getSelRadioValue()
for(i = 0; i< document.forms['Radio'].elements['selection'].length ; i++){
if(document.forms['Radio'].elements['selection'][i].checked == true)
return document.forms['Radio'].elements['selection'][i].value;
}
return null;
}
var selectedRadioValue = getSelRadioValue(); //use this variable in your alert.
if(selectedRadioValue == null)
alert("please select a destination");
else if(confirm("You have selected " + selectedRadioValue))
//deal with success
You need to loop through the selection radios to get the checked value:
var selection = document.Radio.selection;
var selectionResult = "";
for(var i = 0; i < selection.length; i++) {
if(selection[i].checked) {
selectionResult = selection[i].value;
}
}
alert('You chosen:'+'\n'+'\n'+'Name: '+textbox.value +'\n'+'Address: ' +location.value+'\n' + 'Location: '+selectionResult);

Categories