HTML Form Validation Logic in JavaScript or jQuery - javascript

I have a form for which I should write validation logic.
Let's say there's an input field like this.
<div class="group1"><label>Product code</label> <input id="code" name=""code" type="text" class="control1"></div>
If I want to make it a required field how do I write the logic?
I don't have access to the CSS files. But there's an input like this which I can use which has a red outline.
<div class="group1 row has-error">
<div><input type="text" class="control1"></div>
</div>
I have to give the code in JavaScript or jQuery.

Get an element and set true on required property.
const input1 = document.getElementById('code');
input1.required = true;
const input2 = document.querySelector('div.group1>div>input.control1');
input2.required = true;
<form>
<div class="group1"><label>Product code</label>
<input id="code" name="code" type="text" class="control1">
</div>
<div class="group1 row has-error">
<div>
<input type="text" class="control1">
</div>
</div>
<input type="submit">
</form>

I think this is what you need
$("#formSubmit").submit(function(e) {
e.preventDefault();
var error_text = "<div class='text-danger error_val'>Cannot be empty</div>"
var data = $("#formSubmit").serializeArray();
var allInputs = $("#formSubmit input");
for(var i=0; i<data.length; i++){
if(data[i].value.length == 0){
$(".group1").addClass('has-error');
var errorDiv = $(allInputs)[i].closest('.has-error');
$(error_text).insertAfter( errorDiv );
}
}
});
.has-error input{
border: 1px solid #f00;
}
.text-danger{
color:#f00;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="formSubmit">
<div class="group1 row">
<label>Product code</label>
<input id="code" name="code" type="text" class="control1" >
</div>
<button type="submit" id="submitButton">Save</button>
</form>

I know it`s too late but you can use these functions to make an input required/optional
function makeFieldRequired(element, elementName) {
let jqueryObj = $(element);
jqueryObj.attr('title', `${elementName} is required`);
jqueryObj.attr('required', 'true');
if (jqueryObj.closest("form").length)
refreshFormValidtion(jqueryObj.closest("form"));
}
function makeFieldOptional(element) {
let jqueryObj = $(element);
jqueryObj.removeAttr('required');
jqueryObj.removeAttr('title');
if (jqueryObj.closest("form").length)
refreshFormValidtion(jqueryObj.closest("form"));
}
function refreshFormValidtion(form) {
$(form).removeData("validator").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse($(form));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Related

Javascript document.getElementById function not returning checkbox value to HTML form

I have been searching for an answer everywhere but just can not find what I need.
I have a webpage that has an HTML table on the left column and an HTML form on the right column. When I click on a row in the table on the left I want it to display the values in the form on the right.
I have this working perfectly for the text fields on the form, but not for the two checkboxes. My javascript will return either true or false or checked and unchecked to the document.getElementById within the script itself by using alert(); but I have no idea what it needs to allow the checkboxes to display these values. I thought the document.getElementById would return the values but it seems it does not.
I have tried all kinds of conveluted ways to get this to work but can not seem to get the correct code needed.
I am new to all this so there is most likely something really simple I am missing.
This is the HTML form code:
<div class="column right">
<table>
<tr></tr>
<tr>
<div class="lockinv">
<form autocomplete="off" name="lockform" class="keyassign" action="includes/lockinventory.inc.php"
method="post">
<label id="inventory" for="locknum">Lock Number</label>
<input id="invlocknum" type="text" name="locknum" value="" required>
<label id="inventory" for="locktype">Lock Type</label>
<input id="invlocktype" type="text" name="locktype" value="" required>
<label id="inventory" for="keycode">Key Code</label>
<input id="invkeycode" type="text" name="keycode" value="" required>
<label id="inventory" for="lockengraved">Lock Engraved</label>
<input id="invlockengraved" type="hidden" name="lockengraved" value="0">
<input id="invlockengraved" type="checkbox" name="lockengraved" value="1">
<label id="inventory" for="lockmastered">Lock Mastered</label>
<input id="invlockmastered" type="hidden" name="lockmastered" value="0">
<input id="invlockmastered" type="checkbox" name="lockmastered" value="1">
<label id="inventory" for="locknote">Lock Note</label>
<textarea id="inventorynote" name="locknote" rows="5" cols="60"></textarea>
<div class="wheel">
<?php
if (isset($_GET["error"])) {
if($_GET["error"] == "lockexists") {
echo "<p>Lock Already In Inventory!</p>";
}
else if ($_GET["error"] == "lockexistsfailed") {
echo "<p>Lock Already In Inventory!</p>";
}
}
?>
</div>
<input id="bt6" type="submit" name="submit" value="Save">
<button id="bt6" type="reset" name="button">Cancel</button>
</form>
</div>
</tr>
</table>
</div>
This is my JavaScript code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
<script language="javascript"></script>
<script>
$(function () {
$('#lockTable td').click(function () {
var currentRow = $(this).closest("tr");
var locknum = currentRow.find("td:eq(0)").text();
var locktype = currentRow.find("td:eq(1)").text();
var keycode = currentRow.find("td:eq(2)").text();
var engraved = currentRow.find("td:eq(3)").find(":checkbox");
var mastered = currentRow.find("td:eq(4)").find(":checkbox");
var locknote = currentRow.find("td:eq(5)").text();
var lockengraved = engraved.prop("checked");
if (lockengraved === true) {
$grved = "checked";
} else {
$grved = "unchecked";
}
var lockmastered = mastered.prop("checked");
if (lockmastered === true) {
$msted = "checked";
} else {
$msted = "unchecked";
}
document.getElementById('invlocknum').value = locknum;
document.getElementById('invlocktype').value = locktype;
document.getElementById('invkeycode').value = keycode;
document.getElementById("invlockengraved").value = $grved;
document.getElementById('invlockmastered').value = $msted;
document.getElementById('inventorynote').value = locknote;
alert(document.getElementById("invlockengraved").value);
alert(document.getElementById("invlockmastered").value);
});
});
</script>
<p id="invlocknum"></p>
<p id="invlocktype"></p>
<p id="invkeycode"></p>
<p id="invlockengraved"></p>
<p id="invlockmastered"></p>
<p id="invlocknote"></p>
<p id="info"></p>
<p id="result"></p>
I found the answer to my issue. I had to modify my if statement in the Javascript to the following. Works the way I want it to. Thanks to all that helped.
var lockengraved = engraved.prop("checked");
if (lockengraved === true) {
document.getElementById("invlockengraved").checked = lockengraved;
}else if (lockengraved === false) {
document.getElementById("invlockengraved").checked = lockengraved;
}

How to create a 'add more' feature in HTML forms [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am creating a HTML form in which I need to create a 'add more' button so another field appears. Any help would be appreciated
This isn't possible in pure HTML, but it can easily be achieved using javascript!
Basic example
In the basic example, you have one input field. When you click the add field button an extra input gets added after the last inserted input.
$(document).on('click', '.add_field', function() {
$('<input type="text" class="input" name="field[]" value="">').insertAfter('.input:last');
})
form {
padding: 20px;
}
input {
width: 100%;
margin-bottom: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" class="input" name="field[]" value="">
</form>
<button type="button" class="add_field">Add field</button>
Copy value
This example is almost the same as the example above with one difference. It copies the value of the previous input. This is done with help of the JQuery .val() method
$(document).on('click', '.add_field', function() {
let value = $('.input:last').val(); // gets the value of the previous input
$('<input type="text" class="input" name="field[]" value="' + value + '">').insertAfter('.input:last');
})
form {
padding: 20px;
}
input {
width: 100%;
margin-bottom: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" class="input" name="field[]" value="">
</form>
<button type="button" class="add_field">Add field</button>
Input groups
You could also copy an entire input group with multiple input fields.
$(document).on('click', '.add_field', function() {
$('<div class="input-group"><input type="email" class="input" name="email[]" value="" placeholder="Your email"><input type="password" class="input" name="password[]" value="" placeholder="Your password"></div>').insertAfter('.input-group:last');
})
form {
padding: 20px;
}
input {
width: 100%;
margin-bottom: 5px;
}
.input-group {
border-bottom: 1px solid gray;
padding: 5px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="input-group">
<input type="email" class="input" name="email[]" value="" placeholder="Your email">
<input type="password" class="input" name="password[]" value="" placeholder="Your password">
</div>
</form>
<button type="button" class="add_field">Add field</button>
If you need any more examples please leave a comment!
Please try instead,
$(".Addmore").click(function(e) {
e.preventDefault();
// make a separation line
$("#FormItems").append('<hr width="300px">');
// append the input field as your needs
$("#FormItems").append('<input name="user" type="text" placeholder="Username"><br>');
$("#FormItems").append('<input name="email" type="email" placeholder="Email Address">');
});
.formwrapper{
text-align:center;
}
input{
padding:3px;
margin-bottom:5px;
display:inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="formwrapper">
<form>
<div id="FormItems">
<input name="user" type="text" placeholder="Username"><br>
<input name="email" type="email" placeholder="Email Address">
</div>
<input type="button" value="Add More" class="Addmore">
<input type="submit" value="Submit">
</form>
</div>
In a few lines of js and html you can get that :
<button class="add-input">Add one more input</button>
<form action="." method="GET">
<div class="inputs">
<input type="text" name="text[]">
</div>
<input type="submit" value="submit">
</form>
<script>
const addButton = document.querySelector('button.add-input')
const inputDiv = document.querySelector('form .inputs')
addButton.addEventListener('click', ()=>{ // button to add the inputs
let newInput = document.createElement('input')
newInput.name = 'text[]' // add the name of the input
newInput.type = 'text' // add the type of the input
// you can add other attributes before appeding the node into the html
inputDiv.appendChild(newInput)
})
</script>
and you will have this as a result (I used php to prompt the result)
you can add as many input you want/need.
Next step is just doing some css
I hope this is, what you mean
<form>
<input type="text">
<input type="submit" value="cta">
</form>
<button>Add More</button>
<script>
document.querySelector('button').addEventListener('click', () => {
let field = document.createElement('input');
// change field however you'd like
document.querySelector('form').insertBefore(field, document.querySelector('form:last-child'));
})
</script>
You cannot create this using HTML only, you will need javascript. You could use a frontend framework like react.js to make life easy.
For example in react, you could bind an onclick listener on the button and maintain an array of values as state. Use this array to map value to your input. Whenever user clicks the button, you can then simply push a defaultValue to the array and react will handle the rest.
Import React, { useState } from 'react';
const Page = ()=>{
const [ arr, setArr ] = useState([""]);
const handleAdd = ()=>{
setArr([...arr, ""]);
};
return <form>
{arr.map((elem, index)=><input
onChange={ //"implement logic to update value stored in array" }
value={elem}
key={index} /> )}
<button onClick={()=>handleAdd()}>Add</button>
</form>
}
Using Bootstrap and jquery
Only in html is not possible, you need some on click event to trigger the functionality that may change the html dom.
You can use vanilla javascript as well, here is example using jquery library.
It will dynamically add and remove the element
index.html
<!DOCTYPE html>
<html>
<head>
<title>YDNJSY</title>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
<!-- <h1>Lets learn javascript</h1> -->
<div class="col-xs-12">
<div class="col-md-12">
<h3> Actions</h3>
<div id="field">
<div id="field0">
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="action_id">Action Id</label>
<div class="col-md-5">
<input id="action_id" name="action_id" type="text" placeholder=""
class="form-control input-md">
</div>
</div>
<br><br>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="action_name">Action Name</label>
<div class="col-md-5">
<input id="action_name" name="action_name" type="text" placeholder=""
class="form-control input-md">
</div>
</div>
<br><br>
</div>
</div>
<!-- Button -->
<div class="form-group">
<div class="col-md-4">
<button id="add-more" name="add-more" class="btn btn-primary">Add More</button>
</div>
</div>
<br><br>
</div>
</div>
</body>
<script src="./index.js"></script>
</html>
index.js
$(document).ready(function () {
var next = 0;
$("#add-more").click(function (e) {
e.preventDefault();
var addto = "#field" + next;
var addRemove = "#field" + (next);
next = next + 1;
var newIn = ' <div id="field' + next + '" name="field' + next + '"><!-- Text input--><div class="form-group"> <label class="col-md-4 control-label" for="action_id">Action Id</label> <div class="col-md-5"> <input id="action_id" name="action_id" type="text" placeholder="" class="form-control input-md"> </div></div><br><br> <!-- Text input--><div class="form-group"> <label class="col-md-4 control-label" for="action_name">Action Name</label> <div class="col-md-5"> <input id="action_name" name="action_name" type="text" placeholder="" class="form-control input-md"> </div></div><br><br></div>';
var newInput = $(newIn);
var removeBtn = '<button id="remove' + (next - 1) + '" class="btn btn-danger remove-me" >Remove</button></div></div><div id="field">';
var removeButton = $(removeBtn);
$(addto).after(newInput);
$(addRemove).after(removeButton);
$("#field" + next).attr('data-source', $(addto).attr('data-source'));
$("#count").val(next);
$('.remove-me').click(function (e) {
e.preventDefault();
var fieldNum = this.id.charAt(this.id.length - 1);
var fieldID = "#field" + fieldNum;
$(this).remove();
$(fieldID).remove();
});
});
});

How to check if input name is inside an array in Jquery?

I want to know how I can check if input name is equal to name inside an array.
I have multiple inputs like below code:
<div class="inputMain">
<input name="first_name" value="">
</div>
<div class="inputMain">
<input name="last_name" value="">
</div>
<div class="inputMain">
<input name="email" value="">
</div>
And I have an array Like this:
var array = ['last_name', 'email'];
I want to add class to div, that wrap the input his name inside the array.
I don't want to use 2 loops.
You can use the following code:
var inputs = $("input");
var array = ['last_name', 'email'];
inputs.each(function(){
if(array.indexOf($(this).attr("name")) >= 0){
alert($(this).attr("name")+" exists");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="inputMain">
<input name="first_name" value="">
</div>
<div class="inputMain">
<input name="last_name" value="">
</div>
<div class="inputMain">
<input name="email" value="">
</div>
The HTML to the code is same as used by you in your question, I have added a bit of JQuery, that is simple to understand.
I hope it was helpful.
check output in browser console:
$(document).ready(function() {
var array = ['last_name', 'email', 'dsfdsfds'];
array.forEach(function(element) {
var x = document.getElementsByName(element);
console.log(x);
});
});
//check output in browser console
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<div class="inputMain">
<input name="first_name" value="">
</div>
<div class="inputMain">
<input name="last_name" value="">
</div>
<div class="inputMain">
<input name="email" value="">
</div>
there is your solution :)
$(document).ready(function() {
var array = ['last_name', 'email'];
var inputs = $("div[class='inputMain']").find("input");
array.forEach(function(name) {
inputs.each(function (x){
if (inputs[x].name === name) {
inputs[x].parentNode.classList.add("myClass")
}
});
});
console.log(inputs.prevObject);
});
https://jsfiddle.net/12es37ko/62/
you can check result into browser console :)

How to fill div with values from form?

I have a html form with such structure:
...
<select name="Employee">
<option>a</option>
<option>b</option>
</select>
<input type="checkbox" name="email" value="Yes" unchecked>Include Email Contact
<input type="checkbox" name="phone" value="Yes" unchecked>Include Phone Contact
Job Title: <input type="Text" name="jobTitle" size="20"><br>
<input type="Button" value="Generate" onclick="show()" id="refresh">
...
And a div:
<div class="data">
<div class="ft_name"></div>
<div class="ft_pos"></div>
<div class="ft_tbl_meta">E-Mail:</div>
<div class="ft_tbl_data"></div>
<div class="ft_tbl_meta">Phone:</div>
<div class="ft_tbl_data"></div>
</div>
How can I show my values in div section by pressing the button without reloading the entire page?
I know Javascript a bit, but unfortunately, didn't find the answer yet.
Thank you in advance!
Here is one solution, using unobtrusive vanilla javascript.
The function showData() runs when the button is clicked.
Then, the function showData():
gets the Boolean value of each checkbox (either true if checked or false if unchecked)
rewrites the Boolean value as a string (a value of true becomes 'Yes' and a value of false becomes 'No')
rewrites the relevant data field, including the string.
function showData() {
var emailValue = document.querySelector('input[value="email"]').checked;
var phoneValue = document.querySelector('input[value="phone"]').checked;
var data = document.getElementsByClassName('data')[0];
var dataFields = data.getElementsByTagName('div');
if (emailValue === true) {emailValue = 'Yes';} else {emailValue = 'No';}
if (phoneValue === true) {phoneValue = 'Yes';} else {phoneValue = 'No';}
for (var i = 0; i < dataFields.length; i++) {
switch (i) {
case (0) : dataFields[i].textContent = 'E-Mail: ' + emailValue; break;
case (1) : dataFields[i].textContent = 'Phone: ' + phoneValue; break;
}
}
}
var button = document.querySelector('input[type="button"]');
button.addEventListener('click',showData,false);
form, .data, label, input[type="button"] {
display: block;
}
form, .data {
float: left;
width: 200px;
}
input[type="button"] {
margin-top: 24px;
}
<form>
<label><input type="checkbox" name="contact" value="email" unchecked>Include Email Contact</label>
<label><input type="checkbox" name="contact" value="phone" unchecked>Include Phone Contact</label>
<input type="Button" value="Generate">
</form>
<div class="data">
<div class="ft_tbl_meta">E-Mail:</div>
<div class="ft_tbl_meta">Phone:</div>
</div>
set some IDs for your divs you wish to take/assign values from/to and put this code
IncludeEmailCheckBox is for your "include Email" checkbox
EmailToDiv is for your div to get the email
EmailFromDiv is for your input for Email
IncludePhoneCheckBox is for your "include Phone" checkbox
PhoneToDiv is for your div to get the Phone
PhoneFromDiv is for your input for Phone
function show(){
if (document.getElementById("IncludeEmailCheckBox").checked){
document.getElementById("EmailToDiv").innerHTML = document.getElementById("EmailFromDiv").innerHTML ;}
if (document.getElementById("IncludePhoneCheckBox").checked){
document.getElementById("PhoneToDiv").innerHTML = document.getElementById("PhoneFromDiv").innerHTML ;}
return false;
}
Remember to change IDs as nessesary
Get elements of class by calling document.getElementsByClassName(class_name)
Example javascript code below
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function testResults (form) {
var x = document.getElementsByClassName("ft_name");
x[0].innerHTML = form.name.value;
x = document.getElementsByClassName("ft_tbl_meta");
x[0].innerHTML = form.email.value; // name email is one provided in form
// Do same for all other classes
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="myform" ACTION="" METHOD="GET">Enter something in the box: <BR>
<input type="checkbox" name="email" value="Yes" unchecked>Include
Email Contact
<input type="checkbox" name="phone" value="Yes" unchecked>Include Phone Contact
Job Title: <input type="Text" name="jobTitle" size="20"><br>
<input type="Button" value="Generate" onclick="show(this.form)" id="refresh">
<INPUT TYPE="button" NAME="button" Value="Click" onClick="testResults(this.form)">
</FORM>
</BODY>
</HTML>
here is your view (I updated) using Jquery:
<div class="data">
<div class="ft_name"></div>
<div class="ft_pos"></div>
<div class="ft_tbl_meta">E-Mail:<span id="email_here"></span></div>
<div class="ft_tbl_data"></div>
<div class="ft_tbl_meta">Phone:<span id="phone_here"></span></div>
<div class="ft_tbl_data"></div>
</div>
Now fetching and printing values:
var Employee = $( "select[name=Employee]" ).val();
$('.ft_name').html(Employee);
var email = $( "input[name=email]" ).val();
$('#email_here').html(email);
var phone = $( "input[name=phone]" ).val();
$('#phone_here').html(phone);
var jobTitle = $( "input[name=jobTitle]" ).val();
$('.ft_pos').html(jobTitle);

How to revert change made by DOM?

So I made a simple javascript form validator which creates a box with the error message using DOM. But I can't figure out a way how to reset all these changes when i reset the form using
<button type="reset">
I would like to know how it's done please.
Thanks.
The Code
<html>
<head>
<script type="text/javascript">
function validate(){
var fname = document.getElementById("fname");
var surname = document.getElementById("surname");
if(fname.value === "" || fname.value === null){
document.getElementById("sbody").style.display = "block";
document.getElementById("fname").style.display = "block";
return false;
}
//Verify Last Name
if(surname.value === "" || surname.value === null){
document.getElementById("sbody").style.display = "block";
document.getElementById("surname").style.display = "block";
return false;
}
}//End Validate Function
</script>
<style type="text/css">
#sbody{
width: 100px;
height: 100px;
background-color: #f3f3f3;
display:none;
}
.vis{
display: none;
font-size: 12px;
}
</style>
</head>
<body>
<section id="sbody">
<span id="fner" class="vis">First Name is missing.</span>
<span id="lner" class="vis">Surame is missing.</span>
</section>
<form id="registerForm" method="POST" action="register.php" onsubmit="return validate()">
<label for="fname" class="labelStyle">First Name: </label>
<input id="fname" name="fname" type="text" value="">
<label for="surname" class="labelStyle">Surname: </label>
<input id="surname" name="surname" type="text" value="">
<button type="submit">Sign Up</button>
<button type="reset">Reset</button>
</form>
</body>
</html>
The browser cannot magically figure out what has to be done to reset the custom changes.
However you can listen to the reset event of the form using element.addEventListener.
DEMO
HTML
<form id="test">
<div id="errors-ct">The form has errors</div>
<button type="reset">Reset</button>
</form>
JS
//wait for the DOM to be ready
document.addEventListener('DOMContentLoaded', function () {
//store a reference to the errors container div
var errorsCt = document.getElementById('errors-ct');
//listen to the reset event of the form
document.getElementById('test').addEventListener('reset', function (e) {
var form = e.target; //this is how you could access the form
//hide the errors container
errorsCt.style.display = 'none';
});
});
If you want to reset the form, as if user hadn't made any selections or added any input, then just set all form element values to their default value, or empty.
jsFiddle
<div>
<form action="/echo/html" method="get">
<input type="text" placeholder="username" />
<br/>
<input type="password" placeholder="password" />
<br/>
<input type="checkbox" value="test" data-default="checked" checked="checked"/>
<br/>
<button type="reset" value="reset" onclick="resetForm()">reset</button>
<br/>
</form>
<div id="err">Some error message</div>
</div>
window.resetForm = function () {
var fields = $('input'),
uname, pass, check;
uname = $(fields.get(0));
pass = $(fields.get(1));
check = $(fields.get(2));
$("#err").text("");
uname.val('');
pass.val('');
if (check.attr("data-default") == "checked") {
check.attr("checked", "checked");
} else {
check.removeAttr("checked");
}
}

Categories