I created this calculator with two pages. The first page contains a registration form, the second page contains the calculator
html for first page :
<!DOCTYPE html>
<html>
<head>
<title>js assigment 1 _ omar azzazy</title>
<link rel="stylesheet" href="css/style.css"/>
</head>
<body>
<div class="container">
<h1>Registration form</h1>
<form action="calc.html">
First Name: <input type="text"/><br><br>
Last Name: <input type="text"/><br>
Gender:
<input id="m" type="radio" name="gender" value="male"/> Male <br>
<input id="f" type="radio" name="gender" value="female"/>Female <br>
<input type="submit" onclick="go()" value="Go to calculator">
</form>
</div>
<script src="js/plugin.js"></script>
</body>
html for second page :
<!DOCTYPE html>
<html>
<head>
<title>js assigment 1 _ omar azzazy</title>
<link rel="stylesheet" href="css/style.css"/>
</head>
<body>
<div class="container">
<h1>calculator</h1>
<input id="operator1" type="number" value=""/>
<select id="operatorx">
<option value="0">+</option>
<option value="1">-</option>
<option value="2">x</option>
<option value="3">/</option>
</select>
<input id="operator2" type="number" value=""/>
<button onclick="calc()">=</button>
<input id="result" type="text" value=""/>
</div>
<script src="js/plugin.js"></script>
</body>
</html>
javascript code:
function plus(a, b) {
return (a + b);
}
function minus(a, b) {
return (a - b);
}
function multiply(a, b) {
return (a * b);
}
function divide(a, b) {
return (a / b);
}
function calc() {
var x = parseFloat( document.getElementById("operator1").value );
var y = document.getElementById("operatorx").value;
var z = parseFloat( document.getElementById("operator2").value );
switch (y) {
case '0':
w = plus(x, z);
break;
case '1':
w = minus(x, z);
break;
case '2':
w = multiply(x, z);
break;
case '3':
w = divide(x, z);
break;
default:
w = "Don't really know..";
}
document.getElementById("result").value = w;
}
I need if the user selected "Male" in radio button the page and calculator buttons will be in colors suitable for Men mood.
If the user selected "Female" the page and calculator buttons will be in colors suitable for Women mood.
You need to first check which was selected using document.getElementById("id").checked = true;
then use the "style" element of javascript to add your styles, or create add and remove as suggested here:
Change an element's class with JavaScript
Related
I'm trying to learn Javascript by making a simple calculator, but somehow the result of the calculation doesn't show up. I'm wondering what's wrong with my code. I've tried many ways to understand the error, but I still don't know why. The calculation works just fine in the console, it's just the output that seems to have the problem.
Can somebody help me?
function calc(){
var a = parseInt(document.querySelector("#value1").value);
var b = parseInt(document.querySelector("#value2").value);
var op = document.querySelector("#operator").value;
var calculate;
if (op == "add") {
calculate = a + b;
} else if (op == "min"){
calculate = a - b;
}else if (op == "div"){
calculate = a / b;
}else if (op == "mul"){
calculate = a * b;
}
console.log(calculate);
document.querySelector("#result").innerHtml = calculate;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="js/main.js">
</script>
</head>
<body>
<form>
Value 1: <input type="text" name="" value="" id="value1">
Value 2: <input id="value2" type="text" name="" value="">
Operator:
<select id="operator" class="" name="">
<option value="add">Add</option>
<option value="min">Min</option>
<option value="div">Div</option>
<option value="mul">Multiply</option>
</select>
<button type="button" onclick="calc()" name="button">Calculate</button>
</form>
<div id="result">
</div>
</body>
</html>
innerHtml is invalid attribute, you need to use innerHTML instead like:
document.querySelector("#result").innerHTML = calculate;
You should be using textContent instead of innerHtml
function calc(){
var a = parseInt(document.querySelector("#value1").value);
var b = parseInt(document.querySelector("#value2").value);
var op = document.querySelector("#operator").value;
var calculate;
if (op == "add") {
calculate = a + b;
} else if (op == "min"){
calculate = a - b;
}else if (op == "div"){
calculate = a / b;
}else if (op == "mul"){
calculate = a * b;
}
console.log(calculate);
document.querySelector("#result").textContent = calculate;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="js/main.js">
</script>
</head>
<body>
<form>
Value 1: <input type="text" name="" value="" id="value1">
Value 2: <input id="value2" type="text" name="" value="">
Operator:
<select id="operator" class="" name="">
<option value="add">Add</option>
<option value="min">Min</option>
<option value="div">Div</option>
<option value="mul">Multiply</option>
</select>
<button type="button" onclick="calc()" name="button">Calculate</button>
</form>
<div id="result">
</div>
</body>
</html>
An "id" should be unique within a page and should not
be used more than once value1 and value2 in doesn't
recognise by documents.querySelector() so instead of
this use
Var a =
parseInt(document.getElementById("value1").value);
var b =
parseInt(document.getElementById("value2").value);
My problem: I can't get to pass the input data from html to js function as its variables and get the appropriate response.
My goal: when the user clics on submit button he receives whatever response the js function provided.
I have two files in the same directory:
- index.html
- index.js
index.js content:
function quEq(a, b, c) {
var delta = (b ** 2) - (4 * a * c);
if (a == 0) {
return "Not a quadratic equation";
};
if (delta < 0) {
return "Complex root! No solution in real numbers";
} else {
var first= (-b + Math.sqrt(delta)) / (2*a);
var second= (-b - Math.sqrt(delta)) / (2*a);
return {first, second};
};
};
index.html content:
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script src="index.js"></script>
<title>Quadratic Equation</title>
</head>
<body>
<div class="container">
<div class="row justify-content-center">
<div class="bg-red-400">
<div class="">
<form>
<div class="form-group">
<label>Enter 'a' value</label>
<input type="number" class="form-control" id="a" placeholder="1">
<label>Enter 'b' value</label>
<input type="number" class="form-control" id="b" placeholder="5">
<label>Enter 'c' value</label>
<input type="number" class="form-control" id="c" placeholder="6">
<button onclick="quEq(document.getElementById('a').nodeValue, document.getElementById('b').value, document.getElementById('c').value)" type="submit" class="btn btn-primary">Submit</button>
</div>
<div class="form-group">
</form>
</div>
</div>
</div>
</div>
</body>
</html>
THANK YOU FOR YOUR HELP
I HOPE I AM NOT BREAKING ANY RULES
Your onclick event handler should successfully handle the click event, but it isn't clear what you want to do with the return value of your function. The browser will not do anything by default. Instead, you need to manage this yourself.
For example, you could write the results into some other part of the DOM.
In your HTML you can create some nodes to hold the output:
<div id="result-1" />
<div id="result-2" />
Then in your event handler:
document.getElementById('result-1').innerText = first;
document.getElementById('result-2').innerText = second;
You have a variety of HTML and JavaScript syntax errors.
See comments in the code below:
// Get references to the DOM elements that you'll work with
var btn = document.querySelector("button");
var a = document.getElementById('a');
var b = document.getElementById('b');
var c = document.getElementById('c');
// Do event binding in JavaScript, not with inline HTML attributes
btn.addEventListener("click", function(){
// Use "value", not "nodeValue"
quEq(a.value, b.value, c.value);
});
function quEq(a, b, c) {
// Carefull with syntax!
var delta = (b * 2) - (4 * a * c);
if (a == 0) {
// return doesn't show up anywhere
alert("Not a quadratic equation");
} else if (delta < 0) {
alert("Complex root! No solution in real numbers");
} else {
var first= (-b + Math.sqrt(delta)) / (2*a);
var second= (-b - Math.sqrt(delta)) / (2*a);
alert(first + " " + second);
}
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script src="index.js"></script>
<title>Quadratic Equation</title>
</head>
<body>
<div class="container">
<div class="row justify-content-center">
<div class="bg-red-400">
<div class="">
<form>
<div class="form-group">
<label for="a">Enter 'a' value</label>
<input type="number" class="form-control" id="a" placeholder="1">
<label for="b">Enter 'b' value</label>
<input type="number" class="form-control" id="b" placeholder="5">
<label for="c">Enter 'c' value</label>
<input type="number" class="form-control" id="c" placeholder="6">
<button type="button" class="btn btn-primary">Submit</button>
</div>
<!-- The followng line doesn't have a closing tag and so is invalid. -->
<!-- <div class="form-group"> -->
</form>
</div>
</div>
</div>
</div>
</body>
</html>
I see two flaws in this code
1)
document.getElementById('a').nodeValue
instead of
document.getElementById('a').value
2) you should be aware that placeholder is just a text, it seems strange that you can see 6 but there's no number yet, so instead of placeholder set value attribute directly if you want some default numbers
<input type="number" class="form-control" id="a" value="1">
Now its working
a: <input type="number" name="a" id="a"><br>
b: <input type="number" name="b" id="b"><br>
c: <input type="number" name="c" id="c"><br>
<button onclick="quEq(document.getElementById('a').value,document.getElementById('b').value,document.getElementById('c').value)">Submit</button>
<script>
function quEq(a, b, c) {
var delta = (b ** 2) - (4 * a * c);
if (a == 0) {
alert("Not a quadratic equation");
};
if (delta < 0) {
alert("Complex root! No solution in real numbers");
} else {
var first= (-b + Math.sqrt(delta)) / (2*a);
var second= (-b - Math.sqrt(delta)) / (2*a);
alert(first, second);
};
};
</script>
</body>
There are a couple of things in your index.html file that are not correct, for example, you opened a second div with a class "form-group" yet you did not close it, also you did not pass properly the value for "a" (.nodeValue when it should be .value).
I made some changes to your code and appended the response in the div you weren't using (the second "form-group") and changed it's name, also I added type="button" to your button so it won't submit as soon as you click on it, you can find the html and js in codepen
Here is your function:
function quEq() {
var a = document.getElementById('a').value
var b = document.getElementById('b').value
var c = document.getElementById('c').value
var delta = (b ** 2) - (4 * a * c)
if (a == 0) {
document.getElementsByClassName("info")[0].innerHTML = "Not a quadratic equation"
}
if (delta < 0) {
document.getElementsByClassName("info")[0].innerHTML = "Complex root! No solution in real numbers"
}
else {
var first= (-b + Math.sqrt(delta)) / (2*a)
var second= (-b - Math.sqrt(delta)) / (2*a);
document.getElementsByClassName("info")[0].innerHTML = first + ", " + second
}
}
Here is your div changed:
<div class="container">
<div class="row justify-content-center">
<div class="bg-red-400">
<div>
<form>
<div class="form-group">
<label>Enter 'a' value</label>
<input type="number" class="form-control" id="a" placeholder="1" value="1"/>
<label>Enter 'b' value</label>
<input type="number" class="form-control" id="b" placeholder="5" value="5" />
<label>Enter 'c' value</label>
<input type="number" class="form-control" id="c" placeholder="6" value="6" />
<button onclick="quEq()" type="button" class="btn btn-primary">Submit</button>
</div>
<div class="info"></div>
</form>
</div>
</div>
</div>
</div>
I have two buttons in my form for calling two JavaScript functions. The first button works good in its onclick event calling the payroll() function successfully but the second button is of type submit and it never calls the send() function on form submission. I don't know why this issue occurs.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!DOCTYPE html>
<html >
<head>
<title>hr page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript"
src="/static/js/sijax/sijax.js"></script>
<script type="text/javascript">
{{ g.sijax.get_js()|safe }}</script>
<link rel="stylesheet" href="{{url_for('static', filename='styles/signupcss.css')}}">
<script type="text/javascript" >
function payroll() {
var basic=document.forms["salary"]["bsalary"].value;
var empid=document.forms["salary"]["empid"].value;
var ta,hra,da,pf,netsalary,grosssalary;
if (empid == ""||basic == "") {
alert("Employee ID and Salary details must be filled out");
return false;
}
if(isNaN(basic))
{alert("Salary must be in Numbers");
return false;
}
hra=basic*40/100;
da=basic*15/100;
pf=basic*12/100;
basic=parseInt(basic);
hra=parseInt(hra);
da=parseInt(da);
grosssalary=basic + hra + da;
ta=basic*6.2/100;
netsalary=grosssalary-ta;
document.getElementById("hra").innerHTML=hra;
document.getElementById("ta").innerHTML=ta;
document.getElementById("da").innerHTML=da;
document.getElementById("netsalary").innerHTML=netsalary;
document.getElementById("pf").innerHTML=pf;
document.getElementById("grosssalary").innerHTML=grosssalary;
window.alert("HI"+grosssalary);
return true;
}
function send()
{
var id = document.forms['salary']['empid'].value;
var basic = document.forms['salary']['bsalary'].value;
var hra = document.forms['salary']['hra'].value;
var da = document.forms['salary']['da'].value;
var ta = document.forms['salary']['ta'].value;
var pf = document.forms['salary']['pf'].value;
var gross_sal = document.forms['salary']['grosssalary'].value;
window.alert("HI"+gross_sal);
var net_sal = document.forms['salary']['netsalary'].value;
Sijax.request('send',[id, basic, hra, ta, da, pf, gross_sal, net_sal]);
}
</script>
</head>
<body style="font-family:Lato">
<div style="padding-left:5%;padding-top:0.2%;height:1%;width:100%;background-color:#11557c">
<h2>Welcome to HR Department</h2><br>
</div>
<div style="margin-left:15%" >
<h2>Name</h2>
<form id="salary" name="salary" style="margin-top: 2%" method="post" onsubmit="return send()" >
<label id = "empid">Employee ID</label><br>
<input type = "text" name = "empid" placeholder = "Employee ID" /><br><br>
<label id = "bsalary">Basic Salary</label><br>
<input type = "text" name = "bsalary" placeholder = "Basic salary" /><br><br>
<input type="button" value="Calculate" onclick="return payroll()"><br><br>
<label for ="hra">House Rent Allowance(HRA)</label>
<p id="hra" name="hra"></p><br>
<label for ="ta">Travel Allowance(TA)</label>
<p id="ta" name="ta"></p><br>
<label for ="da"> Dearness Allowance(DA)</label>
<p id="da" name="da"></p><br>
<label for ="netsalary">Net Salary</label>
<p id="netsalary" name="netsalary"></p><br>
<label for ="pf">Provident Fund(PF)</label>
<p id="pf" name ="pf"></p><br>
<label for ="grosssalary">Gross Salary</label>
<p id="grosssalary" name="grosssalary"></p><br><br>
<input type="submit" value="Upload Salary">
</form>
</div>
</body>
</html>
You can't act with <p> elements like as a form-elements. You may create a respective <input type="hidden"> elements and fill them in payroll(), or get values by .innerHtml on paragraphs.
P.S. You have actually a TypeError exception, calling undeclared form elements like document.forms['salary']['grosssalary'] and so on.
okay, quick fix, since you are using python flask library Sijax for ajax and therefore jQuery, you can alter your javascript send function like this:
function send(e){
e.preventDefault(); //it is as good as returning
//false from the function in all cases
var id = document.forms['salary']['empid'].value;
...
}
and change your onsubmit handler declaration like this:
<form id="salary" name="salary" style="margin-top: 2%" method="post"
onsubmit="return send(event)" >
please note that when you stop the event chain propagation, you will have to do a manual submission of the form.
So, you can modify your send function to do .preventDefault based on your custom criterias, otherwise, let the form submit
Your code actually works, if you're running this code as a snippet here in stack overflow, Form submission is actually blocked by default. Try running your code in codepen. I tried it and it's actually working.
http://codepen.io/jhonix22/pen/VPZagb
Check this out. It is nowhere close to a perfect solution but I think it helps. You can not access the paragraphs as if you would the form input elements. Im not entirely sure what Sijax thing is. I believe it is just a normal AJAX HTTP thing with some sort of CSRF security filters.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!DOCTYPE html>
<html>
<head>
<title>hr page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript"
src="/static/js/sijax/sijax.js"></script>
<script type="text/javascript">
{
{
g.sijax.get_js() | safe
}
}</script>
<link rel="stylesheet" href="{{url_for('static', filename='styles/signupcss.css')}}">
<script type="text/javascript">
function payroll() {
var basic = document.forms["salary"]["bsalary"].value;
var empid = document.forms["salary"]["empid"].value;
var ta, hra, da, pf, netsalary, grosssalary;
if (empid == "" || basic == "") {
alert("Employee ID and Salary details must be filled out");
return false;
}
if (isNaN(basic)) {
alert("Salary must be in Numbers");
return false;
}
hra = basic * 40 / 100;
da = basic * 15 / 100;
pf = basic * 12 / 100;
basic = parseInt(basic);
hra = parseInt(hra);
da = parseInt(da);
grosssalary = basic + hra + da;
ta = basic * 6.2 / 100;
netsalary = grosssalary - ta;
document.getElementById("hra").innerHTML = hra;
document.getElementById("ta").innerHTML = ta;
document.getElementById("da").innerHTML = da;
document.getElementById("netsalary").innerHTML = netsalary;
document.getElementById("pf").innerHTML = pf;
document.getElementById("grosssalary").innerHTML = grosssalary;
window.alert("HI" + grosssalary);
return true;
}
function send() {
var id = document.forms['salary']['empid'].value;
var basic = document.forms['salary']['bsalary'].value;
var hra = document.getElementById('hra').innerHTML;
var da = document.getElementById('da').innerHTML;
var ta = document.getElementById('ta').innerHTML;
var pf = document.getElementById('pf').innerHTML;
var gross_sal = document.getElementById('grosssalary').innerHTML;
window.alert("HI" + gross_sal);
var net_sal = document.getElementById('netsalary').innerHTML;
// I think you are missing something here.
Sijax.request('send', [id, basic, hra, ta, da, pf, gross_sal, net_sal]);
}
</script>
</head>
<body style="font-family:Lato">
<div style="padding-left:5%;padding-top:0.2%;height:1%;width:100%;background-color:#11557c">
<h2>Welcome to HR Department</h2><br>
</div>
<div style="margin-left:15%">
<h2>Name</h2>
<form id="salary" name="salary" style="margin-top: 2%" method="post" onsubmit="return false">
<label id="empid">Employee ID</label><br>
<input type="text" name="empid" placeholder="Employee ID"/><br><br>
<label id="bsalary">Basic Salary</label><br>
<input type="text" name="bsalary" placeholder="Basic salary"/><br><br>
<input type="button" value="Calculate" onclick="return payroll()"><br><br>
<label for="hra">House Rent Allowance(HRA)</label><br>
<p id="hra" readonly name="hra"></p>
<label for="ta">Travel Allowance(TA)</label><br>
<p id="ta" readonly name="ta"></p>
<label for="da"> Dearness Allowance(DA)</label><br>
<p id="da" readonly name="da"></p>
<label for="netsalary">Net Salary</label><br>
<p id="netsalary" readonly name="netsalary"></p>
<label for="pf">Provident Fund(PF)</label><br>
<p id="pf" readonly name="pf"></p>
<label for="grosssalary">Gross Salary</label><br>
<p id="grosssalary" readonly name="grosssalary"></p><br>
<input type="button" onclick="send()" value="Upload Salary">
</form>
</div>
</body>
</html>
I'm trying to collect data via forms on one page, then transfer that data to the next page for use in a JS function.
(Specifically, I want the user to input values for A, B, and C of the Quadratic equation, and then send to a page where a script takes those values and runs the equation + outputs an answer).
Here the code for my first page --->
<body>
<h1> Welcome to the Math Equation Solver </h1>
<p> Which equation would you like to solve? (Simply input the data for the equation you wish to solve). </p>
<form name="quad" method="get" action="JS_B.html">
<input
<input type="text" name="a_val" size="5">
<br>
<input type="text" name="b_val" size="5">
<br>
<input type="text" name="c_val" size="5">
<br>
<input type="submit" method="get" action="JS_B.html" value="Submit">
<input type="hidden" name="a_val">
<input type="hidden" name="b_val">
<input type="hidden" name="c_val">
</form>
Here is the code for my second page --->
<title>JS_Math Scripts</title>
<body>
<script type="Javascript">
function answer()
{
var a = a_val
document.writeln(a_val)
var b = b_val
var c = c_val
var root = Math.pow(b, 2) - 4 * a * c
var answer1 = (-b + Math.sqrt(root)) / 2*a
var answer2 = (-b - Math.sqrt(root)) / 2*a
if(root<'0');
{
alert('This equation has no real solution.')
}else{
if(root=='0')
{
answerOne = answer1
document.writeln(answerOne)
answerTwo = 'No Second Answer'
}else{
answerOne = answer1
document.writeln(answerOne)
answerTwo = answer2
document.writeln(answerTwo)
}
}
}
// End -->
</script>
<input type="hidden" name="a_val">
<input type="hidden" name="b_val">
<input type="hidden" name="c_val">
<input type="hidden" name="answerOne">
<input type="hidden" name="answerTwo">
<input type="hidden" name="Answer">
</body>
</html>
So anyways, when I input values for A, B, and C it takes me to the second page, but I'm not getting a result. I've tried inspect element and the console isn't indicating any errors, so I think my data is transferring correctly. Any ideas?
You can use FormData() to retrieve values from <input> elements within <form>; use JSON.stringify(), encodeURIComponent() to pass values from form to JS_B.html as query string.
At window load event at JS_B.html, use decodeURIComponent(), JSON.parse() to retrieve object at location.search; destructuring assignment to set variables within answer function using passed object.
Include ; following variable assignments, remove ; following if condition
index.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1> Welcome to the Math Equation Solver </h1>
<p> Which equation would you like to solve? (Simply input the data for the equation you wish to solve). </p>
<form name="quad">
<input type="text" name="a_val" size="5">
<br>
<input type="text" name="b_val" size="5">
<br>
<input type="text" name="c_val" size="5">
<br>
<input type="submit" value="Submit">
<!--
<input type="hidden" name="a_val">
<input type="hidden" name="b_val">
<input type="hidden" name="c_val">
-->
</form>
<script>
var form = document.querySelector("form");
form.onsubmit = function(e) {
e.preventDefault();
var data = new FormData(this);
var obj = {};
for (prop of data.entries()) {
obj[prop[0]] = prop[1]
};
var query = encodeURIComponent(JSON.stringify(obj));
location.href = "JS_B.html?" + query;
}
</script>
</body>
</html>
JS_B.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
function answer(obj) {
var {
a_val: a,
b_val: b,
c_val: c
} = obj;
document.writeln(a);
var root = Math.pow(b, 2) - 4 * a * c;
var answer1 = (-b + Math.sqrt(root)) / 2 * a;
var answer2 = (-b - Math.sqrt(root)) / 2 * a;
if (root < 0) {
alert('This equation has no real solution.')
} else {
if (root == 0) {
answerOne = answer1;
document.writeln(answerOne);
answerTwo = 'No Second Answer'
} else {
answerOne = answer1;
document.writeln(answerOne);
answerTwo = answer2;
document.writeln(answerTwo)
}
}
} // End -->
window.onload = function() {
var obj = JSON.parse(decodeURIComponent(location.search.slice(1)));
console.log(obj);
answer(obj);
}
</script>
<input type="hidden" name="a_val">
<input type="hidden" name="b_val">
<input type="hidden" name="c_val">
<input type="hidden" name="answerOne">
<input type="hidden" name="answerTwo">
<input type="hidden" name="Answer">
</body>
</html>
plnkr http://plnkr.co/edit/aaY5rcJ6v0g7bdEEr7h0?p=preview
This should be a no brainer but i have no experience in Javascript and i can't see why this should not work.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Undantag</title>
<p> STD: </p>
<input type="number" name="STD">
<p> STA: </p>
<input type="number" name="STA">
<p> ATD: </p>
<input type="number" name="ATD">
<p> ATA: </p>
<input type="number" name="ATA">
<button onclick="useUndantag()">Click me</button>
</head>
<body>
<script>
function useUndantag() {
var a = document.getElementsByName("STD");
var b = document.getElementsByName("ATD");
var c = document.getElementsByName("STA");
var d = document.getElementsByName("ATA");
if (a-b >1) {
alert("No undantag");
}
else if (d-c >2) {
alert ("No undantag");
else () {
alert ("NO EU FOR YOU!")
}
}
}
</script>
</body>
</html>
The problem is that i get no alert at all and i can't seem to figure out why. If anyone has any tips if would be very glad for any help i can get.
First of all, getElementsByName returns a collection of HTML elements. Use [0] to access the first element. Next, you must use parseFloat or parseInt to parse the inputs as integers/floats. Also, HTML code goes in the body tag unless you have scripts, links, meta, title, and other tags. Finally, you have an syntax error:
else () { }
Should not have parentheses. You're also missing a brace after the else if, remove a closing brace after the else. Here's a fixed snippet:
function useUndantag() {
var a = document.getElementsByName("STD")[0].value;
var b = document.getElementsByName("ATD")[0].value;
var c = document.getElementsByName("STA")[0].value;
var d = document.getElementsByName("ATA")[0].value;
if (parseInt(a) - parseInt(b) > 1) { //notice the use of parseInt, you can use parseFloat to deal with decimals
alert("No undantag");
} else if(parseInt(d) - parseInt(c) > 2) {
alert("No undantag");
} else { //Notice no parentheses and some more braces
alert("NO EU FOR YOU!")
}
}
<p> STD: </p> <!-- HTML is in body tag !-->
<input type="number" name="STD">
<p> STA: </p>
<input type="number" name="STA">
<p> ATD: </p>
<input type="number" name="ATD">
<p> ATA: </p>
<input type="number" name="ATA">
<button onclick="useUndantag()">Click me</button>
Also, make sure you use .value to get the value.
Your syntax is incorrect.
Also, if you are comparing the values of the inputs then you need to get the value attribute of the input.
Also, document.getElementsByName returns an array of elements so you need to select the first element.
Here is a working example:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Undantag</title>
</head>
<body>
<p> STD: </p>
<input type="number" name="STD">
<p> STA: </p>
<input type="number" name="STA">
<p> ATD: </p>
<input type="number" name="ATD">
<p> ATA: </p>
<input type="number" name="ATA">
<button onclick="useUndantag()">Click me</button>
<script>
function useUndantag() {
var a = document.getElementsByName("STD")[0].value;
var b = document.getElementsByName("ATD")[0].value;
var c = document.getElementsByName("STA")[0].value;
var d = document.getElementsByName("ATA")[0].value;
if (a - b > 1) {
alert("No undantag");
} else if (d - c > 2) {
alert("No undantag");
} else {
alert("NO EU FOR YOU!")
}
}
</script>
</body>
</html>
You have enough errors
the function
document.getElemenstByName
return an array!
var a = document.getElementsByName("STD")[0].value;
var b = document.getElementsByName("ATD")[0].value;
var c = document.getElementsByName("STA")[0].value;
var d = document.getElementsByName("ATA")[0].value;
and you have sentences misdeclared
here code:
https://jsfiddle.net/evpog628/1/
1) It's better to use getElementById(), it's faster and you select only one element ("id" must be unique in HTML document).
2) Be sure to use correct HTML structure
<!doctype html>
<html>
<head>
<meta>
<title></title>
</head>
<body>
<input>
<script>
</script>
</body>
</html>
3) You need to be sure you get integer or float values from HTML fields to make your code work correctly. parseInt() or pareseFloat().
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Undantag</title>
</head>
<body>
<p> STD: </p><input type="number" id="STD">
<p> STA: </p><input type="number" id="STA">
<p> ATD: </p><input type="number" id="ATD">
<p> ATA: </p><input type="number" id="ATA">
<button onclick="useUndantag();">Click me</button>
<script>
function useUndantag() {
var a = document.getElementById("STD");
var b = document.getElementById("ATD");
var c = document.getElementById("STA");
var d = document.getElementById("ATA");
if (parseInt(a.value)-parseInt(b.value)>1) {
alert("No undantag");
}
else if (parseInt(d.value)-parseInt(c.value) >2)
{
alert ("No undantag");
}
else
{
alert ("NO EU FOR YOU!");
}
}
</script>
</body>
</html>