Submiting Javascript variable to PHP via HTML Form - javascript

I have these below codes which give user option to reserve a seat according to their choice. These 3 mentioned below are difficulties that I am facing I need help.
To send the total value of a variable named total from Javascript to PHP
To send the total number of selected seats which are being hold by a variable called results from Javascript to PHP
How to make a Reserve Now button inactive if a user did not select any seat from checkbox.
These below are my codes.
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Seat(s)</title>
</head>
<body>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (isset($_POST['submit'])) { //Seat Reserve
require 'action_page.php';
}
elseif (isset($_POST[''])) { //Cancel
require 'mypage.php';
}
}
//
$parameter = "this is a php variable";
echo "var myval = foo(" . parameter . ");";
?>
?>
<h2>Please choose a seat to book</h2>
<form action="index.php" method="post">
<input type="checkbox" name="vehicle" id="A1" value="100">$100<br>
<input type="checkbox" name="vehicle" id="A2" value="65"> $65<br>
<input type="checkbox" name="vehicle" id="A3" value="55"> $55<br>
<input type="checkbox" name="vehicle" id="A4" value="50"> $50<br>
<p id="demo">
Selected Seat(s)
<br>
<span id="selected-seats"></span> <!-- container for selected seats -->
<br>
Total: <span id="total-container"></span> USD
<button type="submit" class="btn btn-primary" name="submit">Reserve Now</button>
</p>
</form>
<script>
const selections = {};
const inputElems = document.getElementsByTagName("input");
const totalElem = document.getElementById("total-container");
const seatsElem = document.getElementById("selected-seats");
for (let i = 0; i < inputElems.length; i++) {
if (inputElems[i].type === "checkbox") {
inputElems[i].addEventListener("click", displayCheck);
}
}
function displayCheck(e) {
if (e.target.checked) {
selections[e.target.id] = {
id: e.target.id,
value: e.target.value
};
}
else {
delete selections[e.target.id];
}
const result = [];
let total = 0;
for (const key in selections) {
result.push(selections[key].id);
total += parseInt(selections[key].value);
}
totalElem.innerText = total;
seatsElem.innerHTML = result.join(",");
//window.alert(result); //Hold Number of Seats Selected.
//window.alert(total); //Hold Total Cost of Selected Seats.
}
var myval = foo("this is a php variable"); // I tried to take this value and output it but it didn't work out.
$.ajax({
type: 'POST',
url: 'action_page.php',
data: {'variable': total},
});
</script>
</body>
</html>
action_page.php
<html>
<head>
<title>Seats Feedback</title>
</head>
<body>
<?php
echo "<br>";
$myval = $_POST['variable'];
print_r($myval);
?>
Looking forward to hear from you guys.

When you're not doing AJAX, posting data to a PHP script the old fashioned way is a matter of:
setting the action attribute on a <form> element to point to the destination PHP script URL
ensuring your form's <input> elements contain all of the data you want to post
adding a submit button to the form
For step 1, currently, your form says to send the post request to itself. This is totally fine (you can use a <?php block ?> like you're doing to determine whether to show a success confirmation or a blank form depending on the contents of $_POST, but I'm guessing your intention is to ultimately send the data over to action_page.php. I made that the action target and removed all of the PHP from your index.
As for step 2, your total isn't currently in an <input> element and won't be posted. I created an invisible total element for this purpose: <input type="hidden" name="total" id="hidden-total" value="0"> and added a couple lines to the script to retrieve this element and set its value whenever your total is recalculated. You could combine the two total elements and style one to look and be non-editable (exercise for the reader).
Another problem relating to step 2 is that you have four different elements with the name vehicle. Only one of these name/value pairs will be posted, so I updated these elements to use unique names so they'll all be sent.
Step 3, making sure you have a submit button, you've already done successfully.
To verify it's working, you can var_dump($_POST) on the receiving PHP script to see the results of the post request or retrieve a specific value by name with e.g. $_POST['total']. At this point, your PHP script can go ahead and parse/validate/sanitize the post data, render proper response output, do a redirect, and/or do whatever else needs to be done, such as writing to a database.
Here's the full code:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Seat(s)</title>
</head>
<body>
<h2>Please choose a seat to book</h2>
<form action="action_page.php" method="post">
<input type="checkbox" name="vehicle-a1" id="A1" value="100">$100<br>
<input type="checkbox" name="vehicle-a2" id="A2" value="65"> $65<br>
<input type="checkbox" name="vehicle-a3" id="A3" value="55"> $55<br>
<input type="checkbox" name="vehicle-a4" id="A4" value="50"> $50<br>
<input type="hidden" name="total" id="hidden-total" value="0">
<p id="demo">
Selected Seat(s)
<br>
<span id="selected-seats"></span> <!-- container for selected seats -->
<br>
Total: <span id="total-container"></span> USD
<button type="submit" class="btn btn-primary" name="submit">Reserve Now</button>
</p>
</form>
<script>
const selections = {};
const inputElems = document.getElementsByTagName("input");
const totalElem = document.getElementById("total-container");
const hiddenTotalElem = document.getElementById("hidden-total");
const seatsElem = document.getElementById("selected-seats");
for (let i = 0; i < inputElems.length; i++) {
if (inputElems[i].type === "checkbox") {
inputElems[i].addEventListener("click", displayCheck);
}
}
function displayCheck(e) {
if (e.target.checked) {
selections[e.target.id] = {
id: e.target.id,
value: e.target.value
};
}
else {
delete selections[e.target.id];
}
const result = [];
let total = 0;
for (const key in selections) {
result.push(selections[key].id);
total += parseInt(selections[key].value);
}
totalElem.innerText = total;
hiddenTotalElem.value = total;
seatsElem.innerHTML = result.join(",");
}
</script>
</body>
</html>
action_page.php
<!DCOTYPE html>
<html lang="en">
<head>
<title>Seats Feedback</title>
</head>
<body>
<?php
echo "<pre style='font-size: 1.5em;'>"; // format debug post dump
var_dump($_POST);
?>
</body>
</html>
Sample output
array(5) {
["vehicle-a1"]=>
string(3) "100"
["vehicle-a3"]=>
string(2) "55"
["vehicle-a4"]=>
string(2) "50"
["total"]=>
string(3) "205"
["submit"]=>
string(0) ""
}
As before, this isn't an industrial strength example and there is plenty of room for improvement, but hopefully it does communicate the basic idea.

Related

How can I collect data from multiple HTML checkboxes and input that data into a google sheet?

I am continuing work on a previous project: Google Sheet Data in a Sidebar
Now, I would like to retrieve the items that have been checked in the sidebar and return that data to the Code.gs file and ultimately the Google Sheet (see code below). Can you offer suggestions on how to do this?
Below, I am trying to add the checked items to the "students" array. I would then like the "Submit Early Release" button to send the "students" array to the Code.gs file. However, I am unsure how to push the checked items to the array properly.
Page.html
> <!DOCTYPE html>
><html>
> <head>
> <base target="_top">
> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
> </head>
> <body>
> <script>
> function addStudents(studentList){
> $('#rangeResult').text(studentList);
>
> document.write(new Date().toLocaleDateString());
>
> var students = [];
> for (var i = 0; i < studentList.length; i++) {
> document.write('<br><input type="checkbox" name="studentList[i]" id="i" value="i">'+ studentList[i]);
> }
> document.write('<br><input type="button" value="Submit Early Release" onclick="google.script.host.close()" />');
> document.write('<input type="button" value="Close" onclick="google.script.host.close()" />');
> };
>
> google.script.run.withSuccessHandler(addStudents).earlyReleaseList();
> </script>
> </body>
></html>
Thank you for your help!
Update
Madhav, thank you for your suggestions. I've adapted your code to fit my scenario, but I'm still having trouble getting the array data back to the spreadsheet. Specifically, when I click the "Submit Early Release" button the sidebar closes but no data is written into the specified cell. Would you mind taking a look?
Page.html
Added another "src=" line for jquery - not sure if this is needed???
Added "collectNames" function to get checked names and send them back
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<script>
function addStudents(studentList){
$('#rangeResult').text(studentList);
document.write(new Date().toLocaleDateString());
//var students = [];
for (var i = 0; i < studentList.length; i++) {
document.write('<br><input type="checkbox" class="special" name='+ studentList[i]+ 'id="i" value="i">'+ studentList[i]);
}
document.write('<br><input type="button" value="Submit Early Release" onclick="collectNames()" />');
document.write('<input type="button" value="Close" onclick="google.script.host.close()" />');
};
function collectNames(){
var students = [];
var checkboxes=document.getElementsByClassName("special"); //get all checkboxes
for(var i = 0; i < checkboxes.length; i++){
if(checkboxes[i].checked){
students.push(checkboxes[i].getAttribute("name")); //if checked then push to array the value
}
}
//now send the finalarray to the destination
google.script.run.releasedStudents(students);
google.script.host.close();
};
google.script.run.withSuccessHandler(addStudents).earlyReleaseList();
</script>
</body>
</html>
Code.gs
function releasedStudents(values) {
var doc = SpreadsheetApp.openById("1OF6Y1CTU9dkIgd1P-nw-5f2lqHSS5cGZytndwzJhw-o");
var ss = SpreadsheetApp.getActiveSpreadsheet();
var cell = ss.getRange('V20').getValue();
cell.setValue(values);
}
If you want to push checked items into the array, then the first thing you will need to ensure is that each checkbox carries the value it represents in some form or the other. Your code does attempt to do that but when you write
document.write('<br><input type="checkbox" name="studentList[i]" id="i" value="i">'+ studentList[i]);
the name attribute of each checkbox is always the same because it is a constant string ("studentList[i]") and not the value from the array, so it should be replaced with :
document.write('<br><input type="checkbox" class="special"name='+studentList[i]+ ' id="i" value="i">'+ studentList[i]);
Once we are done with the input , we should be able to collect values from the checked boxes only ..one way to do that is to assign a class to all the checkboxes so that they can later be accessed via getElementsByClassName() function.
Once obtained, the value attribute of only those checkboxes should be pushed to the array which have the checked property as true.
A slightly different code demonstrating this is :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button id="clickthis">Click this</button>
</body>
<script>
var studentList=["nevil","ron","draco","harry"];
var finalarray=[];
function runmyfun(){
var checkboxes=document.getElementsByClassName("special"); //get all checkboxes
for(var i=0;i<checkboxes.length;i++){
if(checkboxes[i].checked){
finalarray.push(checkboxes[i].getAttribute("name")); //if checked then push to array the value
}
}
//now send the finalarray to the destination
}
document.getElementById("clickthis").onclick=function(){
document.write(new Date().toLocaleDateString());
for (var i = 0; i < studentList.length; i++) {
document.write('<br><input type="checkbox" class="special"name='+studentList[i]+ ' id="i" value="i">'+ studentList[i]); //concat properly
}
document.write('<br><input type="button" value="Submit Early Release" onclick="runmyfun()" />');
document.write('<input type="button" value="Close" onclick="google.script.host.close()" />');
};
</script>
</html>
I hope this is what you were looking for and not something else.

How to associate dynamically added input fields to parent element/id?

I design a user database system using bootstrap and jquery. The problem is, whenever a button is press, it will append an additional field for user to key in.
let's say the the array name for the first array of the field is ref_title[0]
after the append button is press, another text field will appear with the same attribute but the array value will be ref_title[1].
however on the code itself, it will only show ref_title[]. This is ok, since any new field will keep adding on to the array ref_title[]. Am i right?
next when save changes button is clicked, i will direct the data to js using onclick="newdata('<?php echo $row['drug_id']; ?>')"
'drug_id' is a unique number, for example 1, 2 or 3.
when i inspect the input field for the first box is
<input class="form-control" id="ref_title3" name="ref_title[]" placeholder="Reference Title" type="text">
however on the second box(after the append button is press and additional box appeared)
<input class="form-control" id="ref_title" name="ref_title[]" placeholder="Reference Title" type="text">
Take a look at the id="ref_title". The value 3 is not echo out.
HTML:
<input type="text" class="form-control" id="ref_title<?php echo $row['drug_id'];?>" name="ref_title[]" placeholder="Reference Title">
<button type="button" onclick="newdata('<?php echo $row['drug_id']; ?>')" class="btn btn-primary" data-dismiss="modal">Save changes</button>
JS:
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" class="form-control" id="ref_title<?php echo $row['drug_id'];?>" name="ref_title[]" placeholder="Reference Title"/></div>">Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
Onlick
function newdata(str){
var ref = $('#ref_title'+str).val(); // !!Only can read the first array
var datas="&ref="+ref;
$.ajax({
type: "POST",
url: "update.php",
data: datas
}).done(function( data ) {
$('#info').html(data);
viewdata();
});
};
Not exactly an answer to your question, but a suggestion on what you could do.
Prerequisite: test.php
<pre><?php var_export($_POST); ?></pre>
When you give input controls a name containing [...] php will treat the data as if it were arrays. E.g.
<!DOCTYPE html>
<html>
<head>
<title>...</title>
<meta charset="utf-8" />
</head>
<body>
<form method="post" action="test.php">
<input type="hidden" name="foo[a]" value="a" />
<input type="hidden" name="foo[b]" value="b" />
<input type="hidden" name="foo[bar][]" value="bar1" />
<input type="hidden" name="foo[bar][]" value="bar2" />
<input type="hidden" name="foo[bar][]" value="bar3" />
<div>
<input type="submit" />
</div>
</form>
</body>
</html>
the ouput of test.php will be
<pre>array (
'foo' =>
array (
'a' => 'a',
'b' => 'b',
'bar' =>
array (
0 => 'bar1',
1 => 'bar2',
2 => 'bar3',
),
),
)</pre>
i.e. the names
name="foo[a]"
name="foo[b]"
name="foo[bar][]"
name="foo[bar][]"
name="foo[bar][]"
caused php to build the _POST array like
$_POST = array();
$_POST['foo']['a'] = 'a';
$_POST['foo']['b'] = 'b';
// $_POST['foo'][bar] = array()
$_POST['foo']['bar'][] = 'bar1';
$_POST['foo']['bar'][] = 'bar2';
$_POST['foo']['bar'][] = 'bar3';
Now I suggest that you build the names for the input controls like this:
[drugs][145][add][]
telling hte php script that it is supposed to work on drug items, which one (145), that it should add something plus the [] so you can add an (virtually) arbitrary amount of items.
So a POST body like
drugs[145][add][]=drug145.1&drugs[145][add][]=drug145.2&drugs[22][add][]=drug22.1
(yeah, yeah, the encoding is off....)
would lead to
_POST==$_POST = array(
'drugs' = >array(
'145' => array(
'add' => array(
'drug145.1',
'drug145.2'
),
'22' => array(
'add' => 'drug22.1'
)
)
);
telling your php script to add/append the two descriptions drug145.1 and drug145.2 to the item 145 and drug22.1 to the item 22.
And here's an example how you can do this with html/javascript/jquery
<!DOCTYPE html>
<html>
<head>
<title>...</title>
<meta charset="utf-8" />
<style type="text/css">
.adddrugdesc {
margin-left: 1em;
cursor: pointer;
background-color: Cornsilk;
border: 1px solid silver;
}
</style>
</head>
<body>
<form method="post" action="test.php">
<div class="druglist">
<!-- note the drugid as an data-* attribute, see e.g. https://developer.mozilla.org/en/docs/Web/Guide/HTML/Using_data_attributes
Your php script is supposed to output this id when serving the html document
-->
<fieldset><legend data-drugid="3">Drug A</legend></fieldset>
<fieldset><legend data-drugid="7">Drug B</legend></fieldset>
<fieldset><legend data-drugid="145">Drug C</legend></fieldset>
<fieldset><legend data-drugid="22">Drug D</legend></fieldset>
</div>
<input type="submit" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
var dl = $(".druglist");
// add some kind of edit/add button to each fieldset/legend
dl.find("fieldset legend").each(function(x) {
$(this).append('<span class="adddrugdesc">add description</span>');
});
// add an event handler for all edit/add buttons
dl.on('click', '.adddrugdesc', function(e) {
var me = $(this); // this will be the span element the usr clicked on
var legend = me.parent('legend'); // this will be the legend element in which the span is located
var fset = legend.parent('fieldset'); // same as with legend
var drugid = legend.data()['drugid']; // access the data-* attribute of the element via data() and pick the element "drugid"
var newinput = $('<input type="text" />');
newinput.attr("name", "drugs["+drugid+"][add][]");
fset.append(newinput);
});
});
</script>
</body>
</html>
(It's a bit verbose to keep it "understandable". And ...it's only an example. Some things might be a bit prettier, more robust et al)

Javascript: Displaying output dependent on which checkedboxes pressed?

I am creating a web app that will take 2 sets of user input, i.e. Age and Weight and display an outcome dependent on what box is ticked on each.
What is the best way to do this?
I.e. if one age and weight is selected I wish to display one value, but if a different combo is selected I wish to display another?
I ask this as I know it can be done using multiple if statements, but I assume there is a better way.
Current Code:
<!DOCTYPE html>
<html>
<body>
<h1>Health Calculator</h1>
<p>Select age</p>
<form action="age.asp" method="get">
<input type="checkbox" name="Age" value="under25"> Under 25<br>
<input type="checkbox" name="Age" value="over25"> Over 25<br>
</form>
<p>Select Weight</p>
<form action="weight.asp" method="get">
<input type="checkbox" name="Probability" value="under80"> Under 80kg<br>
<input type="checkbox" name="Probability" value="over80"> Over 80kg<br>
</form>
<br>
<button onclick= "analyseHealth"> Analyse health </button> <br>
<script>
function analyseHealth(age, weight){
//LOGIC RELATING TO CHECK BOXES
}
</script>
</body>
</html>
This is not finished but I think you can guess the rest.
http://codepen.io/anon/pen/RPpjBm
function analyseHealth()
{
var ages = document.getElementsByName('Age');
var probs = document.getElementsByName('Probability');
var age = undefined;
for(var i = 0; i < ages.length; i++)
{
if(ages[i].checked)
{
age = ages[i].value;
}
}
var probability = undefined;
for(var i = 0; i < probs.length; i++)
{
if(probs[i].checked)
{
probability = probs[i].value;
}
}
switch(age){
case 'under80': break;
}
}
Better than if might be switch. First you get the checked radio buttons which might be the better choice here.

Radio Buttons not appearing as they should

I had to edit existing HTML (change title and variables) and run it through Firebug. My radio buttons are boxes (or not showing at all) and I don't know why. I've attached a screenshot of both the HTML code and the Firebug output. I used an online converter to convert the HTML to JavaScript. I am new to JavaScript and am having a hard time getting a handle on this. Any help would be appreciated!
HTML Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD><TITLE>Radio Buttons</TITLE>
<META content=3D"text/html; charset=3Dwindows-1252" =
http-equiv=3DContent-Type>
<SCRIPT type=3Dtext/javascript>
function pick_a_business_card(){
var base_cost =3D get_business_card_value();
alert(base_cost);
}
function get_business_card_value(){
var radio_buttons =3D document.getElementsByName('business card');
for (var i =3D 0, length =3D radio_buttons.length; i < length; i++) {
=09
if (radio_buttons[i].checked) {
return radio_buttons[i].value;
}
}
}
</SCRIPT>
<META name=3DGENERATOR content=3D"MSHTML 8.00.7601.18129"></HEAD>
<BODY>
<FORM id=3Dbusiness_card_addons_calculation_form method=3Dpost action=3D#>
<H2>Radio Buttons</H2>
<P><STRONG>Pick a Business Card:</STRONG><BR><BR><INPUT id=3Dvertical value=3Dvertical
=
type=3Dradio=20
name=3Dcolor> <LABEL for=3Dvertical>Vertical</LABEL> <BR><INPUT id=3Dhorizontal =
value=3Dhorizontal=20
type=3Dradio name=3Dcolor> <LABEL for=3Dhorizontal>Horizontal</LABEL> <BR><INPUT =
id=3DFoldover=20
value=3Dfoldover type=3Dradio name=3Dcolor> <LABEL for=3DFoldover>Foldover</LABEL> =
</P>
<P><INPUT onclick=3Dpick_a_business_card() value=3D" Submit " =
type=3Dbutton></P>
</FORM>
</BODY>
</HTML>
It appears some things were encoded improperly in your conversion.
I cleaned up your code a bit here which should help get you started
Here is the full HTML:
<html>
<head>
<script>
function pick_a_business_card(){
var base_cost = get_business_card_value();
alert(base_cost);
}
function get_business_card_value(){
var radio_buttons = document.getElementsByName('color');
for (var i = 0, length = radio_buttons.length; i < length; i++) {
if (radio_buttons[i].checked) {
return radio_buttons[i].value;
}
}
}
</script>
</head>
<body>
<FORM id=business_card_addons_calculation_form method=post action=#>
<H2>Radio Buttons</H2>
<P><STRONG>Pick a Business Card:</STRONG><BR><BR><INPUT id=vertical value=vertical
type=radio
name=color> <LABEL for=vertical>Vertical</LABEL> <BR><INPUT id=horizontal
value=horizontal
type=radio name=color> <LABEL for=horizontal>Horizontal</LABEL> <BR><INPUT
id=Foldover
value=foldover type=radio name=color> <LABEL for=Foldover>Foldover</LABEL>
</P>
<P><INPUT onclick=pick_a_business_card() value=" Submit "
type=button></P></FORM>
</body>
</html>
Additionally, I'd recommend putting quotes around your HTML attributes.

having trouble with javascript

Beginer to javasctipt. I am trying to write a simple calculation that will display some text if the time since oil change is past 6 months, the amount of oil left in the car is less then it started and finally display if everything is ok.
Thanks for the help
JavaScript
function oil(){
var start = document.oil.start.value;
var lastOilChange = document.oil.time.value;
var totalOil = document.oil.amount.value;
var aa = "you need to change the oil";
if( lastOilChange > 6 || start < totalOil){
document.oil.result.write(aa);
}else{
document.oil.result.write("Everything Is all good");
}
}
HTML
<form name="oil">
Starting amount of oil
<input type="text" name="start">
Time since oil change
<input type="text" name="time">
Total amount of oil in car now(quarts)
<input type="text" name="amount">
<input type="submit" onclick = oil()>
<input name=result readonly>
</form>
There are a couple of problems with your code
Missing Form close tag
Your controls don't have IDs
missing quotes on the result input
Don't need to use a submit input when you're not submitting to a form. Try button
Not sure what document.oil.result.write(aa); will do. I think the correct process is to get the input using document.getElementById and then set the value of the control
I will try to answer your question with the least number of line changes. This is not the optimal answer. Comments have been added to help you understand required changes. Your HTML and JavaScript are invalid, so it was a surprise to me how they both ran on Chrome.
<!doctype>
<html>
<head>
<title>Personal</title>
<meta charset="utf-8">
<script type="text/javascript">
function _oil(){ // oil() conflicts with your form's name
var start = document.oil.start.value;
var lastOilChange = document.oil.time.value;
var totalOil = document.oil.amount.value;
var aa = "you need to change the oil";
if( lastOilChange > 6 || start < totalOil){
document.write(aa); // you can't .write() to an element
}else{
document.write("Everything Is all good");
}
window.event.preventDefault(); // so your window does not load the same page when you submit
return false;
}
</script>
<style>
form input {
display: block;
}
</style>
</head>
<body>
<form name="oil">
Starting amount of oil
<input type="text" name="start">
Time since oil change
<input type="text" name="time">
Total amount of oil in car now(quarts)
<input type="text" name="amount">
<input type="submit" onclick ="_oil()"> <!-- you must enclose the onclick attribute, even if both work -->
<input name=result readonly>
</body>
</html>
May be like this:
<!doctype>
<html>
<head>
<title>Personal</title>
<meta charset="utf-8">
<script type="text/javascript">
function oil(){
var start = document.getElementsByName("start")[0].value;
var lastOilChange = document.getElementsByName("time")[0].value;
var totalOil = document.getElementsByName("amount")[0].value;
var aa = "you need to change the oil";
if( lastOilChange > 6 || start < totalOil){
document.getElementsByName("result")[0].value = aa;
}else{
document.getElementsByName("result")[0].value = "Everything Is all good";
}
}
</script>
<style>
form input {
display: block;
}
</style>
</head>
<body>
<form name="thisform">
Starting amount of oil
<input type="text" name="start">
Time since oil change
<input type="text" name="time">
Total amount of oil in car now(quarts)
<input type="text" name="amount">
<input type="button" value="go" onclick = oil()>
<input name=result readonly>
</form>
</body>
</html>
!!! The form name can not use oil
What you want is to set the value of the form field rather than trying to use write:
if( lastOilChange > 6 || start < totalOil){
document.oil.result.value = aa;
} else {
document.oil.result.value = "Everything Is all good";
}
As pointed out in other answers, though, you also need to prevent the form from trying to submit information to the server and reload the page. There are several ways of doing this (see e.g. JavaScript code to stop form submission). One is to replace the submit button with an ordinary button (<input type="button" value="Calculate" />).
Another is to attach your function to the form as an event handler, and return false at the end of it.
document.oil.onsubmit = function () {
...
return false;
}
(JSFiddle)

Categories