getElementById() returns null on first element - javascript

The following code is my simple registration form. The problem is that alert(elements[0].value) displays undefined instead of the value of name (which is the first element of my form). However, if I try to execute alert(elements[1].value), it displays the value of name without any problem. Any ideas?
<html>
<body>
<form name="register" id="register" method="POST" action="this-file.php">
<fieldset>
<legend><span style="color:red; font-size:20px">
Register</span></legend><br>
<label for="firstname">First name<span style="color:red;">*</span></label>
<input type="text" name="firstname" id="firstname" placeholder="Peter"
autofocus required><br><br>
<label for="lastname">Last name<span style="color:red;">*</span></label>
<input type="text" name="lastname" id="lastname" placeholder="Parker"
required><br><br>
<label for="password">Password<span style="color:red;">*</span></label>
<input type="password" name="password" id="password" required><br><br>
<label for="favfood">Favorite food<span style="color:red;">*</span></label>
<select name="favfood" id="favfood" required>
<option value="" selected>(none)</option>
<option value="chicken">Chicken</option>
<option value="pizza">Pizza</option>
<option value="pasta">Pasta</option>
<option value="hamburger">Hamburger</option>
<option value="steak">Steak</option>
</select>
<p>Gender<span style="color:red;">*</span></p>
<ul>
<li>
<input type="radio" name="gender" id="male" value="male" required>
<label for="male">Male</label>
</li>
<li>
<input type="radio" name="gender" id="female" value="female" required>
<label for="female">Female</label>
</li>
</ul>
</fieldset><br>
<input type="submit" value="Register" name="register">
<input type="reset" value="Clear form" name="clear"><br><br>
</form>
<script type="text/javascript">
var form = document.getElementById('register');
var elements = form.elements;
form.noValidate = true;
form.addEventListener('submit', function (event) {
alert(elements[0].value); //displays "undefined" -- why?
for (var i = 0; i < elements.length; i++) {
if (elements[i].hasAttribute("required")) {
if (!elements[i].checkValidity()) {
event.preventDefault();
alert('Please, fill in every required field.');
form.reset();
elements[0].focus();
break;
}
}
}
}, false);
</script>
</body>
</html>

The first element in the elements collection is the <fieldset>. It doesn't have a name or a value.
(Yes, I know it doesn't really make sense for elements to include fieldsets, but it does).
Test the value of theelement.tagName to see if you are dealing with an input/select/textarea before trying to run your validation routine on it.

Related

JS FormData giving UncaughtTypeError when the HTML form data seems okay

Here's the HTML code:
<div class="some_class">
<form id="some_acc">
<p>First Name</p>
<input type="text" id="firstname" name="firstname" placeholder="Enter your first name">
<p>Last Name</p>
<input type="text" id="lastname" name="lastname" placeholder="Enter your last name">
<p>Date of Birth</p>
<input type="date" id="dob" name="dob" placeholder="Enter your date of birth">
<p>Email</p>
<input type="text" id="email" name="email" placeholder="Enter your email">
<p>Gender</p>
<div class="fieldset_account">
<fieldset>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label>
<input type="radio" id="Other" name="gender" value="other">
<label for="other">Other</label>
</fieldset>
</div>
<p>Choose no.</p>
<div class="acc_no">
<fieldset>
<input type="radio" id="regular" name="account_type" value="regular">
<label for="account_type">Acc 1</label>
<input type="radio" id="zero_bal" name="account_type" value="zero_bal">
<label for="account_type">Acc 2</label>
<input type="radio" id="children_acc" name="account_type" value="children_acc">
<label for="account_type">Acc 3</label>
<input type="radio" id="sr_cit_acc" name="account_type" value="sr_cit_acc">
<label for="account_type">Acc 4</label>
</fieldset>
</div>
<p>Remarks</p>
<div id="textarea_bio">
<textarea name="bio" id="bio" cols="30" rows="10"></textarea>
</div>
<br><br><input type="submit" value="Submit">
</form>
</div>
Here's the JS:
function FormDataToJSON(FormElement){
var formData = new FormData(FormElement);
var ConvertedJSON= {};
for (const [key, value] of formData.entries())
{
ConvertedJSON[key] = value;
}
return ConvertedJSON
}
var ReceivedJSON = FormDataToJSON(document.getElementById('some_acc'));
console.log(ReceivedJSON);
The error I'm getting is this:
Uncaught TypeError: Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.
Doesn't seem like there's anything wrong with the HTML form data. I'm guessing the radio buttons are the issue, but when I comment them out and try again, the error persists. What is going wrong here?
Thanks

How can I disable submit button after required html5 return true on the javascript?

My html code like this :
<form>
<label for="name">* Name</label>
<input type="text" id="name" required><br>
<label for="name">* Address</label>
<input type="text" id="address" required><br>
<input type="submit" value="Submit">
</form>
I'm using required HTML5 attribute to validate fields.
If user does not input text, it will display HTML5 error.
I want to disable the submit button if any of the required fields are left empty.
How can I do it?
You can disable the pointer events on the button with CSS.
form:invalid>#submit {
pointer-events: none;
}
<form>
<label for="name">* Name</label>
<input type="text" id="name" required><br>
<label for="name">* Address</label>
<input type="text" id="address" required><br>
<input type="submit" value="Submit" id="submit">
</form>
You could also disable the button using Javascript.
function disableField() {
const invalidForm = document.querySelector('form:invalid');
const submitBtn = document.getElementById('submit');
if (invalidForm) {
submitBtn.setAttribute('disabled', true);
} else {
submitBtn.disabled = false;
}
}
disableField();
const inputs = document.getElementsByTagName("input");
for (let input of inputs) {
input.addEventListener('change', disableField);
}
<form>
<label for="name">* Name</label>
<input type="text" id="name" required><br>
<label for="name">* Address</label>
<input type="text" id="address" required><br>
<input type="submit" value="Submit" id="submit">
</form>
you can do it after true
$("#button").prop("disabled", true);
You can try something like this:
$(function() {
$("#input-text").keyup(function () {
if($("#input-text")[0].checkValidity()){
$('#submit-button').attr('disabled', 'disabled');
}else{
$('#submit-button').removeAttr('disabled');
}
});
})($);
<form id="newRecord">
<input type="text" required id="input-text"/>
<button form="newRecord" type="submit" id="submit-
button">Submit</button>
</form>
An more generic solution for multiple forms and supporting multiple inputs and buttons.
It detects the change event directly on forms individually, and then change the disabled attribute for all submit types
function disableFormSubmit(form) {
const buttons = form.querySelectorAll(
'button[type="submit"], input[type="submit"]'
);
const disableButtons = () =>
buttons.forEach(el => (el.disabled = form.matches(":invalid")));
form.addEventListener("change", disableButtons);
disableButtons();
}
document.querySelectorAll("form").forEach(disableFormSubmit);
<form action="/">
<legend>First form</legend>
<input type="text" required> <br>
<input type="Checkbox" required> required checkbox <br>
<input type="submit">
<button type="submit">Button submit</button>
</form>
<hr>
<form action="/">
<legend>Second form</legend>
<select required>
<option value="" disabled selected>Select one</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select> <br>
<input type="radio" required name="radio"> required radio <br>
<input type="submit">
<button type="submit">Button submit</button>
</form>
Personally i would go on an solution using only CSS as a visual cue, unless you need the disabled attribute

How to get Multiple Checkbox data by form as root element in JQuery

I am new to JQuery. I am trying to get form data by using JQuery, first I am getting form elements by fields name attribute. All fields values are coming fine. but the multiple checkbox values are not getting. I search out many like this post but don't get any answer that works for me.
Sorry for bad English. Thank you for your help in advance.
$(document).ready(function() {
$('#form-data').on('submit', function(event) {
var form = $(this);
var name = form.find('input[name="name"]').val();
var email = form.find('input[name="email"]').val();
var phone = form.find('input[name="phone"]').val();
var gender = form.find('input[name="gender"]').val();
var subjects = form.find('input[name="subject"]').map(function() {
return $(this).val();
}).get();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" id="form-data">
<label for="name">Enter Name</label>
<input type="text" name="name" id="name"><br>
<label for="email">Enter Email</label>
<input type="email" name="email" id="email"><br>
<label for="phone">Enter Phone</label>
<input type="text" name="phone" id="phone"><br>
<label for="gender" checked>male</label>
<input type="radio" name="gender" value="male">
<label for="gender">female</label>
<input type="radio" name="gender" value="female"><br>
<label for="subject">Subject</label><br>
<input type="checkbox" name="subject[]" value="programing" checked>Programing
<input type="checkbox" name="subject[]" value="Networking">Networking
<input type="checkbox" name="subject[]" value="Database">Database
<input type="checkbox" name="subject[]" value="web development">web development
<input type="checkbox" name="subject[]" value="game development">game development
<br>
<input type="submit" id="submit" name="submit" value="submit">
</form>

How to create simple JavaScript error message from form submission?

I am new to JavaScript, bought Jon Duckett's book, but am not a fan of the way he described creating/displaying error messages- Can someone please tell me how to just display an error message if the NAME field is left empty? Thank you. Below is the HTML for my form:
<form action="form.php" method="post">
<fieldset>
<legend>Your Details:</legend>
<label for="name">Name:</label><br>
<input type="text" name="name" id="name" required="required"><br>
<label for="email">Email:</label><br>
<input type="text" name="email" id="email"><br>
<label for="telephone">Telephone:</label><br>
<input type="text" name="telephone" id="telephone">
</fieldset>
<br>
<fieldset>
<legend>Your Information:</legend>
<p>
<label for="service">What service are you inquiring about?</label>
<select name="service" id="service">
<option value="Collision">Collision</option>
<option value="Mechanical">Mechanical</option>
<option value="Custom">Custom</option>
<option value="Other">Other</option>
</select>
</p>
<label for="comments">Comments:</label>
<br>
<textarea name="comments" id="comments" rows="4" cols="40"></textarea>.
<input type="submit" value="Submit"/>
</fieldset>
</form>
Checkout this link, this link shows how to do a simple JavaScript form validation
https://www.w3schools.com/js/js_validation.asp
HTML Code
<form name="myForm" onsubmit="return validateForm()" action="form.php" method="post">
<fieldset>
<legend>Your Details:</legend>
<label for="name">Name:</label><br>
<input type="text" name="name" id="name"><br>
<label for="email">Email:</label><br>
<input type="text" name="email" id="email"><br>
<label for="telephone">Telephone:</label><br>
<input type="text" name="telephone" id="telephone">
</fieldset>
<br>
<fieldset>
<legend>Your Information:</legend>
<p>
<label for="service">What service are you inquiring about?</label>
<select name="service" id="service">
<option value="Collision">Collision</option>
<option value="Mechanical">Mechanical</option>
<option value="Custom">Custom</option>
<option value="Other">Other</option>
</select>
</p>
<label for="comments">Comments:</label>
<br>
<textarea name="comments" id="comments" rows="4" cols="40"></textarea>.
<input type="submit" value="Submit"/>
</fieldset>
</form>
JavaScript Code
function validateForm() {
var x = document.forms["myForm"]["name"].value;
if (x === "") {
alert("Name must be filled out");
return false;
}
}
Check functionality here
https://codepen.io/anon/pen/QvNGMZ
You have to create a new element ( span, div ... ), and write an error into it, and append that element after\before your form field, which ocured that error. As a good way, you may make an object, like {fieldName:{errorMessage,validationRule}} , where is fieldName - is your field name, that you need to validate, and errorMessage - is error, which you showing on error, and the validationRule - is regexp, for example, telling you how to validate that field. Or you just may hardcode all of these params. :)
P.s. There are a lot of ways to validate form, to get errors, and to show them. You may really easy search for it and choose the best for yourself.

getElementsByName looping through all fields returning values using onChange event

I have a contact form. The contact form has inputs, selectors and radio buttons.
Question 1: Using the getElementsByName how do I get the index of a field using the onChange event? Would I use a For Loop?
Question 2: How do I do this with inputs that selectors and radio buttons?
Question 3: Once I get the data from an Index how do I use the index to the ID of the field as I then want to evaluate the data.
Thanks in advance!
Javascript
`// Var for element
var contactname = document.getElementsByName('cf')[1];
//Get value when clicking out of field
contactname.addEventListener('onchange',function(){
console.log(contactname.value);
});`
HTML Form
<!DOCTYPE html>
<html>
<head>
<title>Contact Me</title>
<link rel="stylesheet" type="text/css" href="contactform_Lab8.css">
</head>
<body>
<form id="contactus">
<fieldset>
<label for="name">Name:</label>
<input id="name" type="text" name="cf" autofocus required>
<label for="email">Email:</label>
<input id="email" type="email" name="cf" required>
<label for="phone">Phone:</label>
<input id="phone" type="tel" name="cf" required>
<label for="status">Status:
<select id="status" name="cf" required>
<option value="client">Client</option>
<option value="partner">Partner</option>
<option value="vendor">Vendor</option>
</select>
</label>
<label for="subscribe">
<input id="subscribe" type="checkbox" name="cf" value="check" checked>
Send me your newsletter</label>
<label for="sales">
<label for="support">
<input id="slsSupport" type="radio" name="cf" value="sales" checked>Sales
<input id="slsSupport" type="radio" name="cf" value="support">Support
</label>
</label>
<label for="msg">Message:</label>
<textarea id="msg" name="cf" rows="10" cols="30" required></textarea>
</fieldset>
<fieldset>
<button type="submit">Send</button>
<button type="reset">Reset</button>
</fieldset>
</form>
<script src="contactform_Lab8.js"></script>
</body>
</html>
Try
// Var for element
var contactname = document.getElementsByName("cf");
//Get value when clicking out of field
Array.prototype.slice.call(contactname).forEach(function(elem, index) {
elem.addEventListener("change",function(event) {
// `log` `elem` `index` , `id` , `value`
console.log(index, event.target.id, event.target.value);
}, false);
});
<form id="contactus">
<fieldset>
<label for="name">Name:</label>
<input id="name" type="text" name="cf" autofocus required>
<label for="email">Email:</label>
<input id="email" type="email" name="cf" required>
<label for="phone">Phone:</label>
<input id="phone" type="tel" name="cf" required>
<label for="status">Status:
<select id="status" name="cf" required>
<option value="client">Client</option>
<option value="partner">Partner</option>
<option value="vendor">Vendor</option>
</select>
</label>
<label for="subscribe">
<input id="subscribe" type="checkbox" name="cf" value="check" checked>
Send me your newsletter</label>
<label for="sales">
<label for="support">
<input id="slsSupport" type="radio" name="cf" value="sales" checked>Sales
<input id="slsSupport" type="radio" name="cf" value="support">Support
</label>
</label>
<label for="msg">Message:</label>
<textarea id="msg" name="cf" rows="10" cols="30" required></textarea>
</fieldset>
<fieldset>
<button type="submit">Send</button>
<button type="reset">Reset</button>
</fieldset>
</form>

Categories