HTML form does not submit in JavaScript - javascript

Trying to create a simple age calculator. At the moment the current year will populate but when you enter your birth year and click submit nothing happens.
function aaa(){
date=new Date();
var y=date.getFullYear();
document.getElementById('ddd').value=y;
}
function display(){
var c=document.getElementById('eee').getFullYear.value;
//var aa= document.getElementById('eee').(this).('getDate').value;
var e= y - c;
{
document.write("Ans="+e);
}
alret(e);
}
<body onload="aaa();">
<form name="xyz" method="post">
CurrentDate:<input type="text" name="ddd" id="ddd">
BirthDate:<input type="date" name="eee" id="eee">
Age:<input type="text" name="age" id="age">
<input type="submit" name="submit" value="submit" onClick="display();">
</form>
</body>

Probably better for code review, but here goes:
<script language="javascript">
The language attribute for script elements was deprecated in HTML 4 and removed in HTML5. Remove it.
function aaa()
Functions should have a meaningful name, e.g. setYear.
{
date=new Date();
You should keep variables local with var.
var y=date.getFullYear();
document.getElementById('ddd').value=y;
You could just do:
document.getElementById('ddd').value = new Date().getFullYear();
}
function display()
{
var c=document.getElementById('eee').getFullYear.value;
Input type date isn't supported by all browsers, and that won't work anyway. If you are just using the difference in years (which will be incorrect by 1 year about half the time) then why not just ask for the year?
var e= y - c;
{
document.write("Ans="+e);
}
The block is redundant, and calling document.write after the load event will first clear the entire document (everything, including all scripts) and load a new document with just the content passed to document.write.
[...]
So a re-write might look like:
function calcAge(element) {
var form = element.form;
form.age.value = form.currentYear.value - form.birthYear.value;
}
window.onload = function() {
document.forms[0].currentYear.value = new Date().getFullYear();
}
<form>
Current year: <input name="currentYear"><br>
Birth year: <input name="birthYear"><br>
<input type="button" onclick="calcAge(this)" value="Caluclate age"><br>
Your age: <input name="age" readonly><br>
</form>
Note that every control in a form has a form property that references the form it's in. Also, form controls with a name are available as named properties of the form (hence a control named submit overwrites the submit method).

document.getElementById('eee') is a DOM element.
document.getElementById('eee').getFullYear is, judging from your code, undefined.
document.getElementById('eee').getFullYear.value should throw an error.
You were trying to read a property from an object which is (unfortunately) undefined, that's why your code doesn't work. Open console and see if there is a red line saying something like this:
Cannot read property 'value' of undefined

Related

Why is the input type "date" value not updating new values from the input

I am trying to get a date from the input type "date" but when I retrieve the data in JavaScript, only the default value that I set is retrieved all the time.
No matter what I do, I keep getting the default value instead of the new one I chose.
I couldn't find any solution from all the similar questions about this, please do not flag this question because I am already getting a warning that my last question was not well received by the community, I thought we are here to learn and asking stupid questions is part of it.
var getInput = document.querySelector("#year");
var data = getInput.value, dob = data.split("-"), byy = dob[0], bmm = dob[1], bdd = dob[2];
function process(){
console.log(byy)
}
<input id="year" type="date" value="2022-12-25" required><br>
<input id="goBtn" onclick="process()" type="button" value="Go">
Get the date value within the function you are calling.
function process() {
var getInput = document.querySelector("#year");
var data = getInput.value, dob = data.split("-"), byy = dob[0], bmm = dob[1], bdd = dob[2];
console.log(byy);
}
<input id="year" type="date" value="2022-12-25" required><br>
<input id="goBtn" onclick="process()" type="button" value="Go">
The variables were being assigned to immediately when the JavaScript executed, giving them the default value. They need to be assigned to at the time you press the go button.

Cant quite invalidate/validate dates correctly (arrival date) ?

This is my html code with a snippet of just the code I am trying to use to invalidate/validate date entries with hopefully all of the corresponding and necessary variables declared.
<html>
<head>
<title> Booking Page </title>
<script>
function Booking(){
var departuredate = document.getElementById("departdate").value; //departure date selected by user
var arrivaldate = document.getElementById("arrivedate").value; //arrival date selected by user
departuredate = new Date(departuredate);
arrivaldate = new Date(arrivaldate);
CurrentDate = new Date(); //todays date
month = '' + (arrivaldate.getMonth() + 1),
day = '' + arrivaldate.getDate(),
year = arrivaldate.getFullYear();
var adate = [day, month, year].join('/');
alert(adate);
the adate is for the arrival date only. I plan to just copy and adjust the code across once it is correct for the departure date. Currently the code seems to invalidate all entries, not allowing completely valid entries to be validated.
var re = /[0-9]{2}\/[0-9]{2}\/[0-9]{4}/;
if (!adate.match(re))
{
document.getElementById("temp").innerHTML = "Incorrect format"
document.MyForm.arrivedate.focus();
document.getElementById("arrivedate").style.border='1px solid red';
return false;
}
else
{
// if none of the above situaton's occur then the input is true and validated
alert('Dates are validated');
return true;
}
}
</script>
</head>
<body>
<H1> Booking Form </H1>
<Form action="testpage.py" method="POST" name="MyForm" onsubmit="return Booking()">
<p>Departure Date:</p>
<input type=date name="departdate" id="departdate" >
<p>Arrival Date:</p>
<input type=date name="arrivedate" id="arrivedate">
<input type=submit value="Find flights">
</Form>
</body>
</html>
You have multiple problems here. First is that the date type for inputs is non-standard, so it won't work in most browsers (IIRC chrome, edge, and iOS safari are the exceptions).
I recommend that you either use a third-party library like jquery-ui-datepicker or use a text input with the validation logic using the html pattern attribute or a js event handler if you have to support desktop safari (which doesn't support the pattern attribute).
Something like <input type="text" pattern="/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/"...
Or if pattern won't work:
var myDateInput = document.getElementById('date-input');
myDateInput.addEventListener('change', function(e) {
if (!(e.target.value.match(dateRegex)) {
//let user know somehow
}
});
You can throttle the handler so that it doesn't fire on successive keystrokes. Also note that even in browsers with the date input type they expect "yyyy-mm-dd" format, so make your regex:
/[0-9]{4}-[0-9]{2}-[0-9]{2}/.

Need help using increments and displaying in a textbox

We need to have a textbox where you enter a number, hit a button, and it increments by 1, while staying in the same text box. Here is the code I have so far:
<form action=#>
<p>
Current Count...<input type="text" id="txtCounter" value="0">
</p>
<p>
<input type="button" value="Increment Count" id="btnIncrement" onclick="btnIncrement_onclick()">
<input type="reset">
</p>
</form>
<noscript>This website requires JavaScript to be enabled.</noscript>
JavaScript:
function btnIncrement_onclick() {
// get textbox and assign to a variable
var countTextbox = document.getElementById("txtCounter");
var txtCounterData = txtCounter.value;
var countTextbox.value = 0++;
}
If someone could explain to me how to do it not just give me the answer. I don't know why I'm having such a hard time with this.
Try the following simple code :
function btnIncrement_onclick()
{
//asign the textbox to variable
var textbox = document.getElementById("txtCounter");
//Get the value of textbox and add 1 then update the textbox
textbox.value = parseInt(textbox.value)+1;
}
<form action=#>
<p>
Current Count...<input type="text" id="txtCounter" value="0">
</p>
<p>
<input type="button" value="Increment Count" id="btnIncrement" onclick="btnIncrement_onclick()">
<input type="reset">
</p>
</form>
<noscript>This website requires JavaScript to be enabled.</noscript>
Hope this helps.
In your HTML:
In your html you had a onclick="btnIncrement_onclick()" and that means every click will triggers your function.
In your JS:
function btnIncrement_onclick() {
// Named as countTextbox you input. sou we can use it later.
var countTextbox = document.getElementById("txtCounter");
// Get the current value attribute of it, initialy 0.
var txtCounterData = txtCounter.value;
// The line above is not being used. but you can check it with a console.log like this:
console.log(txtCounterData);
// Now you are calling again your input and changing his value attribute. this ++ means a increment. so we are increasing +1;
countTextbox.value++;
}
You should read more about increment and operators and DOM (the way whe select the tag by id, and again selected his attribute).
Sorry didn't found a good source in english.

Javascript change hidden field on submit

Hi I am trying to install a merchant facility onto my website and it needs to submit a value $vpc_Amount which is the amount purchased in cents.
What I need to do is multiply the amount entered by the user ($amount) by 100 to get $vpc_Amount.
I tried the following but it isn't working.
<input type="text" ID="A1" name="amount"onkeypress="process1()">
<input type="hidden" id="A2" name="vpc_Amount">
And then the javascript
function process1() {
f1 = document.getElementById("A1").value;
total = f1*1000;
document.getElementById("A2").value = total;
}
What is happening is it is occasionally working but most of the time it doesn't. I know there is something wrong with the script so hence asking here.
Try to use onkeyup function -
<input type="text" id="A1" name="amount" value="" onkeyup="process1();" />
<input type="hidden" id="A2" name="vpc_Amount" />
javascript function -
function process1() {
var f1 = document.getElementById("A1").value;
var total = (f1 * 100);
document.getElementById("A2").value = total;
}
Use Jquery. http://jquery.com/
$(function() {
$('#form_id').submit(function(){
$('#form_id').find('#A2').val('New value');
return true;
});
});
Have you tried to use onkeyup event? It might be so that onkeypress event is triggered before the character is added to text field.
<input type="text" ID="A1" name="amount" onkeyup="process1()">
Also, I would suggest that you try to convert the value of the textfield to integer and add other input handling too. Users might enter any kind of data there and it can crash your javascript code.
This code should work:
document
.getElementById('A1')
.addEventListener('keyup', function (e) {
document.getElementById('A2').value = parseInt(this.value) * 1000;
})
keypress event triggers before value changes in text field and keyup after value has changed.
Basically event trigger in order:
keydown (onkeydown)
keypress (onkeypress)
keyup (onkeyup)
Force value to be integer or you will get NaN in some cases.
I will suggest to use onblur this is the best way if you want to use the build in attribute listener if you don't use jquery. Here is example:
<!DOCTYPE html>
<html>
<body>
Enter your name: <input type="text" id="fname" onblur="myFunction()">
<p>When you leave the input field, a function is triggered which transforms the input text to upper case.</p>
<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</body>
</html>
And url to the example in w3 school :) http://www.w3schools.com/jsref/event_onblur.asp
First of all, I think you should use onkeypup event and not onkeypress
<input type="text" id="A1" name="amount" onkeyup="process1()" value="" />
<input type="hidden" id="A2" name="vpc_Amount" value="" />
Javascript code -
function process1() {
var f1 = parseFloat(document.getElementById("A1").value);
var total = f1*100; //you said 100 so, I changed to 100
document.getElementById("A2").value = total;
}
jQuery code for the same -
jQuery(document).ready(function($){
$("#A1").keyup(function(){
var total = parseFloat($("#A1").val()) * 100;
$("#A2").val(total);
});
});
Your code can be simplified by making use of the fact that form controls are available as named properties of the form baed on their name. This removes the requirement to add IDs to form controls that must have a name anyway.
Pass a reference to the control in the listener:
<input type="text" name="amount" onkeyup="process1(this)">
<input type="hidden" name="vpc_Amount">
Then use the passed reference to get the form and other controls:
function process1(element) {
element.form.vpc_Amount.value = element.value * 100;
}
You may wish to use the change event instead to save updating the hidden field unnecessarily while the user is typing and also to catch changes that aren't based on key presses (e.g. pasting from the context menu).
You should also do some validation of the values entered so the user doesn't attempt to send the form with invalid values (noting that you must also do validation at the server as client side validation is helpful but utterly unreliable).

Expanding HTML forms using Javascript

I have a simple HTML form that asks a user to input their name, SKU, quantity, and comments. This is for a simple inventory request system.
<html>
<body>
<form id="myForm" method="post">
<input type="submit">
<br>Name: <input type="text" name="form[name]">
<br>SKU: <input type="text" name="form[SKU1]">
<br>Quantity: <input type="text" name="form[quantity1]">
<br>Comment: <input type="text" name="form[comment1]">
</form>
Add item
<script>
var num = 2; //The first option to be added is number 2
function addOption() {
var theForm = document.getElementById("myForm");
var newOption = document.createElement("input");
newOption.name = "form[SKU"+num+"]"; // form[varX]
newOption.type = "text";
theForm.appendChild(newOption); //How can I add a newline here?
optionNumber++;
}
</script>
</body>
</html>
Currently I can only get it working where it will add a single form value. I would like to recreate the entire myForm except for the name field with a single click.
Your post is very old, so presumably you've found an answer by now. However, there are some things amiss with your code.
In the JavaScript code you have
var num = 2;
This is the number that is incremented to keep track of how many "line-items" you will have on the form. In the function addOption(), though, instead of incrementing num you have
optionNumber++;
You never use optionNumber anywhere else. Your code works once, when you add the first item, but since you increment the wrong variable, you are effectively always adding option 2.
Oh, and adding the newline: you need to append a <br> element.

Categories

Resources