Collect input data and put in one object for create JSON - javascript

I meet things which I don't understand. I collect all data from form and put to object, but I cannot understand why in that object one key is empty string and value also empty string? Please explain, if you can where is my mistake and why its work like that. And how is better and short way make validation if user not fill anyone input and push submit, and result should be alert("Empty form")
<form id="form">
<div class="mb-3">
<label class="form-label">Email address</label>
<input name="email" type="email" class="form-control">
</div>
<div class="mb-3">
<label class="form-label">First name</label>
<input name="firstName" type="text" class="form-control">
</div>
<div class="mb-3">
<label class="form-label">Last name</label>
<input name="lastName" type="text" class="form-control">
</div>
<div class="mb-3">
<label class="form-label">Nickname</label>
<input name="nickname" type="text" class="form-control">
</div>
<div class="mb-3">
<label class="form-label">Password</label>
<input name="password" type="password" class="form-control">
</div>
<div class="mb-3 ">
<label class="form-label">Select an option</label>
<select name="option" class="form-select">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
</div>
<div class="mb-3 ">
<label class="form-label">Type in your message</label>
<textarea
class="form-control"
placeholder="Leave a comment here"
style="height: 100px"
name="message"
></textarea>
</div>
<div class="mb-3">
<label class="form-label">Default file input example</label>
<input name="file" class="form-control" type="file">
</div>
<div class="mb-3 form-check">
<input name="terms" type="checkbox" class="form-check-input">
<label class="form-check-label" >Согласен с условиями</label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
const myForm = document.getElementById("form");
myForm.addEventListener("submit", element => {
element.preventDefault();
const keyValues = {};
for(let key of myForm) {
keyValues[key.name] = key.value;
}
localStorage.setItem("Item", JSON.stringify(keyValues));
window.location = 'result-submit.html';
})

Try typing the following code and see what you will find in the console :
myForm.addEventListener("submit", (element) => {
element.preventDefault();
const keyValues = {};
console.log(myForm);
for (let key of myForm) {
console.log(key, key.name, key.value);
keyValues[key.name] = key.value;
}
localStorage.setItem("Item", JSON.stringify(keyValues));
// window.location = "result-submit.html";
});
You will notice that it is the button that causes this problem, and to bypass it, try adding this condition :
if (key.type !== "submit") {...}
So your loop will look like this
for (let key of myForm) {
if (key.type !== "submit") {
keyValues[key.name] = key.value;
}
}
As for checking the input, the best way on the client side is to use the input attribute built in html : https://www.w3schools.com/html/html_form_attributes.asp

The submit button is part of the form and is sent along with the form data. Give the button a name so it doesn't appear as an empty key

Add required and name attributes to your required inputs and let the browser do the initial validation. If you want to do further validity you can use JS, perhaps by using the FormData interface.
const form = document.querySelector('form');
form.addEventListener('submit', handleSubmit);
function handleSubmit(e) {
e.preventDefault();
const FD = new FormData(form);
for (const input of FD) {
console.log(input);
}
}
<form id="form">
<div>
<label>Email address</label>
<input name="email" type="email" required>
</div>
<div>
<label>First name</label>
<input name="firstName" type="text" required>
</div>
<div>
<label>Password</label>
<input name="password" type="password" required>
</div>
<div>
<label>Select an option</label>
<select name="option" required>
<option selected disabled value="">Select option</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
</div>
<div>
<label>Type in your message</label>
<textarea name="comment" required placeholder="Leave a comment here"></textarea>
</div>
<div>
<label>Согласен с условиями</label>
<input name="terms" type="checkbox" required>
</div>
<button type="submit">Submit</button>
</form>

Related

How can I use a Javascript variable for a form action tag?

I have A sign-up form with a dropdown list and a script where I get the value of the selected option, I want to know if there is any way I can use the var selectedValue in the form action tag.
function getSelectValue(){
//var that i want to use in the form action tag
var selectedValue = document.getElementById("User_type").value;
console.log(selectedValue);
}
<!--Sign-up form-->
<form class="modal-content animate" action="I WANT THE JS VAR HERE" on method = "POST">
<div class="Logo">
<h1>Logo</h1>
</div>
<div class="container-fluid">
<div class="Name_field">
<input type="text" placeholder="Enter First Name" name="first" required>
</div>
<div class="Username_field">
<input type="text" placeholder="Enter Username/E-mail" name="username" required>
</div>
<div class="Password_field">
<input type="password" placeholder="Enter Password" name="pwd" required>
</div>
<div class="ConfirmPassword_field">
<input type="password" placeholder="Confirm Password" name="pwd2" required>
</div>
<select id="User_type" name="User_type" onchange="getSelectValue();">
<option value="0">Choose User</option>
<option value="signupinc.php">USER1</option>
<option value="signupinc1.php">USER2</option>
<option value="signupinc2.php">USER3</option>
<option value="signupinc3.php">USER4</option>
</select>
<div class= "Submit">
<button type="submit" name="submit">Sign-up</button>
</div>
</div>
</form>

Change required field form when option is selected

I have a form like below
<form>
<div class="6 op" style="display: none;">
<div class="form-group">Service</label>
<select class="form-control" id="exampleFormControlSelect1" required>
<option></option>
<option>Fiber</option>
<option>Hotspot</option>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Capacity</label>
<input type="text" class="form-control" id="formGroupExampleInput" placeholder="example: 1" required>
<select class="form-control" id="exampleFormControlSelect1" required>
<option>Mbps</option>
<option>Gbps</option>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Notes</label>
<textarea class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
<input type="submit">
</div>
</form>
In the code above, required is in service and capacity. I want to know how to add required to notes field automatically only when I choose Hotspot option in service field.
Do you know how to do that ?
Thank you
You can add onchange event handler to select option and as a param pass the value of the selected option. In this case when the value is hotspot you can use setAttribute to add the attribute required to the textarea else set it to false or remove it using removeAttribute. Also id of dom elements need to be unique
let txtArea = document.getElementById('exampleFormControlTextarea1');
function changeService(val) {
if (val.toLowerCase() === 'hotspot') {
txtArea.setAttribute('required', true)
} else {
txtArea.setAttribute('required', false)
}
}
<form>
<div class="6 op" style="">
<div class="form-group"><label for='exampleFormControlSelect1'>Service</label>
<select onchange='changeService(this.value)' class="form-control" id="exampleFormControlSelect1" required>
<option></option>
<option>Fiber</option>
<option>Hotspot</option>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlInput2">Capacity</label>
<input type="email" class="form-control" id="exampleFormControlInput1" placeholder="example: 1" required>
<select class="form-control" id="exampleFormControlSelect2" required>
<option>Mbps</option>
<option>Gbps</option>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Notes</label>
<textarea class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
<input type="submit">
</div>
</form>
Check this simple example below ,
using jquery , if someone select specific role , code toggle class and toggle REQUIRED properties on chosen element
$('select#role').change(function(){
let role = $(this).children("option:selected").val();
if (role == 0 ){
$('.detailed').removeClass("detailed");
$('#employee').prop('required',true);
}
else{
$('#staff').addClass("detailed");
$('#employee').prop('required',false);
}
}); // close $('select#role').change(function(){
let el = document.querySelector("#exampleFormControlSelect1");
el.addEventListener("change",(e)=>{
if(el.options[el.selectedIndex].value == "Hotspot" ) {
document.querySelector("#exampleFormControlTextarea1").setAttribute("required","");
} else {
document.querySelector("#exampleFormControlTextarea1").removeAttribute("required");
}
});
<form>
<div class="6 op" style="">
<div class="form-group">Service</label>
<select class="form-control" id="exampleFormControlSelect1" required>
<option></option>
<option>Fiber</option>
<option>Hotspot</option>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Capacity</label>
<input type="email" class="form-control" id="exampleFormControlInput1" placeholder="example: 1" required>
<select class="form-control" id="exampleFormControlSelect1" required>
<option>Mbps</option>
<option>Gbps</option>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Notes</label>
<textarea class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
<input type="submit">
</div>
</form>
First of all, remove the display:none property from first div. Then check the codes above.
$('#serviceToggle').on('change', function () {
var data = $(this).val();
if (data == 'hotspot') {
$('#notes').prop('required', true);
} else {
$('#notes').prop('required', false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="form-group">
<label for="serviceToggle">Service</label>
<select class="form-control" id="serviceToggle" required>
<option></option>
<option value="fiber">Fiber</option>
<option value="hotspot">Hotspot</option>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Capacity</label>
<input type="email" class="form-control" id="exampleFormControlInput1" placeholder="example: 1">
<select class="form-control" id="exampleFormControlSelect1" required>
<option>Mbps</option>
<option>Gbps</option>
</select>
</div>
<div class="form-group">
<label for="notes">Notes</label>
<textarea class="form-control" id="notes" rows="3"></textarea>
</div>
<input type="submit" value="Submit">
</form>
You can achieve this using jQuery. You need to set the field to required on the onChange event of dropdown.
// Perform some code on the change event of a dropdown
$("#exampleFormControlSelect1").change(function () {
var selected = $(this).children("option:selected").val();
// Get selected value and save it in selected variable
console.log(selected);
if(selected == "Fiber"){
//check the selected value and set the field to required
console.log('i am here');
// Set capacity input to required if value if Fiber
// $("#capacity").attr('required',true);
// Set Notes field to required if value if Fiber
$("#exampleFormControlTextarea1").attr('required',true);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="6 op">
<div class="form-group">Service</label>
<select class="form-control" id="exampleFormControlSelect1" required>
<option></option>
<option>Fiber</option>
<option>Hotspot</option>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Capacity</label>
<input type="text" class="form-control" id="capacity" placeholder="example: 1">
<select class="form-control" id="exampleFormControlSelect1">
<option>Mbps</option>
<option>Gbps</option>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Notes</label>
<textarea class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
<input type="submit">
</div>
</form>
In the above example, the Notes field will become required, if you select Fiber in Service Dropdown.

HTML/JavaScript: How to use alert when submitting a form (with queryselector)?

I wrote some HTML form where the form should alert when nothing is submitted. I started with creating this for the names. As expected, the message 'You must provide your full name!' shows when no name is entered. However, the message also shows up when the names are actually entered…
{% extends "layout.html" %}
{% block main %}
<!-- http://getbootstrap.com/docs/4.1/content/typography/ -->
<h1 class="mb-3">Form</h1>
<!-- http://getbootstrap.com/docs/4.1/components/forms/ -->
<form action="/form" method="post" id="form_id">
<div class="form-row names">
<div class="form-group col-md-3 name1">
<label for="inputFirstname">First name</label>
<input type="name" autofocus class="form-control" id="inputFirstname" placeholder="First name">
</div>
<div class="form-group col-md-3 name2">
<label for="inputLastname">Last name</label>
<input type="name" class="form-control" id="inputLastname" placeholder="Last name">
</div>
</div>
<div class="form-row clubs">
<div class="form-group col-md-3">
<label cfor="inlineFormCustomSelect">Club preference</label>
<select class="custom-select" id="inlineFormCustomSelect">
<option disabled selected value> -- select an option -- </option>
<option value="1">PSV</option>
<option value="2">Ajax</option>
<option value="3">Feyenoord</option>
<option value="4">De Graafschap</option>
<option value="5">RKVV Bergeijk 2</option>
</select>
<div class="invalid-feedback">Please choose one option</div>
</div>
</div>
<div class="form-group">
<label for="PFoot">Preferred foot</label>
<label class="form-check-label">
<input type="radio" id="PFoot" name="algorithm" value="right">
Right
</label>
<label class="form-check-label">
<input type="radio" id="PFoot" name="algorithm" value="left">
Left
</label>
<label class="form-check-label">
<input type="radio" id="PFoot" name="algorithm" value="zweipotig">
Zweipotig
</label>
</div>
<!-- http://getbootstrap.com/docs/4.1/components/buttons/ -->
<button class="btn btn-primary" type="submit">Submit</button>
</form>
<script>
document.querySelector('form').onsubmit = function() {
if (!document.querySelector('.name1').value) {
alert('You must provide your full name!');
return false;
}
return true;
}
</script>
{% endblock %}
As expected, the message 'You must provide your full name!' shows when no name is entered. However, the message also shows up when the names are actually entered…
You are using the wrong selector (.name1) which refers a div element, not the input you are thinking. Try #inputFirstname
document.querySelector('form').onsubmit = function() {
if (!document.querySelector('#inputFirstname').value) {
alert('You must provide your full name!');
return false;
}
else if(!document.querySelector('[name=algorithm]:checked')){
alert('You must provide Preferred foot!');
return false;
}
return true;
}
<form action="/form" method="post" id="form_id">
<div class="form-row names">
<div class="form-group col-md-3 name1">
<label for="inputFirstname">First name</label>
<input type="name" autofocus class="form-control" id="inputFirstname" placeholder="First name">
</div>
<div class="form-group col-md-3 name2">
<label for="inputLastname">Last name</label>
<input type="name" class="form-control" id="inputLastname" placeholder="Last name">
</div>
</div>
<div class="form-row clubs">
<div class="form-group col-md-3">
<label cfor="inlineFormCustomSelect">Club preference</label>
<select class="custom-select" id="inlineFormCustomSelect">
<option disabled selected value> -- select an option -- </option>
<option value="1">PSV</option>
<option value="2">Ajax</option>
<option value="3">Feyenoord</option>
<option value="4">De Graafschap</option>
<option value="5">RKVV Bergeijk 2</option>
</select>
<div class="invalid-feedback">Please choose one option</div>
</div>
</div>
<div class="form-group">
<label for="PFoot">Preferred foot</label>
<label class="form-check-label">
<input type="radio" id="PFoot" name="algorithm" value="right">
Right
</label>
<label class="form-check-label">
<input type="radio" id="PFoot" name="algorithm" value="left">
Left
</label>
<label class="form-check-label">
<input type="radio" id="PFoot" name="algorithm" value="zweipotig">
Zweipotig
</label>
</div>
<!-- http://getbootstrap.com/docs/4.1/components/buttons/ -->
<button class="btn btn-primary" type="submit">Submit</button>
</form>
The class name1 is div, not an input. Then you have to use (".name1 input") in the querySelector
document.querySelector('form').onsubmit = function() {
if (!document.querySelector('.name1 input').value) {
alert('You must provide your full name!');
return false;
}
return true;
}
in my case it's worked
<script>
document.querySelector('form').onsubmit = function() {
if (!document.querySelector('#inputFirstname').value) {
alert('You must provide your full name!');
return false;
}
return true;
}

Div show/hide not working?

The show or hide not working. the div keeps on showing, even if i select an option which should hide it.
However if i console log, it gives me respective show/hide output.
The following are sample code:
$('#categoryt').change(function() {
selection = $(this).val();
console.log(selection);
if (selection == "2") {
console.log("show");
$('#Subjectd').show();
} else {
console.log("hide");
$('#Subjectd').hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" action="insert.php">
<div class="form-group" id="formdiv">
<label for="Category">Category</label>
<select class="custom-select" id="categoryt">
<option selected>Choose Role</option>
<option value="1">Student</option>
<option value="2">Teacher</option>
<option value="3">Animation Designer</option>
<option value="4">Content Verifier</option>
<option value="5">Admin</option>
</select>
</div>
<div class="form-group" id="formdiv">
<label for="Name">Name</label>
<input type="text" id="Name" name="Name" placeholder="Name" class="form-control" />
</div>
<div class="form-group" id="formdiv" id="Schoold">
<label for="School">School</label>
<input type="text" id="School" name="School" placeholder="School" class="form-control" />
</div>
<div class="form-group" id="formdiv" id="Subjectd">
<label for="Subject">Subject</label>
<input type="text" id="Subject" name="Subject" placeholder="Subject" class="form-control" />
</div>
<div class="form-group" id="formdiv" id="Classd">
<label for="Class">Class</label>
<input type="text" id="Class" name="Class" placeholder="Class" class="form-control" />
</div>
You have two id's in your element
<div class="form-group" id = "formdiv" id = "Subjectd">
change to
<div class="form-group" id = "Subjectd">
Please remember that your element can only have one ID and that your ID must be unique in the entire page. Meaning you should never have two elements that share the same ID. Class, on the other hand, can be shared by multiple elements and you can have multiple classes on a single element.
i.e
<div class="form-group class_two class_three">

Display extra form fields if dropdown is selected

I'm trying to make two extra form fields appear if the user selects 'Yes' from a dropdown. If the user does not select 'Yes' from the dropdown, then the two extra fields are not required and are disabled, however if 'Yes' is selected these fields must be filled in before form submission. I have this so far, however it's not working. If anyone could point out the issue it would be greatly appreciated.
HTML:
<form id="form" method="post" action="action.php">
<div class="form-group">
<label class="control-label">Defect?</label>
<select onclick='checkIfYes()' class="select form-control" id="defect" name="defect">
<option id="No" value="No">No</option>
<option id="Yes" value="Yes">Yes</option>
</select>
</div>
<div id="extra" name="extra" style="display: none">
<label class="control-label" for="desc">Description</label>
<input class="form-control" type="text" id="desc" name="desc" required disabled>
<label class="control-label" for="auth_by">Authorised By</label>
<input class="form-control" type="text" id="auth_by" name="auth_by" required disabled>
</div>
<div class="form-group">
<button class="btn btn-info" id="submit" name="submit" type="submit">Submit
</button>
</div>
</form>
JavaScript:
function checkIfYes() {
if (document.getElementById('defect').value == 'Yes') {
document.getElementById('extra').style.display = '';
document.getElementById('auth_by').disabled = false;
document.getElementById('desc').disabled = false;
} else {
document.getElementById('extra').style.display = 'none';
}
}
JSFiddle
checkIfYes needs to be defined before the HTML that references it.
I would also recommend changing the select onclick event to onchange so that it only gets called when the user actually changes he value
See updated fiddle : Updated Fiddle
<script>
function checkIfYes() {
if (document.getElementById('defect').value == 'Yes') {
document.getElementById('extra').style.display = '';
document.getElementById('auth_by').disabled = false;
document.getElementById('desc').disabled = false;
} else {
document.getElementById('extra').style.display = 'none';
}
}
</script>
<form id="form" method="post" action="action.php">
<div class="form-group">
<label class="control-label">Defect?</label>
<select onchange='checkIfYes()' class="select form-control" id="defect" name="defect">
<option id="No" value="No">No</option>
<option id="Yes" value="Yes">Yes</option>
</select>
</div>
<div id="extra" name="extra" style="display: none">
<label class="control-label" for="desc">Description</label>
<input class="form-control" type="text" id="desc" name="desc" required disabled>
<label class="control-label" for="auth_by">Authorised By</label>
<input class="form-control" type="text" id="auth_by" name="auth_by" required disabled>
</div>
<div class="form-group">
<button class="btn btn-info" id="submit" name="submit" type="submit">Submit
</button>
</div>
</form>

Categories