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");
}
}
Related
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>
I am trying show content in a div when a user click on a button. I have three button test connection src , test connection dest, next.
When I click on test connection src if there is no input it should display message but when user click on input field it should hide the message, right now I am able to show the message but when I click on input field it is not hiding
same when test connection src clicked if the input field matches the with pattern that is regex it show display message connection successful,
right now I am not able to show connection successful in <div id = "inp_src_success"></div> and <div id = "inp_dest_success"></div>
Same goes for button test connection dest
next button click should be enabled only once the both become successful
$(document).ready(function () {
$("#test_btn_src").on("click", function(){
var inpsrc = document.getElementById('inp_src').value;
//alert(inpsrc);
if(inpsrc.trim() == null || inpsrc.trim() == "") {
document.getElementById('inp_src1').innerHTML = 'IP src should be filled out';
}
else {
$("inp_src").keypress(function(key){
if (key){
$("inp_src1").hide();
}
});
}
});
$("#test_btn_dest").on("click", function(){
var inpdest = document.getElementById('inp_dest').value;
//alert(inpsrc);
if(inpdest.trim() == null || inpdest.trim() == "") {
document.getElementById('inp_dest1').innerHTML = 'IP src should be filled out';
}
else {
$("inp_dest").keypress(function(key){
if (key){
$("inp_dest1").hide();
}
});
}
});
document.getElementById("mybtn").onclick = function () {
location.href = "www.google.com";
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<body>
<div id = "inp_src_success"></div>
<div>
<label>Enter Source Server IP Here</label>
<input id = "inp_src" name="txtbox_ip_src" minlength="7" maxlength="15" class="form-control" type="text"
placeholder="Source Server Ip:"
pattern="(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
required onkeypress="myFunction()" />
<div id = "inp_src1"></div>
<button id = "test_btn_src" class="btn btn-primary success" type="button" style=" font-size: 10px; margin-top:7px;">Test Connection Src</button>
</div>
<div id = "inp_dest_success"></div>
<div>
<label>Enter Destination Server IP Here</label>
<input id = "inp_dest" name="txtbox_ip_src" minlength="7" maxlength="15" class="form-control" type="text"
placeholder="Destination Server Ip:"
pattern="(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
required onkeypress="myFunction1()" />
<div id = "inp_dest1"></div>
<button id = "test_btn_dest" class="btn btn-primary success" type="button" style=" font-size: 10px; margin-top:7px;">Test Connection Dest</button>
</div>
<button id = "mybtn" class="btn btn-primary nextBtn pull-right" type="button">Next</button>
There's a lot of changes that I would suggest you make in your JavaScript. It can do with a lot of improvement. Since you will be using these elements in a few places I suggest adding global variables for these, so that it's easier to work with.
See the snippet below. I will add comments. I won't be using jQuery, but vanilla JavaScript.
I added type="submit" to the buttons to use the browser's built in validator.
So in the example snippet, you will see a few ways you can validate.
I wrapped your form in form tags, since this is a form, and you're doing validation. I assume you will be submitting the form as well.
$(document).ready(function() {
//Global vars, to be reused.
var sourceValid = false;
var destinationValid = false;
var btnTestSrc = document.getElementById("test_btn_src");
var btnTestDest = document.getElementById("test_btn_dest");
var btnSubmit = document.getElementById("mybtn");
btnSubmit.disabled = true;
var txtInpSrc = document.getElementById("inp_src");
var txtInpDest = document.getElementById("inp_dest");
var inpSrc1 = document.getElementById('inp_src1');
inpSrc1.style.display = "none";
var inpDest1 = document.getElementById('inp_dest1');
inpDest1.style.display = "none";
//
//Add an event listener to the button. Same as the jQuery alternative that you used.
btnTestSrc.addEventListener("click", function() {
sourceValid = InputHasValue(txtInpSrc);
inpSrc1.style.display = sourceValid ? "none" : "block";
if (sourceValid && destinationValid)
btnSubmit.removeAttribute("disabled");
else
btnSubmit.setAttribute("disabled", true);
});
//This event listener will do validation before you click the button
txtInpSrc.addEventListener("keyup", function() {
inpSrc1.style.display = InputHasValue(this) ? "none" : "block";
});
btnTestDest.addEventListener("click", function() {
destinationValid = InputHasValue(txtInpDest);
inpDest1.style.display = destinationValid ? "none" : "block";
if (sourceValid && destinationValid)
btnSubmit.removeAttribute("disabled");
else
btnSubmit.setAttribute("disabled", true);
});
txtInpDest.addEventListener("keyup", function() {
inpDest1.style.display = InputHasValue(this) ? "none" : "block";
});
btnSubmit.addEventListener("click", function() {
alert("submit");
});
//Repeat on Dest
});
function InputHasValue(input) {
var val = input.value.trim();
return val ? true : false;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<form>
<div id="inp_src_success"></div>
<div>
<label>Enter Source Server IP Here</label>
<input id="inp_src" name="txtbox_ip_src" minlength="7" maxlength="15" class="form-control" type="text" placeholder="Source Server Ip:" pattern="(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
required />
<br />
<div id="inp_src1">IP src should be filled out</div>
<button id="test_btn_src" type="submit" class="btn btn-primary success" type="button" style=" font-size: 10px; margin-top:7px;">Test Connection Src</button>
</div>
<div id="inp_dest_success"></div>
<div>
<label>Enter Destination Server IP Here</label>
<input id="inp_dest" name="txtbox_ip_src" minlength="7" maxlength="15" class="form-control" type="text" placeholder="Destination Server Ip:" pattern="(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
required />
<br />
<div id="inp_dest1">IP dest should be filled out</div>
<button id="test_btn_dest" type="submit" class="btn btn-primary success" type="button" style=" font-size: 10px; margin-top:7px;">Test Connection Dest</button>
</div>
<button id="mybtn" type="submit" class="btn btn-primary nextBtn pull-right" type="button">Next</button>
</form>
</body>
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<body>
<div id = "inp_src_success"></div>
<div>
<label>Enter Source Server IP Here</label>
<input id = "inp_src" name="txtbox_ip_src" minlength="7" maxlength="15" class="form-control" type="text"
placeholder="Source Server Ip:"
pattern="(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
required onkeypress="myFunction()" />
<div id="inp_src1"></div>
<br>
<button id = "test_btn_src" class="btn btn-primary success" type="button" style=" font-size: 10px; margin-top:7px;">Test Connection Src</button>
</div>
<div id = "inp_dest_success"></div>
<div>
<label>Enter Destination Server IP Here</label>
<input id = "inp_dest" name="txtbox_ip_src" minlength="7" maxlength="15" class="form-control" type="text"
placeholder="Destination Server Ip:"
pattern="(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
required onkeypress="myFunction1()" />
<div id = "inp_dest1"></div>
<br>
<button id = "test_btn_dest" class="btn btn-primary success" type="button" style=" font-size: 10px; margin-top:7px;">Test Connection Dest</button>
</div>
<button id = "mybtn" class="btn btn-primary nextBtn pull-right" type="button">Next</button>
JS:
$(document).ready(function () {
$("#test_btn_src").on("click", function(){
var inpsrc = document.getElementById('inp_src').value;
//alert(inpsrc);
if(inpsrc.trim() == null || inpsrc.trim() == "") {
document.getElementById('inp_src1').innerHTML = 'IP src should be filled out1';
}
else {
$("#inp_src1").hide();
}
});
$("#test_btn_dest").on("click", function(){
var inpdest = document.getElementById('inp_dest').value;
//alert(inpsrc);
if(inpdest.trim() == null || inpdest.trim() == "") {
document.getElementById('inp_dest1').innerHTML = 'IP src should be filled out';
}
else {
$("#inp_dest1").hide();
}
});
document.getElementById("mybtn").onclick = function () {
location.href = "www.google.com";
};
});
I have my HTML and JS, how would I use this form in my JS so if one of the fields are not entered, the form doesnt submit and shows me my original please enter all fields error
Form:
<form id="myForm" action="http://www.eecs.yorku.ca/~mbrown/EECS1012/testForm.php" method="get">
HTML:
<!doctype html>
<html lang="en">
<head>
<title> Forms </title>
<style>
span {
padding-left: 10px;
display: block;
float: left;
width: 20%;
}
button { margin-left: 10px; }
body {
width: 80%; margin: auto; font-family: sans-serif;
border: 1px solid black;
}
</style>
<meta charset="utf-8">
<script src="prototype.js"></script>
<script src="forms.js"></script>
</head>
<body>
<h1> Keyboard Events and Form Submit </h1>
<!-- Form -->
<form id="myForm" action="http://www.eecs.yorku.ca/~mbrown/EECS1012/testForm.php" method="get">
<p> <span>Name:</span> <input id="input1" value="" placeholder="Enter Name" name="Name"></p>
<p> <span>Id:</span> <input id="input2" value=""
placeholder="Enter ID" name="ID"></p>
<p> <span>Email:</span> <input id="input3" value="" placeholder="Enter Email" name="Email"></p>
<p>
<button id="submitButton" type="button" onclick="submit()"> Submit </button>
<button id="resetButton" type="button" onclick="reset()"> Reset </button>
</p>
<p style="color:red" id="ErrorMessage"> </p>
</body>
</html>
JS:
function reset(){
document.getElementById('input1').value = "";
document.getElementById('input2').value = "";
document.getElementById('input3').value = "";
document.getElementById('ErrorMessage').innerHTML = "";
}
function submit(){
var inp1 = document.getElementById('input1').value;
var inp2 = document.getElementById('input2').value;
var inp3 = document.getElementById('input3').value;
if(inp1 == "" || inp2 == "" || inp3 == "")
{
document.getElementById('ErrorMessage').innerHTML = "Please enter all fields";
}
else{
//do your code here
document.getElementById('ErrorMessage').innerHTML = "";
}
}
change your function name submit() to another because it conflict with builtin JS function, doing onclick="submit()" is same with this.form.submit() or document.getElementById('myForm').submit();
function reset() {
document.getElementById('input1').value = "";
document.getElementById('input2').value = "";
document.getElementById('input3').value = "";
document.getElementById('ErrorMessage').innerHTML = "";
}
function checkSubmit() {
var inp1 = document.getElementById('input1').value;
var inp2 = document.getElementById('input2').value;
var inp3 = document.getElementById('input3').value;
if (inp1 == "" || inp2 == "" || inp3 == "") {
document.getElementById('ErrorMessage').innerHTML = "Please enter all fields";
} else {
//do your code here
document.getElementById('ErrorMessage').innerHTML = "submitting form";
document.getElementById('myForm').submit();
}
}
span {
padding-left: 10px;
display: block;
float: left;
width: 20%;
}
button {
margin-left: 10px;
}
body {
width: 80%;
margin: auto;
font-family: sans-serif;
border: 1px solid black;
}
<h1> Keyboard Events and Form Submit </h1>
<!-- Form -->
<form id="myForm" action="https://www.eecs.yorku.ca/~mbrown/EECS1012/testForm.php" method="get">
<p> <span>Name:</span> <input id="input1" value="" placeholder="Enter Name" name="Name"></p>
<p> <span>Id:</span> <input id="input2" value="" placeholder="Enter ID" name="ID"></p>
<p> <span>Email:</span> <input id="input3" value="" placeholder="Enter Email" name="Email"></p>
<p>
<button id="submitButton" type="button" onclick="checkSubmit()"> Submit </button>
<button id="resetButton" type="button" onclick="reset()"> Reset </button>
</p>
<p style="color:red" id="ErrorMessage"> </p>
</form>
Change button type to "submit" and do validation in onsubmit event handler:
<form onsubmit="return validateMethod()" />
Move all your validation logics into validateMethod, return false if the validation is failed.
Below is an example but I think you should use a jquery lib for this:
function validateMethod(){
var inp1 = document.getElementById('input1').value;
var inp2 = document.getElementById('input2').value;
var inp3 = document.getElementById('input3').value;
if(!inp1 || !inp2 || !inp3)
{
document.getElementById('ErrorMessage').innerHTML = "Please enter all fields";
return false;
}
else{
//do your code here
document.getElementById('ErrorMessage').innerHTML = "";
return true;
}
}
You could simply use document.getElementById('myForm').addEventListener('submit', () => submit());
But you need to change <button id="submitButton" type="button" onclick="submit()"> Submit </button> to <button id="submitButton" type="submit"> Submit </button> (as Barmar said) and you also need to close your <form> tag.
Upon button click of the submission button you can iterate over all the input fields, determine whether or not they have the attribute required and then determine whether or not their value is an empty string (!field.value)
We put this in a try/catch block so that if a field is required and does not have a value, we can break out of the forEach loop by throwing an error and displaying the message Please Enter All Required Fields
let submit = document.querySelector("button");
submit.addEventListener("click", submitFn);
function submitFn() {
try {
document.querySelectorAll("form input").forEach(function(field) {
if (field.hasAttribute("required") && !field.value) {
throw error("not all fields filled in");
}
});
alert("all required fields filled in!")
} catch {
alert("please enter all required fields");
}
}
<form>
<label>first name </label><input required/>
<br/>
<label>last name</label><input required/>
<br/>
<label>email ( not required )</label><input />
<hr>
<button type="button">submit</button>
</form>
Note: It would be better code if you changed the type of the submit button to submit and changed the event from the above code from click to submit, but I've no idea if there was a reason for your markup or not so I leave that to your discretion.
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);
this is my code
i was trying to make a signup form and i made a script
i jst tried that the username should contain both alphabets and numbers and nothing else
if this condition is true than it continues
else it will give an error message displayed jst below it
<html>
<head>
</head>
<body>
<style>
#sign_up_details {
padding: 10px;
}
</style>
<form name="sign_up_details">
<h3>Enter your details below</h3>
<input type="textbox" id="username" placeholder="Enter your desired username" />
<p id="usrnm_check"></p><br>
<input type="password" id="password" placeholder="Enter your desired password" />
<p id="pass_check"></p><br>
<input type="textbox" id="email" placeholder="Enter your email id" />
<p id="email_check"></p><br>
<input type="submit" name="submit" value="Submit" onclick="store()" />
</form>
<script>
var usrnm = document.getElementById("username");
var pass = document.getElementById("password");
var email = document.getElementById("email");
var usrnm_check = document.getElementById("usrnm_check");
var pass_check = document.getElementById("pass_check");
var email_check = document.getElementById("email_check");
function store() {
var newReg = /^[A-Z]+[a-z]+[0-9]+$/
if (usrnm.value.match(newReg)) {
//next action here
} else {
usrnm_check.innerHTML = "Username should have alphabets and numbers";
}
}
</script>
</body>
</html>
for eg when i keep the username field empty and click on submit the error which is to be displayed comes below it but it soon disappears.
i dont know the reason for it.
you will have to set the store in onsubmit event and not on the submit button onclick event because,onclick will execute the function and submit the form as well.
here is fiddle
execute function before submit
<html>
<head>
</head>
<body>
<style>
#sign_up_details {
padding: 10px;
}
</style>
<form name="sign_up_details" onsubmit="return store()">
<h3>Enter your details below</h3>
<input type="textbox" id="username" placeholder="Enter your desired username" />
<p id="usrnm_check"></p><br>
<input type="password" id="password" placeholder="Enter your desired password" />
<p id="pass_check"></p><br>
<input type="textbox" id="email" placeholder="Enter your email id" />
<p id="email_check"></p><br>
<input type="submit" name="submit" value="Submit" />
</form>
<script>
var usrnm = document.getElementById("username");
var pass = document.getElementById("password");
var email = document.getElementById("email");
var usrnm_check = document.getElementById("usrnm_check");
var pass_check = document.getElementById("pass_check");
var email_check = document.getElementById("email_check");
function store() {
var newReg = /^[A-Z]+[a-z]+[0-9]+$/
if (usrnm.value.match(newReg)) {
//next action here
return true;
} else {
usrnm_check.innerHTML = "Username should have alphabets and numbers";
return false;
}
}
</script>
</body>
</html>
You can try something like this:
<form action="/dosomething.htm" method="GET" onsubmit="return store(this)">
[...]
<input type="submit" value="Go">
</form>
<script type="text/javascript">
function store() {
var newReg = /^[A-Z]+[a-z]+[0-9]+$/
if (usrnm.value.match(newReg)) {
//next action here
return true;
} else {
usrnm_check.innerHTML = "Username should have alphabets and numbers";
return false;
}
}
</script>
Notice return true and return false statements in store() and in form onSubmit. If the store() will return false the form will not get submitted. At present your message goes away after display because your form gets submitted even if the validation fails.
Hope this helps!!