How to perform on-submit form validation - javascript

I want to replace the after-submission checks in the form with on-the-fly completeness and correctness checks that are performed when a form field loses focus.
How can I do this?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE HTML>
<html>
<head>
<title>Form</title>
<style>
body {
width: 500px;
}
.part {
width: 100%;
padding: 5px;
border-bottom: 1px solid #000;
}
label {
margin-right: 5px;
}
.label-left {
text-align: right;
}
.label-right {
text-align: left;
}
.error {
color: #cc0000;
}
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
//$(document).ready(function() {
function myValidateEMailAddress(email_address) {
var email_pattern = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return email_pattern.test(email_address);
}
function checkPassword(pwd_str) {
var my_pwd_pattern = /^(?=.*[a-zA-Z].*[a-zA-Z])(?=.*\d.*\d)[a-zA-Z0-9_]{6,20}$/;
return my_pwd_pattern.test(pwd_str);
}
function validatePhoneNumber(phone_number) {
var phone_pattern = /^(\(?\+?[0-9]*\)?)?[0-9_\- \(\)]*$/;
return phone_pattern.test(phone_number);
}
$(document).ready(function() {
$('#form').submit(function(e) {
var my_errors = false;
$('.part> .error').remove();
$('#my_submission').empty();
$(':text, :password, textarea').each(function() {
$(this).val($.trim($(this).val()));
if ($(this).val() == '') {
$(this).parent().append('<div class="error">Please provide a value</div>');
my_errors = true;
}
});
if ($('#email').val() != '') {
if (!myValidateEMailAddress($('#email').val())) {
$('#email').parent().append('<div class="error">Please provide a correct e-mail address</div>');
my_errors = true;
}
}
if ($('#your_password').val() != '') {
if (!checkPassword($('#your_password').val())) {
$('#your_password').parent().append('<div class="error">Please provide a correct password.</div>');
my_errors = true;
}
}
if ($('#phone').val() != '') {
if (!validatePhoneNumber($('#phone').val())) {
$('#phone').parent().append('<div class="error">Please provide a correct phone number.</div>');
my_errors = true;
}
}
if ($('#addresses option:selected').val() == '') {
$('#addresses').parent().append('<div class="error">Please select one item</div>');
my_errors = true;
}
if ($(':radio[name="sex"]:checked').length == 0) {
$(':radio[name="sex"]:first').parent().after('<div class="error">Please select one item</div>');
my_errors = true;
}
if ($(':radio[name="subscription"]:checked').length == 0) {
$(':radio[name="subscription"]:first').parent().after('<div class="error">Please select one item</div>');
my_errors = true;
}
if ($('#likes option:selected').val() == '') {
$('#likes').parent().append('<div class="error">Please select one item</div>');
my_errors = true;
}
if (my_errors) {
return false;
}
else {
e.preventDefault();
var my_submission_array = $('#form').serialize().split('&');
if (my_submission_array.length > 0) {
$('#my_submission').html('<h2>Submitted Elements</h2><ul></ul>');
for (var i = 0; i < my_submission_array.length; i++) {
var my_pair = my_submission_array[i].split('=');
$('#my_submission > ul').append('<li>' + my_pair[0] + ': ' + my_pair[1] + '</li>\n');
}
}
}
});
});
// });
</script>
</head>
<body>
<h3>Output:</h3>
<h2>My Questionnaire</h2>
<form name="form" id="form" action="" method="post">
<div class="part">
<label for="addresses" class="label-left">How should you be addressed?</label>
<select name="addresses" id="addresses">
<option value="">Please select one</option>
<option value="first">Mr.</option>
<option value="second">Madam</option>
<option value="third">Miss</option>
<option value="fourth">Dr.</option>
<option value="fifth">Pr.</option>
</select>
</div>
<div class="part">
<fieldset>
<legend>Sex:</legend>
<input type="radio" name="sex" id="group1" value="1">
<label for="group1" class="label-right">Male</label>
<input type="radio" name="sex" id="group2" value="2">
<label for="group2" class="label-right">Female</label>
</fieldset>
</div>
<div class="part">
<label for="last_name" class="label-left">Last Name: </label>
<input type="text" name="last_name" id="last_name">
</div>
<div class="part">
<label for="first_name" class="label-left">First Name: </label>
<input type="text" name="first_name" id="first_name">
</div>
<div class="part">
<label for="email" class="label-left">E-Mail: </label>
<input type="text" name="email" id="email">
</div>
<div class="part">
<label for="your_password">Password:</label>
<input type="password" name="your_password" id="your_password" size="10" maxlength="20">
</div>
<div class="part">
<label for="phone" class="label-left">Phone number: </label>
<input type="text" name="phone" id="phone">
</div>
<div class="part">
<label for="likes" class="label-left">What are your likes?</label>
<select name="likes" id="likes">
<option value="">Please select one</option>
<option value="first">Programming</option>
<option value="second"> African literature</option>
<option value="third">Poetry</option>
<option value="four">Dancing</option>
</select>
</div>
<div class="part">
<fieldset>
<legend>Do you want to receive our newsletter ?</legend>
<input type="radio" name="subscription" id="group1" value="1">
<label for="group1" class="label-right">Yes</label>
<input type="radio" name="letter" id="group2" value="2">
<label for="group2" class="label-right">No</label>
</fieldset>
</div>
<div class="part">
<label for="comments" class="label-left">Write some comments below:</label>
<textarea name="comments" id="comments" cols="40" rows="3"></textarea>
</div>
<div class="part">
<input type="submit" name="submit" id="submit" value="Submit Form">
</div>
<div id="my_submission"></div>
</form>
</body>
</html>

Before I continue answering, I should note that you're putting jQuery script before <html> tag. This is incorrect. It has to be in <head>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
...
performed when a form field loses focus
An element loses focus when you click away from it. jQuery happends to have a blur event for this occasion:
$('input').on('blur', function() {
// your code here
});
So you might want to do it this way:
$('#email').on('blur', function() {
var emailVal = $(this).val();
if (!emailVal || !myValidateEMailAddress(emailVal)) {
$(this).parent().append('<div class="error">Please provide a correct e-mail address</div>');
my_errors = true;
}
});
the rest of the code might look similar.

Related

Submit Button Not working but if I remove its JavaScript it works

This is my index.html file. It has JavaScript but when JavaScript validation works >Submit button doesn't perform any action. But when I remove JavaScript code it submits the data to the database.
I need to understand where my code has faults or mistakes and why this is happening. How to validate that the arrival date should be smaller than the departure date.
<!DOCTYPE html>
<head>
<title>Book Accomodations</title>
<link rel="stylesheet" href="style.css">
<script>
function validate(){
var x =document.forms["myform"]["fname"].value;
var y =document.forms["myform"]["lname"].value;
var email =document.forms["myform"]["email"].value;
var filter = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var getSelectedValue = document.querySelector( 'input[name="payment"]:checked');
if (x == "" || x == null) {
alert("First Name must be filled out");
return false;
} else if (y == "" || y == null) {
alert(" Last Name must be filled out");
return false;
}
else if (!email.match(filter)) {
alert(" Enter Proper Email ID");
return false;
}
else if(document.getElementById("country").value == "")
{
alert("Please select a country");
return false;
} else if(getSelectedValue == null) {
alert("Select Payment Mode")
return false;
}
return false;
}
</script>
</head>
<body>
<div class="form">
<form name ="myform" action="function.php" onsubmit="return validate();" id="form" method="POST" >
<label for="fname">First Name:</label>
<input type="text" id="fname" name="fname" /><br>
<label for="lname">Last Name:</label>
<input type="text" id="lname" name="lname" /><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" /><br>
<label for="arrival">Arrival Date:</label>
<input type="date" id="arrival " name="adate" ><br>
<label for="departure">Departure Date:</label>
<input type="date" id="departure " name="ddate" />
<br>
<label for="country">Choose a Country:</label>
<select id="country" name="country" form="myform" >
<option disabled selected value> -- select an option -- </option>
<option value="India">India</option>
<option value="U.S.A.">U.S.A.</option>
<option value="Nepal">Nepal</option>
<option value="Bangladesh">Bangladesh</option>
<option value="Germany">Germany</option>
<option value="Spain">Spain</option>
<option value="Italy">Italy</option>
<option value="Sri Lanka">Sri Lanka</option>
<option value="China">China</option>
</select>
<p>Payment Mode:</p>
<input type="radio" id="deb"
name="payment" value="Debit" />
<label for="deb">Debit Card</label>
<input type="radio" id="cred"
name="payment" value="Credit"/>
<label for="Credit">Credit Card</label>
<br>
<input type="submit" id="submit" name="submit" value="submit" style="width: 100px;"/>
<input type="reset" value="Reset" style="width: 100px; "/>
</form> </div>
</body>
You should return true at the end of your validate() function if your validation was successful. Right now you always return false. Thats why the button doesn´t seams to work.
Seems like you missed something.
You should return true after succesfull validation.
if (x == "" || x == null) {
alert("First Name must be filled out");
return false;
} else if (y == "" || y == null) {
alert("Last Name must be filled out");
return false;
} else if (!email.match(filter)) {
alert("Enter Proper Email ID");
return false;
} else if (document.getElementById("country").value == "") {
alert("Please select a country");
return false;
} else if (getSelectedValue == null) {
alert("Select Payment Mode")
return false;
} else {
return true;
}
Or just return true after if-else statement.

Producing an output box from a form

<!DOCTYPE html>
<html><head><title>CT Traders</title>
<style>
fieldset {width:40%; margin:0px 0px 10px 1%;}
legend {padding:2px; text-indent:5px;}
h2, p {margin-left: 1%;}
input[type="submit"], input[type="reset"]
{display:inline; float:none;}
</style>
<script>
//suggested logic for the validateInput() function
function validateInputs()
{
//check payment method
var methodChecked = false;
for (var i=0; i <document.frmCustOrders.class.length;i++)
{
if (document.frmCustOrders.class[i].checked ==true)
{
classChecked = true;
vClass = document.frmCustOrders.class[i].value;
}
}
//check customer index value
var customerIndex = document.getElementById("customer").value;
//retrieve order quantity
var qty = document.getElementById("qty").value;
//validate form data
if (customerIndex == -1) //validate customer
{
alert("Please select a customer.")
return false;
}
else if () //validate qty
{
}
else if (fsClassChecked == false) //validate payment method
{
alert("Please select a payment method.")
return false;
}
else //output
{
orderEntries = customer+ "\n"+ qty+ "\n"+vClass;
alert(orderEntries);
return false;
}
}
</script>
</head>
<body>
<h2>Customer Order</h2>
<form name="frmCustOrders" id="frmCustOrders"
onsubmit="return validateInputs();" action="">
<fieldset id="fsCustomer">
<legend>Customer List</legend>
<select name="customer" id="customer" size="3">
<option>107 Paula Harris</option>
<option>232 Mitch Edwards</option>
<option>229 BTC</option>
</select>
</fieldset>
<p>
<label for="qty">Order Quantity: </label>
<input type="text" name="qty" id="qty" />
</p>
<fieldset id="fsClass">
<legend>Payment Method</legend>
<input type="radio" name="method" id="check" value="check" />
Check<br />
<input type="radio" name="method" id="creditCard" value="credit card" />
Credit Card<br />
<input type="radio" name="method" id="debitCard" value="debit card" />
Debit Card
</fieldset>
<p> <input type="submit" value="Submit" />
<input type="reset" value="Reset" /></p>
</form>
</body>
</html>
I'm having issues getting an output box that retrieves the selections on the form.
Also, in one of my if statements I'm assigned to check if the value is between 1 and 999 but I'm drawing a total blank on this. I'm new to coding (Javascript) and this is my first class. Any help with getting this to work would be greatly appreciated.
There are some issues with your code
Redundant else if ()
fsClassChecked variable not declared.
Redundant class when iterate elements document.frmCustOrders.class
Use wrong variable customer should be customerIndex
Wrong condition (customerIndex == -1) change to (customerIndex == "")
//suggested logic for the validateInput() function
function validateInputs()
{
//check payment method
var methodChecked = false;
var fsClassChecked = false;
for (var i=0; i <document.frmCustOrders.length;i++)
{
if (document.frmCustOrders[i].checked ==true)
{
fsClassChecked = true;
vClass = document.frmCustOrders[i].value;
}
}
//check customer index value
var customerIndex = document.getElementById("customer").value;
//retrieve order quantity
var qty = document.getElementById("qty").value;
//validate form data
if (customerIndex == "") //validate customer
{
alert("Please select a customer.")
return false;
}
else if(qty == "" || qty < 1 || qty > 999){
alert("Please enter qty 1-999.")
return false;
}
else if (fsClassChecked == false) //validate payment method
{
alert("Please select a payment method.")
return false;
}
else //output
{
orderEntries = customerIndex + "\n"+ qty+ "\n"+vClass;
alert(orderEntries);
return false;
}
return false;
}
<!DOCTYPE html>
<html><head><title>CT Traders</title>
<style>
fieldset {width:40%; margin:0px 0px 10px 1%;}
legend {padding:2px; text-indent:5px;}
h2, p {margin-left: 1%;}
input[type="submit"], input[type="reset"]
{display:inline; float:none;}
</style>
<script>
</script>
</head>
<body>
<h2>Customer Order</h2>
<form name="frmCustOrders" id="frmCustOrders"
onsubmit="return validateInputs();" action="#">
<fieldset id="fsCustomer">
<legend>Customer List</legend>
<select name="customer" id="customer" size="3">
<option>107 Paula Harris</option>
<option>232 Mitch Edwards</option>
<option>229 BTC</option>
</select>
</fieldset>
<p>
<label for="qty">Order Quantity: </label>
<input type="text" name="qty" id="qty" />
</p>
<fieldset id="fsClass">
<legend>Payment Method</legend>
<input type="radio" name="method" id="check" value="check" />
Check<br />
<input type="radio" name="method" id="creditCard" value="credit card" />
Credit Card<br />
<input type="radio" name="method" id="debitCard" value="debit card" />
Debit Card
</fieldset>
<p> <input type="submit" value="Submit" />
<input type="reset" value="Reset" /></p>
</form>
</body>
</html>

JS methods does not load in onload method

I have a HTML file, with some Script inside.
I bring all functions in one Script Tag.
Now I want to use these methods in onload and onclick events.
Here is this HTML file with all scripts :
<!DOCTYPE html>
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js">
</script>
<script src="../configwireless.php">
</script>
<title>configuration</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.center {
margin: auto;
width: 40%;
border: 3px solid #73AD21;
padding: 10px;
text-align: center;
margin-left: auto;
margin-right: auto;
background : url(wall5.jpg) center no-repeat;
}
#font-face {
font-family: myFont;
src: url(fonts/Raleway-Medium.otf);
src: url(fonts/Raleway-Medium.ttf);
src: url(fonts/Raleway-Medium.woff);
}
body {
font-family:myFont;
background : url(wall5.jpg) center;
height: 100%;
font-family:myFont;
background-position: center;
background-repeat: repeat;
background-size: cover;
width: 100%;
}
lable {
font-family:myFont;
}
form{
font-family: myFont;
}
input {
text-align: center;
}
</style>
</head>
<body>
<form name="general" action="" id="general" class="center" method="post">
<div id="wirelessmodediv">
<label>Wireless Mode</label>
<select name="wirelessmode" id="wirelessmode"
onclick="checkGeneralWirelessMode()">
<option value="ap">AP</option>
<option value="xxx">Client</option>
<option value="xxx">Client Bridge(Routed)</option>
<option value="xxx">Adhoc</option>
<option value="xxx">WDS Station</option>
<option value="xxx">WDS AP</option>
</select> <br>
</div>
<div id="networkmodediv">
<label>Wireless Network Mode</label>
<select name="wirelessNetworkMode" id="wirelessNetworkMode">
<option value="disabled">Disable</option>
<option value="mixed">Mixed</option>
<option value="a-only">A-Only</option>
<option value="na-only">NA-Mixed</option>
<option value="n5-only">N-Only(5 GHz)</option>
</select> <br>
</div>
<div id="channelwidthdiv" >
<label> Channel Width </label>
<select id="channelWidth" name="channelWidth">
<option value="20">Full</option>
<option value="40">Wide </option>
<option value="2040">Dynamic </option>
<option value="10">Half (10 MHz)</option>
<option value="5">Quarter(5 MHz)</option>
</select> <br>
</div>
<div id="countrydiv">
<label>Country</label>
<select id="country" name="country"
onchange="fillWirelessChannel();"
onload="fillWirelessChannel();"
onclick="fillWirelessChannel();">
<option value="china" >China</option>
<option value="japan" >japan</option>
</select>
</div>
<br>
<div id="wirelesschannel">
<label>Wireless Channel</label>
<select id="wirelessChannel" name="wirelessChannel">
</select>
</div>
<br>
<div id="extentionchanneldiv">
<label> Extention Channel </label>
<select id="extentionChannel" name="extentionChannel">
<option value="auto">auto</option>
<option value="lower">lower</option>
<option value="upper">upper</option>
</select>
</div>
<br>
<div id="linkname" >
<label>Wireless Link Name</label>
<input type="text" name="ssid" id="ssid" /><br>
</div>
<div id="ssidbroadcast" >
<label>Wireless SSID Broadcast</label>
<input type="radio" name="broadcaststatus" id="enablebroadcaststatus"
value="0"> Enable
<input type="radio" name="broadcaststatus" id="disablebroadcaststatus" value="1" > Disable <br>
</div>
<div id="gatewaydiv" >
<label>Default GW Mode</label>
<input type="radio" name="gateway" id="gateway" value="1" onclick="checkDefaultGateway()"> Auto (DHCP)
<input type="radio" name="gateway" id="gateway" value="0" onclick="checkDefaultGateway()"> Manual <br>
</div>
<div id="gatewayipdiv" >
<label>Gateway</label>
<input type="text" name="gatewayip" id="gatewayip" ><br>
</div>
<label>Advanced Setting</label>
<input type="checkbox" name="advancecheck" id="advancecheck"
onchange="advancecheckChanged()"
onload="advancecheckChanged()"/><br>
<div id="advanceddiv" style="display:none;">
<label>Super Channel</label>
<input type="radio" name="supperchannel" value="ebable"> Enable
<input type="radio" name="supperchannel" value="disable"> Disable <br>
<label>TX Power</label>
<input type="text" name="txpower" id="txpower"><br>
<label>Antenna Gain</label>
<input type="text" name="antennagain" id="antennagain"><br>
<label>Noise Immunity</label>
<input type="radio" name="noise" id="enablenoise" value="1"> Enable
<input type="radio" name="noise" id="disablenoise" value="0"> Disable <br>
<label> Protection Mode </label>
<select id="protection">
<option value="None">one</option>
<option value="CTS">CTS</option>
<option value="RTS/CTS">RTS/CTS</option>
</select> <br>
<label>RTS Threshold</label>
<input type="text" name="rts" id="rts"> <br>
<label>Short Preamble</label>
<input type="radio" name="preamble" id="enablepreamble" value="ebable"> Enable
<input type="radio" name="preamble" id="disablepreamble" value="disable"> Disable <br>
<label>Short GI</label>
<input type="radio" name="gi" id="enablegi" value="1"> Enable
<input type="radio" name="gi" id="disablegi" value="0"> Disable <br>
<label>TX Antenna Chains</label>
<select id="txantennachains">
<option value="1">1</option>
<option value="3">1+2</option>
</select><br>
<label>RX Antenna Chains</label>
<select id="rxantennachains">
<option value="1">1</option>
<option value="3">1+2</option>
</select><br>
<label>Beacon Interval</label>
<input type="text" name="interval" id="interval"><br>
<label>DTIM Interval</label>
<input type="text" name="dtiminterval" id="dtiminterval"><br>
<label>AP Isolation</label>
<input type="radio" name="isolation" id="enableisolation" value="1"> Enable
<input type="radio" name="isolation" id="disableisolation" value="0"> Disable <br>
<label>Sensitivity Range (ACK Timing)</label>
<input type="text" name="sensitiverange" id="sensitiverange"><br>
<label>Max Associated Clients</label>
<input type="text" name="maxassociate" id="maxassociate"><br>
<label>Network Configuration</label>
<input type="radio" name="configuration" id="enableconfiguration" value="0"
onload="checkBridgeMode()"
onclick="checkBridgeMode()"
onchange="checkBridgeMode()"> Unbridge
<input type="radio" name="configuration" id="disableconfiguration" value="1"
onload="checkBridgeMode()"
onclick="checkBridgeMode()"
onchange="checkBridgeMode()"> Bridge<br>
<div id="multicastdiv">
<label>Multicast forwarding</label>
<input type="radio" name="multicast" id="enablemulticast" value="1"> Enable
<input type="radio" name="multicast" id="disablemulticast" value="0"> Disable <br>
<label>Masquerade / NAT</label>
<input type="radio" name="masquerade" id="enablemasquerade" value="1"> Enable
<input type="radio" name="masquerade" id="disablemasquerade" value="0"> Disable <br>
<label>Net Isolation</label>
<input type="radio" name="netisolation" id="enablenetisolation" value="1"> Enable
<input type="radio" name="netisolation" id="disablenetisolation" value="0"> Disable <br>
<label>Forced DNS Redirection</label>
<input type="radio" name="forcedns" id="enableforcedns" value="1"
onload="Checkradiobutton()" onclick="Checkradiobutton()" > Enable
<input type="radio" name="forcedns" id="disableforcedns" value="0"
onload="Checkradiobutton()" onclick="Checkradiobutton()"> Disable <br>
<label>Optional DNS Target</label>
<input type="text" name="optionaldns" id="optionaldns"><br>
<label>IP Address</label>
<input type="text" name="ipaddress" id="ipaddress"><br>
</div>
</div>
<div id="subnetmaskdiv" style="display:none;">
<label>Subnet Mask</label>
<input type="text" name="subnetmask" id="subnetmask"><br>
</div>
<input type="submit" name="apply" id="apply" value="Apply"/>
</form>
<script type="text/javascript">
function checkGeneralWirelessMode() {
if ((document.getElementById('wirelessmode').value == "ap") ||
(document.getElementById('wirelessmode').value == "infra") ||
(document.getElementById('wirelessmode').value == "wdsap"))
{
document.getElementById("channelwidthdiv").style.display = 'block';
document.getElementById("countrydiv").style.display = 'block';
document.getElementById("extentionchanneldiv").style.display = 'block';
document.getElementById("wirelesschannel").style.display = 'block';
document.getElementById("linkname").style.display = 'block';
document.getElementById("ssidbroadcast").style.display = 'block';
document.getElementById("networkmodediv").style.display = 'block';
document.getElementById("gatewayipdiv").style.display = 'none';
document.getElementById("gatewaydiv").style.display = 'none';
} else if (document.getElementById('wirelessmode').value == "wet") {
document.getElementById("networkmodediv").style.display = 'block';
document.getElementById("gatewayipdiv").style.display = 'block';
document.getElementById("linkname").style.display = 'block';
document.getElementById("gatewaydiv").style.display = 'block';
document.getElementById("extentionchanneldiv").style.display = 'none';
document.getElementById("channelwidthdiv").style.display = 'none';
document.getElementById("countrydiv").style.display = 'none';
document.getElementById("wirelesschannel").style.display = 'none';
document.getElementById("ssidbroadcast").style.display = 'none';
} else if (document.getElementById('wirelessmode').value == "sta" ||
document.getElementById('wirelessmode').value == "wdssta") {
document.getElementById("channelwidthdiv").style.display = 'block';
document.getElementById("linkname").style.display = 'block';
document.getElementById("networkmodediv").style.display = 'block';
document.getElementById("extentionchanneldiv").style.display = 'none';
document.getElementById("gatewayipdiv").style.display = 'none';
document.getElementById("gatewaydiv").style.display = 'none';
document.getElementById("countrydiv").style.display = 'none';
document.getElementById("wirelesschannel").style.display = 'none';
document.getElementById("ssidbroadcast").style.display = 'none';
}
}
function advancecheckChanged() {
if (document.getElementById('advancecheck').checked &&
document.getElementById('enableforcedns').checked) {
document.getElementById("advanceddiv").style.display = 'block';
document.getElementById("subnetmaskdiv").style.display = 'block';
} else
document.getElementById("advanceddiv").style.display = 'none';
document.getElementById("subnetmaskdiv").style.display = 'none';
}
function fillWirelessChannel() {
var index;
var selectTag = document.getElementById('wirelessChannel');
selectTag.options.length = 0;
var auto = document.createElement("option");
auto.value = 'auto';
auto.innerHTML = 'auto';
selectTag.appendChild(auto);
// console.log(document.getElementById('country').value);
if (document.getElementById('country').value == "iran") {
for (index = 4920; index <= 5825; index += 5) {
var opt = document.createElement("option");
opt.value = index;
opt.innerHTML = index;
selectTag.appendChild(opt);
}
} else if (document.getElementById('country').value == "japan") {
for (index = 4920; index <= 6075; index += 5) {
var otherOpt = document.createElement("option");
otherOpt.value = index;
otherOpt.innerHTML = index;
selectTag.appendChild(otherOpt);
}
}
}
function checkDefaultGateway() {
if (document.getElementById('gateway').checked) {
document.getElementById("gatewayipdiv").style.display = 'none';
} else
document.getElementById("gatewayipdiv").style.display = 'block';
}
function checkBridgeMode() {
if (document.getElementById('enableconfiguration').checked) {
document.getElementById("multicastdiv").style.display = 'block';
} else
document.getElementById("multicastdiv").style.display = 'none';
}
function Checkradiobutton() {
if (document.getElementById('enableforcedns').checked) {
document.getElementById("subnetmaskdiv").style.display = 'block';
} else
document.getElementById("subnetmaskdiv").style.display = 'none';
}
</script>
</body>
</html>
I can call methods in onclick event via using onclick method in every tag I want use a specific method.
But I want to try all methods in onload.
I tried onload="functionName;" in tags, but no effect.
I used window.onload="functionName"; in end of the script tags, but no effect.
I just could use
window.onload=function somefuntion() {
in function declaration and in worked.
But just for one method I can do that and when I do in this way the onclick method does not work.
How can I use these methods in onload and in onclick both? in my satisfied tags?
Maybe just:
window.addEventListener("load", function(event){
someFunc1();
someFunc2();
},false);

Custom dialog box not showing

I am writing some javascript and HTML, and I want to do custom dialog boxes for user error handling(not filling in fields). For some reason the boxes do not show up when the user error occurs. My Java scrip and html follows:
<script>$(document).ready(function(){
$('#submit_button').click(function(){
ShowCustomDialog();
});
});
function ShowCustomDialog()
{
var name = document.getElementById('name');
var address = document.getElementById('email');
var reason = document.getElementById('reason');
var message = document.getElementById('message');
if(name.value == ''){
ShowDialogBox('Warning','Enter your name','Ok','', 'GoToAssetList',null);
return false;
}
if(email.value == ''){
ShowDialogBox('Warning','Enter your email.','Ok','', 'GoToAssetList',null);
return false;
}
if(reason.value == ''){
ShowDialogBox('Warning','Select a reason','Ok','', 'GoToAssetList',null);
return false;
}
if(message.value == ''){
ShowDialogBox('Warning','Enter a message.','Ok','', 'GoToAssetList',null);
return false;
}
}
function ShowDialogBox(title, content, btn1text, btn2text, functionText, parameterList) {
var btn1css;
var btn2css;
if (btn1text == '') {
btn1css = "hidecss";
} else {
btn1css = "showcss";
}
if (btn2text == '') {
btn2css = "hidecss";
} else {
btn2css = "showcss";
}
$("#lblMessage").html(content);
$("#dialog").dialog({
resizable: false,
title: title,
modal: true,
width: '400px',
height: 'auto',
bgiframe: false,
hide: { effect: 'scale', duration: 400 },
buttons: [
{
text: btn1text,
"class": btn1css,
click: function () {
$("#dialog").dialog('close');
}
},
{
text: btn2text,
"class": btn2css,
click: function () {
$("#dialog").dialog('close');
}
}
]
});
}</script><form method="post" action="MAILTO:me" enctype="text/plain" onsubmit=" return ShowCustomDialog()">
<div class="row">
<label>Your Name:</label>
<input type="text" id="name" name="name" size="20" />
</div>
<div class="row">
<label>Your E-mail:</label>
<input type="text" id="email" name="email" size="20" />
</div>
<div class="row">
<label>Reason for Report:</label>
<select id="reason" name="reason" />
<option value="">Please Select...</option>
<option value="bug">Bug Report</option>
<option value="feature">Feature</option>
<option value="tech_support">Technical Support</option>
<option value="other">Other...</option>
</select>
</div>
<div class="row">
<label>Your Message:</label>
<textarea type="text" id="message" name="message" rows="7" cols="30"></textarea>
</div>
<input id="submit_button" type="submit" value="Send E-mail" />
<div id="dialog" title="Alert message" style="display: none">
<div class="ui-dialog-content ui-widget-content">
<p>
<span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0"></span>
<label id="lblMessage">
</label>
</p>
</div>
</div>
</form>
I would be grateful for any help
When you have a click event on a button, you have to return false or use e.preventDefault(). Otherwise, the button submits the page and you never see the dialog box.
For example
$(document).ready(function(){
$('#submit_button').click(function(e){
if(!ShowCustomDialog()) {
e.preventDefault()
}
});
});
With my example, you should add a return true to your ShowCustomDialog function.
function ShowCustomDialog()
{
...
if(message.value == ''){
ShowDialogBox('Warning','Enter a message.','Ok','', 'GoToAssetList',null);
return false;
}
return true;
}
why you don't use modal see:
http://www.w3schools.com/howto/howto_css_modals.asp
or bootstrap modals:
http://getbootstrap.com/javascript/#modals

JS form validation is not working

I have a form where i have JS form validation. But validation process is not working. The inserting process in working fine.
Below is the form for inserting the data into mysql Database-
<?php
session_start();
include("includes/connection.php");
include("header.php");
include("includes/adminmenu.php");
if(isset($_SESSION['username']))
{
//echo $_SESSION['username'];
?>
<!--Javasript Validation File Import -->
<script type="text/javascript" src="js/qcheck.js"></script>
<script type="text/javascript" language="JavaScript">
function HidePart(d) { document.getElementById(d).style.display = "none"; }
function ShowPart(d) { document.getElementById(d).style.display = "block"; }
function CheckboxChecked(b,d)
{
if(b) { ShowPart(d); }
else { HidePart(d); }
}
</script>
<br />
<div class="userstat">
<div style="background-color:#666666; text-align:center; font-weight:bold; color:#FFFFFF; font-size:24px;"><span>Insert A new Question</span></div>
<br />
<div class="statdata">
<form action="includes/insertq.php" method="POST" name="qform" onSubmit="return valide()">
<div style="text-align:center;">
<select name="subject" size="0">
<option selected="0" value="">Select Subject</option>
<option value="bangla">Bangla</option>
<option value="english">English</option>
<option value="physics">Physics</option>
<option value="chemistry">Chemistry</option>
<option value="math">Mathematics</option>
<option value="biology">Biology</option>
<option value="gk">General knowledge</option>
</select>
</div>
<br /><br />
<label for="question">Write Down the Question below</label>
<textarea name="question" rows="3" cols="40"></textarea><br /><br />
<label for="ans">Options</label><br /><br />
<label for="option1">a.</label>
<input type="text" name="option1" size="40" /><br />
<label for="option2">b.</label>
<input type="text" name="option2" size="40" /><br />
<label for="option3">c.</label>
<input type="text" name="option3" size="40" /><br />
<label for="option4">d.</label>
<input type="text" name="option4" size="40" /><br /><br />
<label for="correct">Correct.</label><br />
<input type="text" name="correct" size="40" /><br /><br /><br />
<div style="text-align:center;">
<input type="submit" name="submit" value="Submit Question" />
</div>
<br />
<br />
</form>
</div>
</div>
</body>
<?php
}
else
{
header("location: admin.php");
}
?>
<?php
include("includes/footer.php");
?>
and the Javascript file is
function valide()
{
var subject=document.forms["qform"]["subject"].value;
var question=document.forms["qform"]["question"].value;
var option1=document.forms["qform"]["option1"].value;
var option2=document.forms["qform"]["option2"].value;
var option3=document.forms["qform"]["option3"].value;
var option4=document.forms["qform"]["option4"].value;
var correct=document.forms["qform"]["correct"].value;
if(subject == null || Subject == "Select Subject")
{
alert("Select subject Type");
return false;
}
else if(question==null || question=="" || question.length<5)
{
alert("Insert Valid question");
return false;
}
else if(option1==null || option1=="")
{
alert("Insert Option 1.");
return false;
}
else if(option2==null || option2=="")
{
alert("Insert Option 2.");
return false;
}
else if(option3==null || option3=="")
{
alert("Insert option 3.");
return false;
}
else if(option4==null || option4=="")
{
alert("Insert option 4.");
return false;
}
else if(correct==null || correct=="")
{
alert("Insert correct option.");
return false;
}
}
case matters
if(subject == null || Subject == "Select Subject")
^
Subject !== subject
Also value is not going to be null. You should be checking for a length of zero.

Categories