Converting HTML form input into Javascript variables and comparing values - javascript

I am trying to compare the birth dates of two people. Person 1 and Person 2 input their names and dates of birth in an HTML form, and I want to use Javascript to compare the two dates and print out which person is older on the HTML page. However, I'm not sure how to submit the form and compare the dates. Here is what I have so far for the HTML:
<form id="form1">
Full name of first person: <input type="text" name="name1"><br>
Birthday: <input type="date" date="date1"><br>
<br>
Full name of second person: <input type="text" name="name2"><br>
Birthday: <input type="date" date="date2"><br>
</form>
And the Javascript:
var name1 = document.getElementsByName("name1");
var name2 = document.getElementsByName("name2");
var date1 = document.getElementsByName("date1");
var date2 = document.getElementsByName("date2");
How do I submit the variables in HTML and then have Javascript compare the two dates?

You forgot two things:
A submit button.
A submit handler.
I guess this solves your question.
window.onload = function () {
document.getElementById("form1").onsubmit = function () {
var name1 = document.getElementById("name1");
var name2 = document.getElementById("name2");
var date1 = document.getElementById("date1");
var date2 = document.getElementById("date2");
if ((new Date(date1.value)).getTime() < (new Date(date2.value)).getTime()){
console.log(name1.value + " is greater than " + name2.value)}
else if ((new Date(date1.value)).getTime() > (new Date(date2.value)).getTime()){
console.log(name2.value + " is greater than " + name1.value)}
else{
console.log(name2.value + " and " + name1.value + " are of same age.")};
};
};
<form id="form1">
Full name of first person: <input type="text" id="name1"><br>
Birthday: <input type="date" id="date1"><br>
<br>
Full name of second person: <input type="text" id="name2"><br>
Birthday: <input type="date" id="date2"><br>
<input type="submit" value="Check" />
</form>

You need to add an action to the form and a submit button. Then you can add an onsubmit call from your button to invoke a simple string comparison function to see which number is greater

Basic form data access demo
var compare = function () {
var form = document.getElementById("form1");
var output = document.getElementById("demo");
output.innerHTML = "";
for(var i = 0; i< form.length; i++){
output.innerHTML = output.innerHTML +" "+ form.elements[i].value;
};
};
<form id="form1">
Full name of first person: <input type="text" id="name1"><br>
Birthday: <input type="date" id="date1"><br>
<br>
Full name of second person: <input type="text" id="name2"><br>
Birthday: <input type="date" id="date2"><br>
</form>
<input type="button" name="submit" value="Compare " onclick="compare()" />
<p id="demo"></p>

Well, let's go step by step on this
1. How to submit a form
In HTML you have 2 ways of submitting a form:
Through an <input> tag with the type="submit" attribute (resulting in <input type="submit" />
Trough a <button> tag with the type="submit" attribute (resulting in <button type="submit">...content...</button>
Now when these buttons get clicked, they will trigger the <form>'s submit event.
2. How to subscribe to a form's submit event
As when submitting a form, there're (without any external libraries) 2 ways of subscribing to a form's submit event:
Directly setting a property on the form: formvar.onsubmit = function() { /* ... do stuff ... */ } (not really recommended as other plugins/scripts might overwrite this)
Adding an event listener: formvar.addEventListener("submit", function() { /* ... do stuff ... */ } (better than directly setting a property as this won't be removed when another script subscribes to the same event)
3. Comparing dates
Well, first you'd have to transform the dates from the string value you got from the textbox to a proper Date type:
date1 = Date.parse(date1.value);
date2 = Date.parse(date2.value);
And then with a simple arithmetic operator you can find out which one of them is the oldest:
var difference = date2 - date1;
if(difference > 0)
{
// Second person is the oldest
}
else if (difference < 0)
{
// First person is the oldest
}
else
{
// They are the same age
}

You don't need to submit the form to check the difference. A simple onclick function or click event listener will do.
You need to check if they are older, younger, or the same age. Try it below. You code wasn't working because you didn't have a name property for your dates. I switched them to use ids.
document.getElementById("theButton").addEventListener('click', checkOldest);
function checkOldest() {
var name1Value = document.getElementById("name1").value,
name2Value = document.getElementById("name2").value,
date1Value = document.getElementById("date1").value,
date2Value = document.getElementById("date2").value,
result = document.getElementById("result");
// make sure you have input for both birthdates and names
if (name1Value && name2Value && date1Value && date2Value) {
var dateOneComparedToTwo = new Date(date1Value) - new Date(date2Value);
if (dateOneComparedToTwo < 0) {
result.innerText = name1Value + ' is older than ' + name2Value + '!';
} else if (dateOneComparedToTwo > 0) {
result.innerText = name1Value + ' is younger than ' + name2Value + '!';
} else {
result.innerText = name1Value + ' and ' + name2Value + ' are the same age!';
}
} else {
result.innerText = "You need to fill out the form completely!";
}
}
<form id="form1">
Full name of first person: <input type="text" id="name1" name="name1"><br>
Birthday: <input type="date" id="date1" name="date1"><br>
<br>
Full name of second person: <input type="text" id="name2" name="name2"><br>
Birthday: <input type="date" id="date2" name="date2"><br>
<button id="theButton">Who's oldest?</button>
</form>
<p id="result">
Fill out the form please!
</p>

Related

How to split string of input tag HTML?

When a user enters the below link in an input tag, I just want the last part of the string, in order to minimize input mistakes - the two input fields generate a new link that the user can copy and use.
name:id:5icOoE6VgqFKohjWWNp0Ac (I just want the last '5icOoE6VgqFKohjWWNp0Ac' part)
Can anyone help me with amending the below to achieve this?
function generateFullName() {
document.getElementById('txtFullName').value = ('https://nlproducts.nl/item/') + document.getElementById('fName').value + ('?context=') + document.getElementById('lName').value;
}
Enter a product ID:
<input type="text" id="fName" placeholder='0A5gdlrpAuQqZ2iFgnqBFW' />
Enter a user ID:
<input type="text" id="lName" oninput="generateFullName()" placeholder='37i9dQZF1DXcBWIGoYBM5M'/><br/></p>
Tada! This would be the link for your campaign:
<input type="text" id="txtFullName" name="txtFullName" />
Here's a JavaScript function that takes a string as input, and formats it to only keep the last part after the last colon (if it contains a colon):
function parseColon(txt) {
return txt.split(":").slice(-1).pop();
}
Eg. parseColon("a:b:c") would return "c"
You can validate your inputs with:
function isValidInput(txt) {
numberOfColons = txt.split(":").length - 1;
if (txt.length == 32 && numberOfColons == 2)
return true
return false
}
In your code you can use these two functions to check & parse lName and fName like this:
function generateFullName() {
var lName_val = document.getElementById('lName').value;
var fName_val = document.getElementById('fName').value;
//fill in link in the output if fName and lName are valid inputs
if(isValidInput(fName_val) && isValidInput(lName_val))
document.getElementById('txtFullName').value = ('https://nlproducts.nl/item/') + parseColon(fName_val) + ('?context=') + parseColon(lName_val);
// otherwise, clear the output field
else
document.getElementById('txtFullName').value = "";
}
function parseColon(txt) {
// return the part after the last colon
return txt.split(":").slice(-1).pop();
}
function isValidInput(txt) {
numberOfColons = txt.split(":").length - 1;
if (txt.length == 38 && numberOfColons == 2)
return true
return false
}
Enter a product ID:<br>
<input type="text" id="fName" oninput="generateFullName()" placeholder='0A5gdlrpAuQqZ2iFgnqBFW' size="50"/><br/>
Enter a user ID:<br>
<input type="text" id="lName" oninput="generateFullName()" placeholder='37i9dQZF1DXcBWIGoYBM5M' size="50"/><br/><br/>
Tada! This would be the link for your campaign:<br>
<input type="text" id="txtFullName" name="txtFullName" size="50"/>

Setting values to fields with the same name/key possible?

Ok, say I have a checkbox such as this:
<input type="checkbox" value="1" class="discount_select" name="select[101132]">
...and 3 text fields like this:
<input type="text" name="start[101132]">
<input type="text" name="end[101132]">
<input type="text" name="discount[101132]">
I am running some code right now that will update the text field values if the checkbox is checked, however I'm not sure if or how you can target the correct fields as they all have different ID's.
So I basically have this code to loop through the checked boxes, but not sure how to make updates to the correct text fields:
// Get values
var discount = $('#apply_discount').val();
var start = $('#apply_start_date').val();
var end = $('#apply_end_date').val();
$('.discount_select:checked').each(function() {
// How can I target the correct fields/ID's here?
});
Try
// Get values
var discount = $('#apply_discount').val();
var start = $('#apply_start_date').val();
var end = $('#apply_end_date').val();
$('.discount_select:checked').each(function() {
var num = this.name.substring(7, this.name.length - 1);
$('input[name="start[' + num + ']"]').val(start)
$('input[name="end[' + num + ']"]').val(end)
$('input[name="discount[' + num + ']"]').val(discount)
});
Change the name and ids of your fields to make it simpler
<input type="checkbox" value="1" class="discount_select" id="101132" name="select_101132">
<input type="text" name="start_101132">
<input type="text" name="end_101132">
<input type="text" name="discount_101132">
Then:
var discount = $('#apply_discount').val();
var start = $('#apply_start_date').val();
var end = $('#apply_end_date').val();
$('.discount_select:checked').each(function() {
var select_id = this.attr("id");
$('[name=start_'+select_id+']').val(start);
$('[name=end_'+select_id+']').val(end);
$('[name=discount_'+select_id+']').val(discount);
});

Use user info without prompt or confirm?

All I want to do is be able to do is have users submit info and be able to use it - without using prompt.
I would like to have them be able to input and have a different box to be able to give them info based on there info. I.E. 81 is a great number.
var c = prompt("pick a number")
if(c>100){
console.log("110 is to high of a number")
}
This is what I have. I'm used to JavaScript editors and using console.log. I'm looking for a way to do that based on info I receive and be able to give feed back in a different <div> or whatever. Can anyone help?
<input type="text" name="fname" id="fname" />
<input type="text" name="lname" id="lname" />
<input type="submit" value="submit" />
function showConfirmationDialog() {
var textbox = document.getElementById('textbox');
var location = document.getElementById('location');
alert(textbox.value + '\n' + location.value);
}
<input type="button" value="submit" onclick="showConfirmationDialog();" />
If you're using jQuery, you can use a click handler that looks like this:
$('#someButton').click(function () {
var val = $('#inputFieldId').val();
var $outputDiv = $('#outputFieldId');
var msg = '';
if (! $.isNumeric(val)) {
msg = 'Please enter a valid number';
}
else if (parseInt(val, 10) > 100) {
msg = 'Enter number less than 100';
}
else {
msg = 'Thank you for the wonderful number: ' + val;
}
$outputDiv.text(msg);
}
Here's a fiddle that shows the above code in action.

jquery Datepicker date range validation

I have a field like Born date. I have used jquery datepicker to show the calender so that user can select the date.Now I have a problem.
In the the Born date field there is a option to choose between which opens two date picker fields like
Born Date -- Between--------- ---From------- And --To----------
Now the problem is if the user selects a date in 'To field' which is less than 'From field' and press the submit button it gets submitted. I need to prevent it from submitting and display appropriate message so the user enters right date .
Please Help.
Here is the code that i am using
<input id="borndate" class="dateISO" onchange="checkDate('borndate');">
</input>
<span id="span_borndate" style="display:none">
<input id="borndate" class="dateISO" onchange="checkDate('borndate');">
</span>
This is the Java script i am using
function checkdate(fieldname) {
var comparator = '#comp_' + fieldName;
var compVal = $(comparator).val();
Value = $('#' + fieldName).val();
var fromDate = jQuery.datepicker.parseDate('mm-dd-yy', Value, null);
Values = $('#' + fieldName + '-to').val();
var toDate = jQuery.datepicker.parseDate('mm-dd-yy', Values, null);
$('#span_' + fieldName).find('.error').remove();
if (compVal == "Between") {
if (toDate < fromDate) {
$('#span_' + fieldName).append("<label class='rangeError' generated='false'>Start date should come before end date</label>");
return false;
}
}
return true;
}
And this is the function which is called again while submitting
function validateforms() {
var valid = true;
$('//classnamefor table rows which includes the date td').each(function (index) {
fieldName = $(this).attr("name");
if ($('#' + fieldName).hasClass('dateISO')) {
valid = checkDate(fieldName);
}
}
return valid;
}
Try this
http://jqueryui.com/demos/datepicker/#date-range
and make the textboxes readonly='true'
<input type="text" id="from" name="from_date" value="" readonly="true"/>
<input type="text" id="to" name="to_date" value="" readonly="true"/>

How can I validate multiple different form fields, I have searched and searched for a week

How do I validate dd/mm/yyyy, numeric loan amount, alphabetic first, last name together. I am having trouble using this forum. Thanks for responding so fast!
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
<!--//
function validate(form){
var message = 'Please fill in the following fields:\n\n\t';
for(var i=0; i<form.elements.length; i++){
if(form.elements[i].value.length == 0){
message+= form.elements[i].name.toUpperCase()+'\n\t';
}
}
message+= '\nOK submit incomplete form';
message+= '\nCANCEL return to the form';
message = confirm(message);
if(!message){ return false };
else{ return true };
}
//-->
</script>
</head>
<body>
<form name="loanform" action="processform.htm" method="get" onsubmit="return validate(this)">
First Name: <input type="text" name="firstname" maxlength="15"><br>
Last Name: <input type="text" name="lastname" maxlength="15"><br>
Birth Date: <input type="text" name="birthdate" maxlength="8"><br>
Loan Amount: <input type="text" name="loanamount" maxlength="6" ><br>
Years: <input type="text" name="years" maxlength="2"><br>
<br>
<input type="reset" value="clear">
<input type="submit" value="submit">
</form>
</body>
</html>
You can use a function like this. It sets up a regular expression for each type of field and then makes a table that says which regular expression to use for which form element. It uses the named form elements to access the individual values.
function validate(form) {
var nameRE = /^[A-Za-z \.]+$/;
var dateRE = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
var amountRE = /^\$?[\d\.,]+$/;
var yearsRE = /^\d+$/;
var formItems = [
{name: "firstname", re: nameRE, tag: "First Name"},
{name: "lastname", re: nameRE, tag: "Last Name"},
{name: "birthdate", re: dateRE, tag: "Birth Date", isDate: true},
{name: "loanamount", re: amountRE, tag: "Loan Amount", min: 50000, max: 750000},
{name: "years", re: yearsRE, tag: "Years", min: 5, max: 30}
];
var item, val, num, month, day, year, valid, matches, incomplete = false;
var msg = 'Please fill in the following fields:\n\n\t';
for (var i = 0; i < formItems.length; i++) {
item = formItems[i];
// strip leading or trailing whitespace
var val = form[item.name].value.replace(/^\s+|\s+$/g, "");
form[item.name].value = val;
// see if it matches the regex
valid = item.re.test(val);
if (valid && item.isDate) {
matches = val.match(item.re);
month = parseInt(matches[1], 10);
day = parseInt(matches[2], 10);
year = parseInt(matches[3], 10);
if (month <= 0 || month > 12 ||
day <= 0 || day >= 31 ||
year < 1900 || year > 2020) {
valid = false;
}
}
if (!valid) {
incomplete = true;
msg += item.tag + '\n\t';
} else {
if (item.min && item.max) {
// clear out non-numeric chars
val = val.replace(/[,\$\s]/g, "");
// convert to a number
num = parseInt(val, 10);
// compare to min and max
if (num < item.min || num > item.max) {
incomplete = true;
msg += item.tag + " (must be between " + item.min + " and " + item.max + ")\n\t";
}
}
}
}
if (incomplete) {
msg += '\nOK submit incomplete form';
msg += '\nCANCEL return to the form';
return(confirm(msg));
}
return(true);
}
​
Working demo here: http://jsfiddle.net/jfriend00/GChEP/
A way to do would be to use classes to know what kind of validation you need for a given input. Also, you can use the title attribute to have a more human-friendly representiation of the input.
Your HTML would then look like:
<form name="loanform" action="processform.htm" method="get" onsubmit="return validate(this)">
First Name (text only): <input class="validate-text" title="First Name" type="text" name="firstname" maxlength="15"><br>
Last Name (text only): <input class="validate-text" title="Last Name" type="text" name="lastname" maxlength="15"><br>
Birth Date (format dd/mm/yyyy): <input class="validate-date" title="Birth Date" type="text" name="birthdate" maxlength="8"><br>
Loan Amount (US dollars, numeric only): <input class="validate-number" title="Loan Amount" type="text" name="loanamount" maxlength="6" ><br>
Years (numeric only): <input class="validate-number" title="Years" type="text" name="years" maxlength="2"><br>
<br>
<input type="reset" value="clear">
<input type="submit" value="submit">
</form>
And your JavaScript function (regular expressions seem to be the best way to go):
function validate(f) {
var message=new Array(); //will contain the fields that are misfilled
var reText=new RegExp("^[a-z \-'\.]+$", "i"); //a RegExp to match names: only letters, "-", "'" and "." allowed
var reDate=new RegExp("^[0-9]{2}/[0-9]{2}/[0-9]{4}$"); //a RegExp to match a date in the format dd/mm/yyyy
var reNumber=new RegExp("^[0-9]+$"); //a RegExp to match a number
for(var e in f.elements) { //loop on every input of the form
var test=null; //set or reset the RegExp to use for the current input
var input=f.elements[e]; //assign the input to a var (easier to type, not needed)
if(!input.className) //if this input doesn't have any class declared
continue; //then we skip the rest of the loop to keep going with the next input
var classes=input.className.split(" "); //maybe the input has several classes, so we split them in a "classes" array
for(var c in classes) { //we loop on every class of the current input
switch(classes[c]) { //and we test if the current class of the current input is one of the classes we're interested in
case "validate-text": //if it is a text
test=reText; //the variable "test" will contain the RegExp we want to use
break;
case "validate-date": //same for a date
test=reDate;
break;
case "validate-number": //and same for a number
test=reNumber;
break;
default: //if the class is not something we want, nothing to do
break;
} //end switch
} //end classes loop
//here test is either null (no "validate-something" class found for the current input), or it contains the RegExp telling us the kind of input we must validate.
if(test!=null && !input.value.match(test)) { //if it is not null and if the input's value does not match the RegExp
message.push(input.title); //we add the field to the "message" array
}
} //end input loop
if(message.length>0) { //if the arary is not empty, we display a confirm box
return confirm("Please correctly fill the following field(s), or click OK to send an incomplete form:\n"+message.join("\n"));
}
//otherwise, the form is correctly filled, we return true to submit the form
return true;
}

Categories