enabling submit btn after filling form (all inputs) with javascript no jquery - javascript

I am trying to create a form that the submit btn is disabled untill all (except for one) of the fields are filled.
this is the html:
<section id="contacSection">
<form id="contactForm">
<fieldset id="contactSection">
<legend>Your contact information</legend>
<label for="FirstName">First Name</label>
<input type="text" id="FirstName" name="FirstName" placeholder="First Name" required>
<label for="LastName">Last Name</label>
<input type="text" id="LastName" name="LastName" placeholder="Last Name">
<label for="email">E-mail</label>
<input type="email" id="email" name="email" placeholder="example#gmail.com" required>
<label for="comments">Comment</label>
<textarea type="text" id="comments" name="comments" placeholder="Don't be shy, drop a comment here!" required></textarea>
</fieldset>
<fieldset>
<legend>Would you like to meet for?</legend>
<div class="radiobtn">
<input type="radio" id="meetingtype1" name=meetingtype value="coffee" checked> A coffee</input>
<input type="radio" id="meetingtype2" name=meetingtype value="zoom"> A zoom meeting</input>
<input type="radio" id="meetingtype3" name=meetingtype value="drive"> A drive to Eilat</input>
<input type="radio" id="meetingtype4" name=meetingtype value="chef"> A chef meal</input>
</div>
</fieldset>
<button id="submitform" type="submit" >Submit</button>
</form>
</section>
this is the js:
const firstName = document.querySelector('#FirstName');
const lastName = document.querySelector('#LastName');
const email = document.querySelector('#email');
const comments = document.querySelector('#comments');
const submitform = document.querySelector('#submitform');
const contactForm = document.querySelector('#contactForm');
submitform.disabled = true;
contactForm.addEventListener('keyup', function (){
var ins = document.getElementsByTagName("INPUT");
var txs = document.getElementsByTagName("TEXTAREA");
var filled = true;
for(var i = 0; i < txs.length; i++){
if(txs[i].value === "")
filled = false;
}
for(var j = 0; j < ins.length; j++){
if(ins[j].value === "")
filled = false;
}
submitform.disabled = filled;
});
first, it takes a few seconds until the btn becomes disabled. secondly, after I fill any field the btn becomes enabled.
thank you!

Disregarding the comments and the radio buttons and focusing on the main issue, try changing the second half of the code to:
submitform.disabled = true;
contactForm.addEventListener('keyup', function() {
var ins = document.getElementsByTagName("INPUT");
filled = []
for (var j = 0; j < ins.length; j++) {
if (ins[j].value === "")
filled.push(false);
else {
filled.push(true)
}
}
if (filled.includes(false) === false) {
submitform.disabled = false
};
});
and see if it works.

The reason it becomes enabled when you input something is because you are setting
submitform.disabled = filled
At the start, filled is set to true which is why the button is disabled. However, once you type something in any input, you set filled to false which enables the button (submitform.disabled = false).
There's a lot of ways to go about this but here's one. It increments a counter when ever something is filled in. Then you check if that counter is the same as the amount of inputs and textareas.
Secondly, we set the button to be disabled at the very start so even if you remove text from an input, the button will be disabled again if it wasn't
const firstName = document.querySelector('#FirstName');
const lastName = document.querySelector('#LastName');
const email = document.querySelector('#email');
const comments = document.querySelector('#comments');
const submitform = document.querySelector('#submitform');
const contactForm = document.querySelector('#contactForm');
submitform.disabled = true;
contactForm.addEventListener('keyup', function (){
var ins = document.getElementsByTagName("INPUT");
var txs = document.getElementsByTagName("TEXTAREA");
var amountFilled = 0
submitform.disabled = true
for(var i = 0; i < txs.length; i++){
if(txs[i].value !== "") {
amountFilled += 1
}
}
for(var j = 0; j < ins.length; j++){
if(ins[j].value !== "") {
amountFilled += 1
}
}
if (amountFilled === ins.length + txs.length) {
submitform.disabled = false
}
});
<section id="contacSection">
<form id="contactForm">
<fieldset id="contactSection">
<legend>Your contact information</legend>
<label for="FirstName">First Name</label>
<input type="text" id="FirstName" name="FirstName" placeholder="First Name" required>
<label for="LastName">Last Name</label>
<input type="text" id="LastName" name="LastName" placeholder="Last Name">
<label for="email">E-mail</label>
<input type="email" id="email" name="email" placeholder="example#gmail.com" required>
<label for="comments">Comment</label>
<textarea type="text" id="comments" name="comments" placeholder="Don't be shy, drop a comment here!" required></textarea>
</fieldset>
<fieldset>
<legend>Would you like to meet for?</legend>
<div class="radiobtn">
<input type="radio" id="meetingtype1" name=meetingtype value="coffee" checked> A coffee</input>
<input type="radio" id="meetingtype2" name=meetingtype value="zoom"> A zoom meeting</input>
<input type="radio" id="meetingtype3" name=meetingtype value="drive"> A drive to Eilat</input>
<input type="radio" id="meetingtype4" name=meetingtype value="chef"> A chef meal</input>
</div>
</fieldset>
<button id="submitform" type="submit" >Submit</button>
</form>
</section>

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>

Why the output from javascript just shown for a short period of time?

I am developing a Registration form for my assignment. All things are working but when I click on the submit button, the warning messages on the label are just shown for a very short period of time. I am using eclipse and apache tomacat. here is my code.
JSP Code:
<form method="post">
<h2>Welcome to AP Auctions. Please Enter Bid</h2>
<span id="msg" style="color:red;font-size:25px"></span><br/>
<label id="itemid_l">Item Id:</label> <input type="text" name="itemid" id="itemid"/><br/>
<label id="itemname_l">Item Name:</label> <input type="text" name="itemname" id="itemname"/><br/>
<label id="uname_l">Your Name:</label> <input type="text" name="uname" id="uname"/><br/>
<label id="email_l">Your Email Address:</label> <input type="text" name="email" id="email"/><br/>
<label id="amount_l">Amount Bid:</label> <input type="number" name="amount" id="amount"/><br/>
<label id="autoincrement_l">Auto-increment to match other bidders:</label><input type="checkbox" name="autoincrement" id="autoincrement"><br/>
<input type="submit" value="Submit Bid" onclick="validate()"/>
</form>
Javascript Code:
function validate()
{
var itemid=document.getElementById("itemid").value;
var itemname=document.getElementById("itemname").value;
var uname=document.getElementById("uname").value;
var email=document.getElementById("email").value;
var amount=document.getElementById("amount").value;
var autoincrement=document.getElementById("autoincrement");
var flag=true;
if(itemid.length==0){
flag=false;
document.getElementById("itemid_l").innerHTML="<b>Required field!</b> Item Id: ";
}
if(itemname.length==0){
flag=false;
document.getElementById("itemname_l").innerHTML="<b>Required field!</b> Item Name: ";
}
if(uname.length==0){
flag=false;
document.getElementById("uname_l").innerHTML="<b>Required field!</b> Your Name: ";
}
if(email.length==0){
flag=false;
document.getElementById("email_l").innerHTML="<b>Required field!</b> Your Email Address: ";
}
if(amount.length==0){
flag=false;
document.getElementById("amount_l").innerHTML="<b>Required field!</b> Amount Bid: ";
}
if(!autoincrement.checked){
flag=false;
document.getElementById("autoincrement_l").innerHTML="<b>Required field!</b> Auto-increment to match other bidders:: ";
}
if(flag==true){
alert('Good job!!');
return true;
}
else
{
document.getElementById("msg").innerHTML="Required data is missing. Please fill";
return false;
}
}
Any suggestion will help me a lot..
You can use onsubmit event so that whenever user click on submit button this gets call and if the function validate() return true form will get submitted else it will not submit form .
Demo code :
function validate() {
var itemid = document.getElementById("itemid").value;
var itemname = document.getElementById("itemname").value;
var uname = document.getElementById("uname").value;
var email = document.getElementById("email").value;
var amount = document.getElementById("amount").value;
var autoincrement = document.getElementById("autoincrement");
var flag = true;
if (itemid.length == 0) {
flag = false;
document.getElementById("itemid_l").innerHTML = "<b>Required field!</b> ";
} else {
//if fill remove error any
document.getElementById("itemid_l").innerHTML = ""
}
if (itemname.length == 0) {
flag = false;
document.getElementById("itemname_l").innerHTML = "<b>Required field!</b> ";
} else {
//if fill remove error any
document.getElementById("itemname_l").innerHTML = "";
}
if (uname.length == 0) {
flag = false;
document.getElementById("uname_l").innerHTML = "<b>Required field!</b> ";
} else {
document.getElementById("uname_l").innerHTML = "";
}
if (email.length == 0) {
flag = false;
document.getElementById("email_l").innerHTML = "<b>Required field!</b> ";
} else {
document.getElementById("email_l").innerHTML = "";
}
if (amount.length == 0) {
flag = false;
document.getElementById("amount_l").innerHTML = "<b>Required field!</b>";
} else {
document.getElementById("amount_l").innerHTML = "";
}
if (!autoincrement.checked) {
flag = false;
document.getElementById("autoincrement_l").innerHTML = "<b>Required field!</b>";
} else {
document.getElementById("autoincrement_l").innerHTML = "";
}
if (flag == true) {
document.getElementById("msg").innerHTML = "";
alert('Good job!!');
flag = true; //do true
} else {
document.getElementById("msg").innerHTML = "Required data is missing. Please fill";
flag = false; //do false
}
return flag; //return flag
}
<!--add onsubmit -->
<form method="post" id="forms" onsubmit="return validate()">
<h2>Welcome to AP Auctions. Please Enter Bid</h2>
<span id="msg" style="color:red;font-size:25px"></span><br/>
<!--give id to span instead of label-->
<label> <span id="itemid_l"></span>Item Id:</label> <input type="text" name="itemid" id="itemid" /><br/>
<label><span id="itemname_l"></span>Item Name:</label> <input type="text" name="itemname" id="itemname" /><br/>
<label><span id="uname_l"></span>Your Name:</label> <input type="text" name="uname" id="uname" /><br/>
<label><span id="email_l"></span>Your Email Address:</label> <input type="text" name="email" id="email" /><br/>
<label><span id="amount_l"></span>Amount Bid:</label> <input type="number" name="amount" id="amount" /><br/>
<label><span id="autoincrement_l"></span>Auto-increment to match other bidders:</label><input type="checkbox" name="autoincrement" id="autoincrement"><br/>
<input type="submit" value="Submit Bid" />
</form>
Also , if you just need to check for empty field you can just use required attribute on input tag like below :
<form method="post">
<h2>Welcome to AP Auctions. Please Enter Bid</h2>
<span id="msg" style="color:red;font-size:25px"></span><br/>
<!--added required attribute-->
<label id="itemid_l">Item Id:</label> <input type="text" name="itemid" id="itemid" required/><br/>
<label id="itemname_l">Item Name:</label> <input type="text" name="itemname" id="itemname" required/><br/>
<label id="uname_l">Your Name:</label> <input type="text" name="uname" id="uname" required/><br/>
<label id="email_l">Your Email Address:</label> <input type="text" name="email" id="email" required/><br/>
<label id="amount_l">Amount Bid:</label> <input type="number" name="amount" id="amount"required/><br/>
<label id="autoincrement_l">Auto-increment to match other bidders:</label><input type="checkbox" name="autoincrement" id="autoincrement" required><br/>
<input type="submit" value="Submit Bid"/>
</form>

Checkbox checked input required , if checkbox is unchecked input not required

This is my html
<input type="checkbox" name="checked" id="check" onclick="unlocking()">
<label for="checkbox">If checked</label>
<fieldset id="unlock" style="display:none;">
<input type="text" name="Name" value="Name" id="inside" required>
<input type="text" name="email" value="email" id="inside" required>
<input type="text" name="Adress" value="Adress" id="inside" required>
</fieldset>
And this is my js with the function to hide and show the fieldset.
function unlocking() {
var checkBox = document.getElementById("check")
var form = document.getElementById("unlock")
if(checkBox.checked) {
form.style.display="block";
}else {
form.style.display="none";
}
}
If the fieldset is show i want the input to be required and if not just to skip it.
You could loop through each child and set its required attribute to either true or false depending on if the checkbox is checked or not, like so:
for (child of form.children) {
child.required = true;
}
Please check the snippet below:
function unlocking() {
var checkBox = document.getElementById("check");
var form = document.getElementById("unlock");
if (checkBox.checked) {
form.style.display = "block";
for (child of form.children) {
child.required = true;
console.log(child);
}
} else {
form.style.display = "none";
for (child of form.children) {
child.required = false;
console.log(child);
}
}
}
<input type="checkbox" name="checked" id="check" onclick="unlocking()" />
<label for="checkbox">If checked</label>
<fieldset id="unlock" style="display: none;">
<input type="text" name="Name" value="Name" id="inside" />
<input type="text" name="email" value="email" id="inside" />
<input type="text" name="Adress" value="Adress" id="inside" />
</fieldset>
//element.setAttribute("required", ""); turns required on
//element.removeAttribute("required"); turns required off
function unlocking() {
var checkBox = document.getElementById("check")
var form = document.getElementById("unlock")
var inputs = document.querySelectorAll('input[type=text]')
if(checkBox.checked) {
form.style.display="block";
for(var i = 0; i < inputs.length; i++)
inputs[i].setAttribute("required", "");
}else {
form.style.display="none";
for(var i = 0; i < inputs.length; i++)
inputs[i].removeAttribute("required");
}
}

"Cannot set property 'innerHTML' of undefined" of a javascript generated element

In my html form, when users leave blank fields I want to print a message below the fields. At first I tried using empty spans in my html to contain the possible error messages and it worked. But now, I want to generate those empty spans via javascript. The problem comes when I try to print a innerHTML in my empty spans, the console shows me "Can not set property' innerHTML 'of undefined" but variable statusMessageHTML is defined outside both loops so I do not understand why I'm getting this error.
JS
var myForm = document.getElementsByTagName('form')[0];
var formFields = document.getElementsByTagName('label');
myForm.addEventListener('submit', function(){
event.preventDefault();
var statusMessageHTML;
// create empty spans
for(i = 0; i < formFields.length; i++){
statusMessageHTML = document.createElement('span');
statusMessageHTML.className = 'status-field-message';
formFields[i].appendChild(statusMessageHTML);
}
// print a string in empty spans
for(i = 0; i < formFields.length; i++){
statusMessageHTML[i].innerHTML = "Error Message"
}
return false;
});
HTML
<form method="POST" action="form.php">
<label>
<input type="text" name="name" placeholder="Your name*">
</label>
<label>
<input type="text" name="number" placeholder="Your phone number*">
</label>
<label>
<input type="text" name="email" placeholder="Your e-mail*">
</label>
<label>
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="female">Female
</label>
<label>
<textarea name="message" rows="2" placeholder="Your message"></textarea>
</label>
<button type="submit" value="Submit">SUBMIT</button>
</form>
CODEPEN
PD: I want to solve this with pure javascript.
the attribute [i] does not exist on the statusMessageHTML object. That is the reason for the undefined message. If statusMessageHTML[i] is undefined, then you cannot set the innerHTML attribute of something that does not exist.
var myForm = document.getElementsByTagName('form')[0];
var formFields = document.getElementsByTagName('label');
myForm.addEventListener('submit', function(){
event.preventDefault();
var statusMessageHTML;
var elementArray = [];
// create empty spans
for(i = 0; i < formFields.length; i++){
statusMessageHTML = document.createElement('span');
statusMessageHTML.className = 'status-field-message';
formFields[i].appendChild(statusMessageHTML);
elementArray.push(statusMessageHTML);
}
// print a string in empty spans
for(i = 0; i < elementArray.length; i++){
elementArray[i].innerHTML = "Error Message"
}
return false;
});
<form method="POST" action="form.php">
<label>
<input type="text" name="name" placeholder="Your name*">
</label>
<label>
<input type="text" name="number" placeholder="Your phone number*">
</label>
<label>
<input type="text" name="email" placeholder="Your e-mail*">
</label>
<label>
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="female">Female
</label>
<label>
<textarea name="message" rows="2" placeholder="Your message"></textarea>
</label>
<button type="submit" value="Submit">SUBMIT</button>
</form>
statusMessageHTML is treated as element object in the first for loop but in the second loop you are assuming it as an array
// create empty spans
for(i = 0; i < formFields.length; i++){
statusMessageHTML = document.createElement('span');
statusMessageHTML.className = 'status-field-message';
formFields[i].appendChild(statusMessageHTML);
statusMessageHTML.innerHTML = "Error Message"
}

Output form within html page

I want to print the submitted input elements within the same page below the html form. The checked checkbox elements should all be printed. The image element can be avoided.
The function does not seem to be working.
function validateForm(myForm) {
var a = document.getElementById("fname").value;
document.getElementById("display").innerHTML = y;
var b = document.getElementByName("passwords").value;
document.getElementById("display1").innerHTML = y;
var c = document.getElementByName("gender");
var i;
for (i = 0; i < c.length; ++i) {
if (c[i].checked)
document.getElementById("display1").innerHTML = c[i].value; //looping through radio buttons
}
var d = document.getElementByName("hobbies");
for (i = 0; i < d.length; ++i) {
if (d[i] checked)
ans = ans + d[i].value; //looping through checkboxes and adding to display in display 2 id.
}
document.getElementById("display2").innerHTML = ans;
var e = document.getElementByName("cities").value;
document.getElementById("display3").innerHTML = e;
}
<form name="myForm">
<fieldset>
<legend>Personal Details</legend>
Name:
<input type="text" id="fname" <br>Password:
<input type="password" name="password" id="passwords" />
<br>Gender:
<input type="radio" name="gender" />Male
<input type="radio" name="gender" />Female</input>
<br>Hobbies:
<input type="radio" name="hobbies" value="Reading" />Reading
<input type="radio" name="hobbies" value="Writing" />Writing</input>
<br>City:
<select name="cities" />
<option>Surat</option>
<option>Ahmedabad</option>
<option>Rajkot</option>
<option>Vadodra</option>
</select>
<br>Image:
<input type="file" accept="image/*" value="image" style="margin:0px 10px 10px 100px; margin:absolute;" />
</form>
<br>
<input type="Submit" value="Submit" onSubmit="validateform(myForm);">
</fieldset>
<p id="display"></p>//display the values submitted within the html page
<p id="display1"></p>
<p id="display2"></p>
<p id="display3"></p>
getElementsByName - plural and when accessing the first, use [0] like
document.getElementsByName("cities")[0].value
missing a dot in d[i].checked
move the onSubmit="validateform(myForm);" to the form tag and do onSubmit="return validateForm(this);" and add return false;
validateForm misspelled in event handler (lower case f)
y missing
ans not defined
function validateForm(myForm) {
var a = document.getElementById("fname").value;
document.getElementById("display").innerHTML = a;
var b = document.getElementsByName("passwords").value;
document.getElementById("display1").innerHTML = a;
var c = document.getElementsByName("gender");
var i, ans;
for (i = 0; i < c.length; ++i) {
if (c[i].checked)
document.getElementById("display1").innerHTML = c[i].value; //looping through radio buttons
}
var d = document.getElementsByName("hobbies");
for (i = 0; i < d.length; ++i) {
if (d[i].checked)
ans = ans + d[i].value; //looping through checkboxes and adding to display in display 2 id.
}
document.getElementById("display2").innerHTML = ans;
var e = document.getElementsByName("cities")[0].value;
document.getElementById("display3").innerHTML = e;
return false; // normally when error but here to stay on page
}
<form name="myForm" onSubmit="return validateForm(this);">
<fieldset>
<legend>Personal Details</legend>
Name:
<input type="text" id="fname" <br>Password:
<input type="password" name="password" id="passwords" />
<br>Gender:
<input type="radio" name="gender" />Male
<input type="radio" name="gender" />Female</input>
<br>Hobbies:
<input type="radio" name="hobbies" value="Reading" />Reading
<input type="radio" name="hobbies" value="Writing" />Writing</input>
<br>City:
<select name="cities" />
<option>Surat</option>
<option>Ahmedabad</option>
<option>Rajkot</option>
<option>Vadodra</option>
</select>
<br>Image:
<input type="file" accept="image/*" value="image" style="margin:0px 10px 10px 100px; margin:absolute;" />
</form>
<br>
<input type="Submit" value="Submit">
</fieldset>
<p id="display"></p><!-- display the values submitted within the html page -->
<p id="display1"></p>
<p id="display2"></p>
<p id="display3"></p>

Categories