javascript code not working with html script - javascript

hi guys I just begin to learn javascript recently and I came across an issue, when I enter a "10" as the first input element and click submit, it should print a "10" at the bottom of the html page, but instead it prints nothing.
<html>
<head>
<head>
<form action="" method="POST" id="info">
<br>Age:<br><label>
<input name="age" id="age" type="text" placeholder= "enter your age" />
</label>
<br>Sex:<br><label>
female<input name="female" id="female" type="checkbox" />|
male<input type="checkbox" name="male" id="male" />|
</label>
<br>weight:<br><label>
<input type="text" name="weight" id="weight" placeholder="enter your weight in kg" />
</label>
<input type="submit" form="info" value="Submit" onclick="validation()"/>
</form>
<div id="div1"> </div>
<script src = "test.js"></script>
<html>
This is the html code (index.html)
function validation(){
var ageinput = parseInt(document.getElementById("age"));
var femaleinput = ducument.getElementById("female");
var maleinput = ducument.getElementById("male");
var weight = parseInt(document. getElementById("weight"));
var formulaformale;
var formulaforfemale;
var gendererror;
if (ageinput == 10){
gendererror = ageinput
}
document.getElementById("div1").innerHTML = gendererror;
}
this is the javascript code.(test.js)
I tried to find syntax errors but everything looks fine to me, I also compared my code with other people's and I could find anything in my code that is different.I am totally new in javascript so I might have missed certain part of the programming language. please help.

Your button type is submit, so it will always submit and reload the page every time you press the button. Make it a normal button by changing input type to button
<input type="button" form="info" value="Submit" onclick="validation()"/>
Then follow #Ibra answer
// add .value
var ageinput = parseInt(document.getElementById("age").value);
// ducument -> document
var femaleinput = ducument.getElementById("female").value;

Try again like this :
// add .value
var ageinput = parseInt(document.getElementById("age").value);
// ducument -> document
var femaleinput = ducument.getElementById("female").value;

Related

How to transfer values from between input

Before anyone marks this as a duplicate, I have looked at many sites and am currently using this one - jQuery - passing value from one input to another for guidance, yet no result... I am trying to pass a value from one input in one form to another input in a 'table'. I have put it in a table because of a very weird reason - it does not display a Sparql value when in a form only displays in a table so the input was placed in a table. My code is below:
Form
<form onclick="txtFullName.value = txtFirstName.value +'_'+ txtLastName.value">
First name : <input type="text" name="txtFirstName" value="#ViewBag.FirstName"/> <br><br>
Last name : <input type="text" name="txtLastName" value="#ViewBag.LastName" /> <br><br>
Full name : <input type="text" id="txtFullName" name="txtFullName"> <br><br />
<input id="submit12" type="button" value="Submit">
</form>
Table
<table id="results">
<Full name:
<br>
<input id="userInput" type="text" name="fullname" ${userJson.userId == ''?'': 'disabled'} value="#ViewBag.DisplayName">
<br>
<input id="submit" type="submit" value="Submit">
</table>
JQUERY
$('#submit12').on('click', function (e) { //Form submit
$('#userInput').change(function () {
$('txtFullName').val($(this).val());
});
});
I am trying to display the txtFullName into userInput input when pressing submit but right now only the `txtFullName' is displayed when pressing submit. Also the submit is the submit button in the FORM.
Anymore info needed let me know:)
You need to change the onclick to action on the form if you are trying to use submit button. The other way is to use input type button instead of submit:
So:
$(document).ready(function() {
$('#submit12').on('click', function (e) {
console.log('test');
$("#txtFullName").val($("#txtFirstName").val() + '_' + $("#txtLastName").val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
First name : <input type="text" id="txtFirstName" value="First"/> <br><br>
Last name : <input type="text" id="txtLastName" value="Last" /> <br><br>
Full name : <input type="text" id="txtFullName" name="txtFullName"> <br><br />
<input id="submit12" type="button" value="Submit">
</form>
If you want to display txtFullName into userInput, simply do something like this:
$('#submit12').on('click', function (e) { //Form submit
$('#userInput').val($('#txtFullName').val());
});
And why do you need change function there , if yo need changes when click submit.
Edit your JQuery like this:
$('#submit12').on('click', function (e) { //Form submit
$('#userInput').change(function () {
$('#txtFullName').val($(this).val());
});
});
$('#submit').on('click', function () { //Form submit
$('#userInput').val($('#txtFullName').val());
});
I don't clearly understand why you do it but It can fix your code.
It is not entirely clear what the two buttons do, but the operation itself is really very simple. See comments inline for explanations:
// Wait until the DOM is loaded and all elements are avaialble
window.addEventListener("DOMContentLoaded", function(){
// Get references to the DOM elements you'll need
var theForm = document.getElementById("frmTest");
var txtFirstName = document.getElementById("txtFirstName");
var txtLasttName = document.getElementById("txtLastName");
var txtFulltName = document.getElementById("txtFullName");
var txtUserInput = document.getElementById("txtUserInput");
var btn1 = document.getElementById("btnSubmit1");
var btn2 = document.getElementById("btnSubmit2");
// Function to join names together
function combine(){
txtFullName.value = txtFirstName.value + '_' + txtLastName.value;
}
// Set event handlers
frmTest.addEventListener("click", combine);
btn1.addEventListener("click", combine);
});
<!-- Keep you JavaScript out of your HTML -->
<form id="frmTest">
First name : <input type="text" id="txtFirstName" name="txtFirstName" value="#ViewBag.FirstName">
<br><br>
Last name : <input type="text" id="txtLastName" name="txtLastName" value="#ViewBag.LastName" >
<br><br>
Full name : <input type="text" id="txtFullName" name="txtFullName"> <br><br />
<input id="btnSubmit1" type="button" value="Combine Names">
<table id="results">
<Full name:
<br>
<input id="txtUserInput" type="text" name="fullname" ${userJson.userId == ''?'': 'disabled'} value="#ViewBag.DisplayName">
<br>
<input id="btnSubmit2" type="submit" value="Submit">
</table>
</form>

Multiplying calculator

I am trying to create a simple calculator that takes a number from 1 text box and after hitting a submit button it takes the number and multiplies it by 92 then puts it in a read only box.
This is what I have so far:
<form name="1star">
<input type="text" name="input"/>
<input type="button" value="Enter" OnClick="1star.output.value == 1star.input.value * 92"/>
<br/>
<input type="text" name="output" readonly="readonly" />
</form>
This is not working and I could use some help. I know its easy but I am very new to js and I'm not understanding why this isn't working.
<form name="onestar">
<input type="text" name="input"/>
<input type="button" value="Enter" OnClick="onestar.output.value = onestar.input.value * 92"/>
<br/>
<input type="text" name="output" readonly="readonly" />
</form>
An identifier cannot start with a digit in JavaScript, so 1star is an error. Also, you wanted = (assignment), not == (comparison).
That said, there are a number of outdated or beginner practices above. If I was writing it, I would separate the script from the markup, and I'd use document.getElementById to fetch the element rather than relying on implicit variables defined by name. I would also explicitly parse the string into a number. But for now no need to worry about it too much. Even though the code seems much more complicated at first glance, it's all things that will make your life easier later, with bigger programs.
var input = document.getElementById('input');
var output = document.getElementById('output');
var button = document.getElementById('button');
button.addEventListener('click', function(evt) {
var value = parseInt(input.value, 10);
if (!isNaN(value)) {
output.value = value * 92;
}
});
<form>
<input type="text" id="input"/>
<input type="button" id="button" value="Enter"/>
<br/>
<input type="text" id="output" readonly="readonly" />
</form>

Why is my alert always showing the wrong information? (addition)

I'm currently writing some code using both HTML and Javascript. I'm building myself a mini Javascript calculator that can run simple additions using a HTML 'GUI' - if you take it that way. The code is below.
<!DOCTYPE html>
<html lang="en">
<head>
<link href="stylesheet/calculator.css" type="text/css" rel="stylesheet" />
<script>
function activeButton() {
if (document.getElementById("radioAdd").checked === true) {
var valueOne = Number(document.getElementById("number1".value));
var valueTwo = Number(document.getElementById("number2".value));
var result = valueOne + valueTwo;
alert("Your Result Is " + result);
}
}
</script>
</head>
<body>
<div id="wrapper">
<div id="form-move">
<form name = "calculator" id="calculator">
<div id="numberInput">
<input type="number" name="inputNumber1" id="number1" placeholder="Type or Select Your First Number" />
<input type="number" name="inputNumber2" id="number2" placeholder="Type or Select Your Second Number" />
</div>
<div id="radio-input">
<span class="title">Operators:</span>
<input type="radio" name="radioInputAdd" id="radioAdd" value="Addition" />
<label for="radioAdd">Addition</label>
<input type="radio" name="radioInputAdd" id="radioDivision" value="Division" />
<label for="radioDivision">Division</label>
<input type="radio" name="radioInputAdd" id="radioMultiply" value="Multiplication" />
<label for="radioMultiply">Multiply</label>
<input type="radio" name="radioInputAdd" id="radioSubtract" value="Subtraction" />
<label for="radioSubtract">Subtract</label>
</div>
<div class="submit">
<input type="submit" value="Enter" id="submit" onclick="activeButton()" />
</div>
</form>
</div>
</div>
There are TWO input boxes in the middle of the page, which only accept numbers.
Underneath them are four radio buttons - Add, division, Multiply and Subtract. Now, You can see the javascript incorporated at the top of the page. The problem I have is that when I run the page and want to add two numbers, the code works but the answer comes out as 0. I have tested this in chrome and this happens all the time.
Could Someone Possibly please help?
The problem is in how you're trying to get the value from the input elements. In this code:
var valueOne = Number(document.getElementById("number1".value));
var valueTwo = Number(document.getElementById("number2".value));
You're trying to get the value property from the string "number1", which is undefined, then passing that to document.getElementById, which will return null, and then passing that to Number, which will return 0.
Try this this instead:
var valueOne = Number(document.getElementById("number1").value);
var valueTwo = Number(document.getElementById("number2").value);
Try this:
var valueOne = Number(document.getElementById("number1").value);
var valueTwo = Number(document.getElementById("number2").value);
You have the paranthesis in the wrong place.

Get numerical values from input fields and use them to calculate the surface area of a trapezoid

I am new to Javascript and I will be thankful if someone help me understand what I am doing wrong. I am trying to calculate the surface area of a trapezoid by obtaining values from input fields. When I press the "Calculate S" button I get a "Nan" as an answer.
This is the major part of the HTML code:
<form method="post">
<label for="a">a</label>
<input type="text" id="a"/> <br/>
<label for="b">b</label>
<input type="text" id="b"/> <br/>
<label for="h">h</label>
<input type="text" id="h"/> <br/>
<button onclick="alert(S)">Calculate S</button>
</form>
And this is the script I am using to obtain the values and calculate the surface:
<script type="text/javascript">
var a=parseInt(document.getElementById("a"), 10);
var b=parseInt(document.getElementById("b"), 10);
var h=parseInt(document.getElementById("h"), 10);
var S=parseInt(((a+b)/2)*h, 10);
</script>
Thanks in advance!
You need to get the value out of each input, not just the input, like this:
<script type="text/javascript">
var a=parseInt(document.getElementById("a").value, 10);
var b=parseInt(document.getElementById("b").value, 10);
var h=parseInt(document.getElementById("h").value, 10);
var S=((a+b)/2)*h;
</script>
Use .value property on the input elements to get their contents. then call parseInt on that to get a number.
No need to parseInt the result too.
var S = ((a + b) / 2) * h;
Wrap the code in a callable function if you want it executed on button click (what you have now will execute when the code been parsed by your browser).
Example found here: http://jsfiddle.net/bpwEh/
Updated code:
<head>
<!-- ... -->
<script>
function calc(){
var a=parseInt(document.getElementById("a").value, 10);
var b=parseInt(document.getElementById("b").value, 10);
var h=parseInt(document.getElementById("h").value, 10);
return ((a+b)/2)*h, 10;
}
</script>
</head>
<body>
<form method="post">
<label for="a">a</label>
<input type="text" id="a"/> <br/>
<label for="b">b</label>
<input type="text" id="b"/> <br/>
<label for="h">h</label>
<input type="text" id="h"/> <br/>
<button onclick="alert(calc()); return false;">Calculate S</button>
</form>
</body>

How to fix form action issue in XHTML 1.0 Strict

I've got an issue with validating my code to XHTML 1.0 Strict.
I've been using the w.3 validator to try and validate my page.
It tells me
Line 112, Column 24: required attribute "action" not specified
<form id="orderform">
The attribute given above is required for an element that you've used,
but you have omitted it. For instance, in most HTML and XHTML document
types the "type" attribute is required on the "script" element and the
"alt" attribute is required for the "img" element.
Typical values for type are type="text/css" for and
type="text/javascript" for script.
I'm relatively new to XHMTL and CSS and I'm also learning Javascript at this time, I've done a Google search and I've found a lot of people talking about using a Javascript line to fix the error, but none of them are clear enough. Is there anyone here who can provide a clear explanation for me?
This is my XHTML code..
<form id="orderform">
<div class="field">
Name:
<input type="text" id="name" name="name" value="" />
</div>
<div class="field">
# of Home shirts:
<input type="text" id="homeshirt" name="home" value="" onchange="updateOrder();" />
</div>
<div class="field">
# of Away shirts:
<input type="text" id="awayshirt" name="away" value="" onchange="updateOrder();" />
</div>
<div class="field">
Date of collection:
<input type="text" id="date" name="date" value="" />
</div>
<div class="field">
Subtotal:
<input type="text" id="subtotal" name="subtotal" value="" readonly="readonly" />
</div>
<div class="field">
Tax:
<input type="text" id="tax" name="tax" value="" readonly="readonly" />
</div>
<div class="field">
Total:
<input type="text" id="total" name="total" value="" readonly="readonly" />
</div>
<div id="button">
<input type="button" class="button" value="Place Order" onclick="placeOrder(this.form);" />
</div>
</form>
and my Javascript...
<script type="text/javascript">
function updateOrder() {
const TAXRATE = 0.0925;
const SHIRTPRICE = 39.99;
var numHomeShirt = parseInt(document.getElementById("homeshirt").value);
var numAwayShirt = parseInt(document.getElementById("awayshirt").value);
if (isNaN(numHomeShirt))
numHomeShirt = 0;
if (isNaN(numAwayShirt))
numAwayShirt = 0;
var subTotal = (numHomeShirt + numAwayShirt) * SHIRTPRICE;
var tax = subTotal * TAXRATE;
var total = subTotal + tax;
document.getElementById("subtotal").value = "£" + subTotal.toFixed(2);
document.getElementById("tax").value = "£" + tax.toFixed(2);
document.getElementById("total").value = "£" + total.toFixed(2);
}
function placeOrder(form) {
if (document.getElementById("name").value == "")
alert("I'm sorry but you need to provide a name to print on the shirt.");
else if (document.getElementById("date").value == "")
alert ("I'm sorry but you must provide a date you can collect your shirt(s).");
}
</script>
Thank you for your time,
Cheers.
Jamie
Maybe this is too obvious and I'm missing something, but why not just add the action attribute to the form?
No need for javascript. If you're using php just add the following code:
<form id="your_id" action="<?=$_SERVER['PHP_SELF']?>">
Basically, this code will set the action to the same page.
Or others suggest, just add an empty action :)
To fix that particular validation error you need to include the action attribute in the form element.
<form id="orderform" action="">
It looks like you're using JavaScript to handle form submission, so you should just be able to leave the action empty, otherwise give it a value that pertains to the form submission php script.
XHTML require that your form include an action that will be called (that is, another script on the server) when the submit button is pressed.
Currently you're only implementing the behaviour in Javascript - if this is disabled then nothing will happen. Ideally you should point to a script, usually the same PHP script as the one generating the form, to handle the submit button press:
<form id="your_id" action="<?=$_SERVER['PHP_SELF']?>">
Then your script should handle the submission in the case that the Javascript didn't.

Categories

Resources