how to update the form field automatically - javascript

I am developing a task management system in that i am having the age field in registration form i am having doubt about how to update the field automatically when i click.
my script is
<script>
var a = document.age1.dob.value;
age = a.getFullYear();
var curr = new Date();
year = curr.getFullYear();
var age1 = year - age;
</script>
i calculated the age and stored it in age1 variable.
<form id="form2" action="#" method="post" name="age1">
<h4><b>Register here</b></h4>
<b>Name</b>: <input type="text" name="name" required="required" placeholder="Your name" pattern="[a-zA-Z0-9\s]+"><br><br>
<b>E-mail</b>: <input type="email" name="email" required="required" placeholder="someone#example.com" pattern="[a-z0-9._+%-]+#[a-z0-9.-]+\.[a-z]{2,4}$"><br><br>
<b>Password</b>: <input type="password" name="password" required="required"><br><br>
<b>DOB</b>: <input type="text" name="dob" required placeholder="dd/mm/yyyy" pattern="^[0-3]?[0-9].[0-3]?[0-9].(?:[0-9]{2})?[0-9]{2}$"><br><br>
<b>Age</b>: <input type="text" name="age" id="age2"><br><br>
<b>Address</b>: <textarea name="address" rows="6" cols="30"></textarea>
<button id="butr" type="submit" class="btn btn-warning">Signup</button>
After i input my DOB in the registration form and click the age field i want the calculated age that i stored it in age1 variable to automatically update the value in age field that i have it in my registration form

Add an onchange function to dob field
<input type="text" onchange="ageCalculation()" name="dob">
Add this code in your <script>
function ageCalculation(){
if(document.age1.dob.value!==""){
var a = document.age1.dob.value;
a=new Date(a);
age = a.getFullYear();
var curr = new Date();
year = curr.getFullYear();
var age1 = year - age;
document.age1.age.value=age1;
}
}

Related

HTML - Input text pattern/required attributes conflict with submission

This simple form is part of a larger web app I have created. Both the required attributes and the pattern attributes only work intermittently. Changing the event listener to "submit" rather than "click" makes the form validation work properly, but then I get a blank page when I submit with the proper input formatting.
var v = "userForm"
document.getElementById("clockIn").addEventListener("click", addLine); //CHANGE TO CLICK FOR WORKING PAGE BUT PATTERN WONT WORK
function addLine() {
//e.preventDefault();
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
var jobNumber = document.getElementById("jnum").value;
var process = document.querySelector('input[name="operation"]:checked').value;
var comment = document.getElementById("comment").value;
var timeIn = new Date().toLocaleString();
var info = [firstName, lastName, jobNumber, process, timeIn, comment];
google.script.run.addEntry(info);
document.getElementById("fname").value = "";
document.getElementById("lname").value = "";
document.getElementById("jnum").value = "";
document.getElementById("comment").value = "";
document.querySelector('input[name="operation"]:checked').checked = false;
alert("Submitted");
}
function addEntry(info) {
var ssid = "1E81r5Xy**********************W1o4Q";
var ss = SpreadsheetApp.openById(ssid);
var oj = ss.getSheetByName("Open Jobs");
var FileIterator = DriveApp.getFilesByName("Drawings & Links");
while (FileIterator.hasNext()) {
var file = FileIterator.next();
if (file.getName() == "Drawings & Links") {
// var Sheet = SpreadsheetApp.open(file);
var dlid = file.getId();
}
}
var drawingLinks = SpreadsheetApp.openById(dlid);
var dl = drawingLinks.getSheetByName("Sheet1");
Logger.log(dlid)
oj.appendRow(info);
}
<form id="inputForm">
<h2 class="subHead">
Enter Basic Information
</h2>
<label for="fname" class="form">First name:</label><br><br>
<input type="text" id="fname" name="fname" size="25" style="font-size:25px;" placeholder="John" required><br><br>
<label for="lname" class="form">Last name:</label><br><br>
<input type="text" id="lname" name="lname" size="25" style="font-size:25px;" placeholder="Doe" required><br><br>
<label for="jnum" class="form">Job number:</label><br><br>
<input type="text" id="jnum" name="jnum" size="25" style="font-size:25px;" pattern="[A-Z]-[0-9]{4}" placeholder="A-1234" required><br>
<h2 class="subHead">
Select Operation
</h2>
<div>
<label for="cut" class="form">Cut</label>
<input type="radio" id="cut" name="operation" value="cut" required><br><br>
<label for="drill" class="form">Drill</label>
<input type="radio" id="drill" name="operation" value="drill" required><br><br>
<label for="fitup" class="form">Fit Up</label>
<input type="radio" id="fitup" name="operation" value="fit up" required><br><br>
<label for="weld" class="form">Weld</label>
<input type="radio" id="weld" name="operation" value="weld" required><br>
</div>
<h2 class="subHead">
Enter Comments
</h2>
<input type="text" id="comment" size="25" style="font-size:25px;" placeholder="Optional"><br>
<br>
<input type="submit" id="clockIn" class="button" value="Clock In">
</form>
Thanks for the help.
I think I have narrowed the problem down to something to do with the event listener. My thought is that when the "click" event is used, the function runs before the fields are validated by the browser. Yet, I just get a blank page if I use the "submit" event. The function "addEntry" doesn't appear to run; the logged data doesn't appear. Same goes for "addLine" when I add an alert. I have isolated the regex code and verified it works as expected.
Edit: I found that when I remove the event listener on the submit button and add an onsubmit (onsubmit="addLine()") attribute to the form, the alert in "addLine" appears. The "Submitted" alert also appears. Still a blank page after.
Your validation fails but that is outside the scope of the question as I see it since you need to check the actual values before you let it submit and probably need a preventDefault() on the form if any fail.
You get an error because you cannot filter by :checked unless you then determine if that is null OR filter it after you get the nodeList.
Here I show a couple of ways to handle the radio buttons; up to you to determine which suits you.
var v = "userForm"
document.getElementById("clockIn").addEventListener("click", addLine); //CHANGE TO CLICK FOR WORKING PAGE BUT PATTERN WONT WORK
function addLine() {
//e.preventDefault();
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
var jobNumber = document.getElementById("jnum").value;
//demonstrate a few ways to hanlde the radio buttons:
const procOne = document.querySelector('input[name="operation"]:checked');
console.log(!!procOne ? procOne.value : procOne, typeof procOne); // null and object if none are checked
let processValue = procOne === null && typeof procOne === "object" ? "" : procOne.value;
// querySelectorAll to get all of them so we can filter the list
const processAll = document.querySelectorAll('input[name="operation"]');
// creates an array like object of the nodelist; then filters it for checked ones
const checkProcess = [...processAll].filter(item => item.checked);
console.log("How many?:", processAll.length);
console.log("How many checked?:", checkProcess.length);
console.log(checkProcess.length ? checkProcess.value : "nothing");
// anther way to get value:
processValue = checkProcess.length ? checkProcess.value : "nothing"
if (checkProcess.length !== 0) { //Test if something was checked
console.log(checkProcess.value); // the value of the checked.
} else {
console.log('Nothing checked'); // nothing was checked.
}
var comment = document.getElementById("comment").value;
var timeIn = new Date().toLocaleString();
let process = processValue;
var info = [firstName, lastName, jobNumber, process, timeIn, comment];
//ccommented out as google is not defined
//google.script.run.addEntry(info);
// hitting the DOM again is not a great thing here but left as not part of the question/issue
document.getElementById("fname").value = "";
document.getElementById("lname").value = "";
document.getElementById("jnum").value = "";
document.getElementById("comment").value = "";
// cannot filter by :checked if none are so check first and set to false
if (procOne != null) procOne.checked = false;
alert("Submitted");
}
function addEntry(info) {
var ssid = "1E81r5Xy**********************W1o4Q";
var ss = SpreadsheetApp.openById(ssid);
var oj = ss.getSheetByName("Open Jobs");
var FileIterator = DriveApp.getFilesByName("Drawings & Links");
while (FileIterator.hasNext()) {
var file = FileIterator.next();
if (file.getName() == "Drawings & Links") {
// var Sheet = SpreadsheetApp.open(file);
var dlid = file.getId();
}
}
var drawingLinks = SpreadsheetApp.openById(dlid);
var dl = drawingLinks.getSheetByName("Sheet1");
Logger.log(dlid)
oj.appendRow(info);
}
<form id="inputForm">
<h2 class="subHead">
Enter Basic Information
</h2>
<label for="fname" class="form">First name:</label><br><br>
<input type="text" id="fname" name="fname" size="25" style="font-size:25px;" placeholder="John" required><br><br>
<label for="lname" class="form">Last name:</label><br><br>
<input type="text" id="lname" name="lname" size="25" style="font-size:25px;" placeholder="Doe" required><br><br>
<label for="jnum" class="form">Job number:</label><br><br>
<input type="text" id="jnum" name="jnum" size="25" style="font-size:25px;" pattern="[A-Z]-[0-9]{4}" placeholder="A-1234" required><br>
<h2 class="subHead">
Select Operation
</h2>
<div>
<label for="cut" class="form">Cut</label>
<input type="radio" id="cut" name="operation" value="cut" required><br><br>
<label for="drill" class="form">Drill</label>
<input type="radio" id="drill" name="operation" value="drill" required><br><br>
<label for="fitup" class="form">Fit Up</label>
<input type="radio" id="fitup" name="operation" value="fit up" required><br><br>
<label for="weld" class="form">Weld</label>
<input type="radio" id="weld" name="operation" value="weld" required><br>
</div>
<h2 class="subHead">
Enter Comments
</h2>
<input type="text" id="comment" size="25" style="font-size:25px;" placeholder="Optional"><br>
<br>
<input type="submit" id="clockIn" class="button" value="Clock In">
</form>

How do i get a send button to only submit and write to its own inputField?

I'm a beginner and I'm now stuck trying to figure out two things for the below code:
How do I code so that each of the send buttons only connects to its own input field?
How do I code so that each new text input overwrites the previous?
My code:
<h1>Data input</h1>
<input type="text" placeholder="Last name" id="inputField1" name="lastName" required>
<input type="button" value="Send" id="myButton1">
<br>
<br>
<input type="text" placeholder="First name" id="inputField2" name="firstName" required>
<input type="button" value="Send" id="myButton2">
<br>
<br>
<p id="lastName">Last name</p>
<p id="firstName">First name</p>
<script>
var b1=document.getElementById("myButton1")
b1.addEventListener("click", handleClick);
var b2=document.getElementById("myButton2")
b2.addEventListener("click", handleClick);
function handleClick(){
var i=document.getElementById("inputField1");
var iValue=i.value;
var d=document.getElementById("lastName");
var oldText=d.innerText;
var newText=oldText+"\n"+iValue;
d.innerText=newText;
var k=document.getElementById("inputField2");
var kValue=k.value;
var f=document.getElementById("firstName");
var oldText=f.innerText;
var newText=oldText+"\n"+kValue;
f.innerText=newText;
}
Here is a solution that sends a 1 or a 2 to the handleClick function as a parameter depending on which button you click. It then gets the value of the input that matches the number, checks to make see if it is empty, and outputs the name to the correct paragraph if it isn't and an error message if it is. Let me know if you have any problems with it.
var b1 = document.getElementById("myButton1");
b1.addEventListener("click", () => handleClick("1"));
var b2 = document.getElementById("myButton2");
b2.addEventListener("click", () => handleClick("2"));
function handleClick(iNum){
var i = document.getElementById("inputField" + iNum);
var iValue = i.value;
var d = document.getElementById("name" + iNum);
if (iValue != "") {
var pText = (iNum == "1" ? "Last" : "First");
var newText = pText + " name: " + iValue;
d.textContent = newText;
} else {
d.textContent = "Please enter a name!";
}
}
<h1>Data input</h1>
<input type="text" placeholder="Last name" id="inputField1" name="lastName" required>
<input type="button" value="Send" id="myButton1">
<br>
<br>
<input type="text" placeholder="First name" id="inputField2" name="firstName" required>
<input type="button" value="Send" id="myButton2">
<br>
<br>
<p id="name1"></p>
<p id="name2"></p>
Not really sure what's going on here, but usually you have to access the input field via the event: event.target.value (just put event as a parameter)

show result which is created through JavaScript in input field

I have a form in which a date/time picker is working fine.
I created JavaScript to calculate the two fields' date difference and show in a third field - named Course Duration.
Somehow I am not able to display the results in the "Course Duration" input Field.
Code:
function GetDays() {
var dropdt = new Date(document.getElementById("course_end_date").value);
var pickdt = new Date(document.getElementById("admission_date").value);
return parseInt((dropdt - pickdt) / (24 * 3600 * 1000));
}
function cal() {
if (document.getElementById("course_end_date")) {
document.getElementById("course_duration").value = GetDays();
}
}
<input id="admission_date" name="admission_date" placeholder="" type="text" class="form-control" value="" />
<input id="course_end_date" name="course_end_date" placeholder="" type="text" class="form-control" value="" />
<input id="course_duration" name="course_duration" placeholder="" type="text" class="form-control" value="" />
You need something to trigger the cal() function, which currently you don't have.
So I made a demo below which has a "Calculate" button. Enter your dates and then press the button, and it will run the calculation. As long as you enter valid dates, it should work.
For example, if you enter 2018-02-01 and 2018-02-02 it will return 366.
var calcButton = document.getElementById("calculate");
calcButton.addEventListener("click", cal);
function GetDays() {
var dropdt = new Date(document.getElementById("course_end_date").value);
var pickdt = new Date(document.getElementById("admission_date").value);
return parseInt((dropdt - pickdt) / (24 * 3600 * 1000));
}
function cal() {
if (document.getElementById("course_end_date")) {
document.getElementById("course_duration").value = GetDays();
}
}
<input id="admission_date" name="admission_date" placeholder="" type="text" class="form-control" value="" />
<input id="course_end_date" name="course_end_date" placeholder="" type="text" class="form-control" value="" />
<button id="calculate" type="button">Calculate</button>
<input id="course_duration" name="course_duration" placeholder="" type="text" class="form-control" value="" />

Store HTML form to variable

I have an HTML form and I'm wondering how I can set that info when submitted to the variables in my js file.
HTML
<input id="column-left" type="text" name="first-name" placeholder="First Name"/>
<input id="column-right" type="text" name="last-name" placeholder="Last Name"/>
<input id="input-field" maxlength="16" type="text" name="number" placeholder="Card Number"/>
<input id="column-left" maxlength="4" type="text" name="expiry" placeholder="MM / YY"/>
<input id="column-right" maxlength="3" type="text" name="cvc" placeholder="CCV"/>
(Leaving out unimportant info)
JS
var order_info = {name: "your name", // your first and last name
email: "your#email.com", // your email
phone: "5555555555", // your phone number
address1: "123 street lane", // your street address
address2: "apartment 1", // leave blank if you dont have one
zip_code: "00000", // your zip code
city: "New York", // city
state_code: "NY", // state code, if you dont know this then look it up son
country: "USA" // only two options, "USA" or "CANADA"
};
I need to set the info from the form into these fields.
One of many ways to get values from html form tag to Javascript object.
document.querySelector("#myForm").addEventListener("keyup", function(){
var data = {};
var inputs = document.querySelectorAll('input');
inputs.forEach(input => {
data[input.name] = input.value;
});
document.querySelector("#text").innerText = JSON.stringify(data);
});
document.querySelector("#myForm").dispatchEvent(new Event('keyup'));
<form id="myForm">
<input value="Niklesh" type="text" name="first_name" placeholder="First Name"/>
<input value="Raut" type="text" name="last_name" placeholder="First Name"/>
<input value="" type="text" name="email" placeholder="Email"/>
<div id='text'></div>
</form>
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var card = document.getElementById("card").value;
var expire = document.getElementById("expire").value;
var cvc = document.getElementById("cvc").value;
var order_info = {
fname: fname ? fname : '',
lname: lname ? lname : '',
card: card ? card : '',
expire: expire ? expire : '',
cvc: cvc ? cvc: ''
}
console.log(order_info);
<input id="fname" type="text" name="first-name" value="sourav" placeholder="First Name"/>
<input id="lname" type="text" name="last-name" value="singh" placeholder="Last Name"/>
<input id="card" maxlength="16" type="text" name="number" value="" placeholder="Card Number"/>
<input id="expire" maxlength="4" type="text" name="expiry" value="08/12" placeholder="MM / YY"/>
<input id="cvc" maxlength="3" type="text" name="cvc" value="111" placeholder="CCV"/>
First you should define a unique ID to each input you have, then get the value of this ID using javascript document.getElementById('ID').value or using jQuery $('ID').val().
Second part, you must match your number of inputs with your array.
Now you have an array of data, do what ever you want to do with it.
document.getElementById("save").addEventListener("click", function() {
var order_info = {
firstName: document.getElementById('first-name').value,
lastName: document.getElementById('last-name').value,
number: document.getElementById('number').value,
expiry: document.getElementById('expiry').value,
cvc: document.getElementById('cvc').value,
};
console.log(order_info);
});
<input id="first-name" type="text" name="first-name" placeholder="First Name"/>
<input id="last-name" type="text" name="last-name" placeholder="Last Name"/>
<input id="number" maxlength="16" type="text" name="number" placeholder="Card Number"/>
<input id="expiry" maxlength="4" type="text" name="expiry" placeholder="MM / YY"/>
<input id="cvc" maxlength="3" type="text" name="cvc" placeholder="CCV"/>
<button id="save">Save Data</button>
if you want to serialise data;
var order_info = $('form').serializeArray();
if you want to use formdata :
var fd = new FormData();
var order_info = $('form').serializeArray();
$.each(order_info,function(key,input){
fd.append(input.name,input.value);
});
Using the DOM (Document Object Model) you can access the values of the HTML components.
For example, given your code, you can lookup the element by its "id":
var lastname = document.getElementById("column-right");
var cardnumber = document.getElementById("input-field");
... etc
You can also lookup the element by using the value of its "name" attribute:
var lastname = document.getElementsByName("last-name");
var cardnumber = document.getElementsByName("number");
Tip: You normally do this when the page is loaded (event "onload") and if the values are received by the same page, it needs to implement typically the scenario of the first load as well (where the values are null, not initialized).
Javascript references:
https://www.w3schools.com/jsref/met_doc_getelementsbyname.asp
https://www.w3schools.com/jsref/met_document_getelementbyid.asp
You can use JQuery .serializeArray() method to do so.
like this:
var x = $("form").serializeArray();
You should get Key:Value pairs of all the text fields and their values by doing so.

Calling function to work

I'm new to JavaScript and I need to use the string method all in one html page. I need to make sure user input the data, but I can't get my function calling to work. Any idea? I finished all of it, but just to make sure that one button submit can validate all string method function perfectly.
This is my HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset ="utf-8"/>
<h1> Try 1</h1>
<p>Please enter all the field below.</p>
</head>
<body>
<form id="myForm">
<fieldset>
<legend>String Methods</legend>
<p>Using concat()</p>
<input type="text" id="word1" size="25" placeholder="Enter first word/sentences."></br>
<input type="text" id="word2" size="25" placeholder="Enter second word/sentences."></br></br>
<p>Using substr()</p>
<input type="text" id="subtr" size="25" placeholder="Please enter word/sentences."></br></br>
<p>Using lastIndexOf()</p>
<input type="text" id="lastindex" size="25" placeholder="Please enter word/sentences."></br>
<input type="text" id="srch" size="25" placeholder="Word that you want to search."></br></br>
<p>Using toLowerCase()</p>
<input type="text" id="lcase" size="35" placeholder="Please enter Uppercase word/sentences."></br></br>
<p>Using toUpperCase()</p>
<input type="text" id="ucase" size="35" placeholder="Please enter Lowercase word/sentences."></br></br>
<p>Using match()</p>
<input type="text" id="match" size="25" placeholder="Please enter word/sentences."></br>
<input type="text" id="match1" size="25" placeholder="Words that you want to find match."></br></br>
<p>Using replace()</p>
<p id="phrase"><i>The voice in my head shouts out through the world like a breath.</i></p>
<input type="text" id="replce" size="35" placeholder="Word you want to change in sentence above."></br>
<input type="text" id="replce2" size="25" placeholder="Word you want to change with."></br></br>
<p>Using split()</p>
<input type="text" id="splt" size="25" placeholder="Please enter word/sentences."></br></br>
<p>Using charCodeAt()</p>
<input type="text" id="cca" size="25" placeholder="Please enter word/sentences."></br></br>
<p>Using slice()</p>
<input type="text" id="slce" size="25" placeholder="Please enter word/sentences."></br></br>
<input type="submit" value="Submit" id="btnSubmit" onclick="validateEverything()">
</fieldset>
</form>
<div id="answers"></div>
</body>
</html>
This is my JavaScript code:
<script>
function validateEverything(){
var wo1 = document.getElementById("word1").value;
var wo2 = document.getElementById("word2").value;
var sub = document.getElementById("subtr").value;
var lin = document.getElementById("lastindex").value;
var sea = document.getElementById("srch").value;
var lca = document.getElementById("lcase").value;
var uca = document.getElementById("ucase").value;
var mat = document.getElementById("match").value;
var ma1 = document.getElementById("match1").value;
var phr = document.getElementById("phrase").value;
var rep = document.getElementById("replce").value;
var re1 = document.getElementById("replce1").value;
var ph1 = document.getElementById("phrase1").value;
var spl = document.getElementById("splt").value;
var cha = document.getElementById("cca").value;
var slc = document.getElementById("slce").value;
var ans = document.getElementById("answers");
//Concat
var con = wo1.concat(" "+wo2);
//Subtr
var subr = sub.substring(1, 7);
//lastindexof
var n = lin.lastIndexOf(sea);
//toLowerCase
var lc = lca.toLowerCase();
//toUpperCase
var uc = uca.toUpperCase();
//match
var mc = mat.match(ma1);
//replace
var rp = phr.replace(replce, replce1);
//split
var sp = sp1.split(" ")
//charCodeAt
var cc = cha.charCodeAt(0);
//slice
var sl = slc.slice(1, 5);
show();
}
function show(){
ans.innerHTML = answersHTML();
}
//answers
function answersHTML(){
var ans = document.getElementById("answers").innerHTML;
document.write(con);
document.write(subr);
document.write(n);
document.write(lc);
document.write(uc);
document.write(mc);
document.write(rp);
document.write(sp);
document.write(cc);
document.write(sl);
}
</script>
There are multiple issues in your snippet.In some case there is no DOM element present but still you are doing document.getElementById();
Also how answerHTML will know about con,sub,.... ? They are local to validateEverything function & you are not passing it to answerHTML function
You are using input type = "submit". You need to use event.preventDefault() to stop submission. You are not submitting anything. Rather use input type = "button"
There is also no use of show() function
Everytime you are using document.write, so it will delete anything which is previously written. Instead string concatenation and innerHTML will be fine.
Here is a working snippet with minimum code.
JS
function validateEverything(event){
event.preventDefault();
var wo1 = document.getElementById("word1").value;
var wo2 = document.getElementById("word2").value;
var sub = document.getElementById("subtr").value;
var ans = document.getElementById("answers");
//Concat
var con = wo1.concat(" "+wo2);
//Subtr
var subr = sub.substring(1, 7);
ans.innerHTML = con+" "+subr;
}
HTML
<input type="submit" value="Submit" id="btnSubmit" onclick="validateEverything(event)">
JSFIDDLE

Categories