Javascript if statement not working for form compare - javascript

I have a bootstrap form and i'm handling it with js.
but having problem cause if statement is not working correctly.
if you run the code you will see that the if statement that is comparing the second and third field is not working correctly
for second and third field in case 9 and a number below 9 it works but if you enter for example 10 and 5 for second and third field it wont work true.
Also if you enter 5 and 10 for second and third field it must return the error but it works.
any idea?
function mcalculate() {
var mainPrice = document.forms["disc"]["price"].value;
var productPercentage = document.forms["disc"]["t-per"].value;
var customerPercentage = document.forms["disc"]["c-per"].value;
var productCount = document.forms["disc"]["count"].value;
var runProject = true;
if (isNaN(mainPrice)){
document.getElementById("error1").innerHTML = "قیمت کالا باید عدد باشد";
runProject = false;
}
else {
document.getElementById("error1").innerHTML = "";
}
if (mainPrice<1){
document.getElementById("error2").innerHTML = "قیمت کالا باید عدد و مثبت باشد";
runProject = false;
}
else {
document.getElementById("error2").innerHTML = "";
}
if (isNaN(productPercentage ) || isNaN(customerPercentage)){
document.getElementById("error3").innerHTML = "درصد باید عدد باشد";
runProject = false;
}
else {
document.getElementById("error3").innerHTML = "";
}
if (productPercentage>100 || productPercentage<0){
document.getElementById("error4").innerHTML = "تخفیف شما بین 0 تا 100 نیست";
runProject = false;
}
else {
document.getElementById("error4").innerHTML = "";
}
if (customerPercentage>100 || customerPercentage<0 ){
document.getElementById("error5").innerHTML = "تخفیف مشتری بین 0 تا 100 نیست. ";
runProject = false;
}
else {
document.getElementById("error5").innerHTML = "";
}
if (isNaN(customerPercentage)){
document.getElementById("error6").innerHTML = "درصد باید عدد باشد"
runProject = false;
}
else if(customerPercentage > productPercentage){
document.getElementById("error6").innerHTML = "تخفیف مشتری از تخفیف شما بیشتر است";
runProject = false;
}
else {
document.getElementById("error6").innerHTML = "";
}
if (isNaN(productCount)){
document.getElementById("error7").innerHTML = "تعداد کالا باید عدد باشد";
runProject = false;
}
else {
document.getElementById("error7").innerHTML = "";
}
if (productCount<1){
document.getElementById("error8").innerHTML = "تعداد کالا باید عدد و مثبت باشد";
runProject = false;
}
else {
document.getElementById("error8").innerHTML = "";
}
if (runProject==true){
document.getElementById("calResult").innerHTML = "das"
}
else{
document.getElementById("calResult").innerHTML = "";
}
}
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<form name="disc" class="form-horizontal" action="" method="post">
<div class="form-group">
<label class="control-label col-md-6" for="price">قیمت کالا به تومان :</label>
<div class="col-md-6">
<input type="text" class="form-control" id="price" placeholder="مثلا 2580000" name="price" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-6" for="t-per">درصد تخفیف دریافتی شما :</label>
<div class="col-md-6">
<input type="text" class="form-control" id="t-per" placeholder="مثلا 8" name="t-per" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-6" for="c-per">درصد تخفیف شما به مشتری :</label>
<div class="col-md-6">
<input type="text" class="form-control" id="c-per" placeholder="مثلا 6" name="c-per" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-6" for="count">تعداد کالا :</label>
<div class="col-md-6">
<input type="text" class="form-control" id="count" placeholder="مثلا 5" name="count">
</div>
</div>
<div class="form-group">
<div class="col-md-4"></div>
<div class="col-md-4"></div>
<div class="col-md-2">
<button type="button" class="btn btn-default" onclick="mcalculate()">محاسبه</button>
</div>
<div class="col-md-2">
<button type="reset" class="btn btn-default">ریست</button>
</div>
</div>
</form>
</div>
<div class="col-md-3">
</div>
</div>
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<p id="error1" class="red"></p>
<p id="error2" class="red"></p>
<p id="error3" class="red"></p>
<p id="error4" class="red"></p>
<p id="error5" class="red"></p>
<p id="error6" class="red"></p>
<p id="error7" class="red"></p>
<p id="error8" class="red"></p>
<p id="calResult"></p>
</div>
<div class="col-md-3"></div>
</div>

You should cast all inputs that you want to use/compare as numbers to type Number first. .value always returns strings. You should also try to use dot notation instead of bracket notation whenever possible - reduces syntax noise.
var mainPrice = Number(document.forms.disc.price.value);
var productPercentage = Number(document.forms.disc.['t-per'].value);
var customerPercentage = Number(document.forms.disc.['c-per'].value);
var productCount = Number(document.forms.disc.count.value);

Related

Form validation change input value

I am using Javascript regualar expression for form validation in my project.Once the validation is completed without any error and while clicking submit button the form should submit and I need to change the submit value to 'please wait..'.
I have tried two methods.
Method 1:By changing the submit value
Method 2:Hide/show method using jquery
Both the methods are not working and i couldn't find the error to.Can anyone help me with this?
/*
// Initialize and add the map
function initMap() {
// The location of Uluru
var uluru = {lat: 12.991011, lng: 77.721225};
// The map, centered at Uluru
var map = new google.maps.Map(
document.getElementById('map'), {zoom: 10, center: uluru});
// The marker, positioned at Uluru
var marker = new google.maps.Marker({position: uluru, map: map});
}
*/
function pagetest(){
var name= document.getElementById("name").value;
var filt = /^[a-zA-Z]+$/;
if (!name.match(filt)){
document.getElementById("name").style.borderColor="red";
document.getElementById("nameerror").innerHTML='Name should not contain any number or special characters';
document.getElementById("nameerror").style.color='red';
}
else{
document.getElementById("name").style.borderColor="green";
document.getElementById("nameerror").innerHTML='valid name';
document.getElementById("nameerror").style.color='green';
}
var number=document.getElementById("mobile").value;
if(number.length!=10)
{
document.getElementById("mobile").style.borderColor="red";
document.getElementById("moberror").innerHTML="Number should be exactly 10 digits and not less than or more than that";
document.getElementById("moberror").style.color='red';
}
else
{
document.getElementById("mobile").style.borderColor="green";
document.getElementById("moberror").innerHTML="valid number";
document.getElementById("moberror").style.color='green';
}
var email = document.getElementById("email").value;
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,3})+$/;
if (!filter.test(email)) {
document.getElementById("email").style.borderColor="red";
document.getElementById("emailerror").innerHTML="Please provide a valid email address";
document.getElementById("emailerror").style.color="red";
}
else{
document.getElementById("email").style.borderColor="green";
document.getElementById("emailerror").innerHTML='valid email address';
document.getElementById("emailerror").style.color='green';
}
var country= document.getElementById("country").value;
var filt = /^[a-zA-Z]+$/;
if (!country.match(filt)) {
document.getElementById("country").style.borderColor="red";
document.getElementById("countryerror").innerHTML='country should not contain any number or special characters';
document.getElementById("countryerror").style.color='red';
}
else{
document.getElementById("country").style.borderColor="green";
document.getElementById("countryerror").innerHTML='Valid Country name';
document.getElementById("countryerror").style.color='green';
}
var city= document.getElementById("city").value;
var filt = /^[a-zA-Z]+$/;
if (!city.match(filt)) {
document.getElementById("city").style.borderColor="red";
document.getElementById("cityerror").innerHTML='city should not contain any number or special characters';
document.getElementById("cityerror").style.color='red';
}
else{
document.getElementById("city").style.borderColor="green";
document.getElementById("cityerror").innerHTML='Valid city name';
document.getElementById("cityerror").style.color='green';
}
/* var reg = /[^A-Za-z]/;
if ((reg.test(query) == false) && (query ==""))
{
document.getElementById('query').style.borderColor="red";
document.getElementById('queryerror').innerHTML="This field is required";
}
else{
document.getElementById("query").style.borderColor="green";
document.getElementById("queryerror").innerHTML ="";
}*/
var security = document.getElementById("security").value;
var securitycode = document.getElementById("securitycode").innerHTML;
if(security ==securitycode){
document.getElementById("security").style.borderColor="";
document.getElementById("codeerror").innerHTML="Code matched";
document.getElementById("codeerror").style.color='green';
}
else{
document.getElementById("security").style.borderColor="red";
document.getElementById("codeerror").innerHTML="Code didn't match or emplty";
document.getElementById("codeerror").style.color='red';
var val =Math.floor(1000 + Math.random() * 9000);
document.getElementById("securitycode").innerHTML =val;
security.focus;
}
if( (name!="") && (email!="") && (number!="") && (country!="") && (city!="") && (security!=""))
{
//alert("ok");
document.getElementById("form_id").submit();//submit() is a predefined function in js.
//document.getElementById("").innerHTML='Please wait..';
}
}
/*$(document).ready(function(){
$('form').submit(function(){
if(validationIsTrue()){
(":button").css('display':'none');
('#Button1').css('display':'block');
}
else{
return false;
}
});
});
$("#form_id").on("submit", function(e){
var $this = $(this);
if(this.checkValidity()) {
e.preventDefault();
alert('ok');
//$this.parents(".form-wrap").hide();
//$(".success-msg").removeClass("hidden")
}
});
*/
.iframe-container{
position: relative;
width: 100%;
padding-bottom: 56.25%; /* Ratio 16:9 ( 100%/16*9 = 56.25% ) */
}
.iframe-container > *{
display: block;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: 0;
padding: 0;
height: 100%;
width: 100%;
}
/* Demo styles */
.iframe-container{
margin-top:50px;
width:100%;
}
/*form */
.content{
background-image:url("contact-us (1).jpg");
min-height: 380px;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
box-shadow: inset 0 0 0 400px rgba(185, 212, 212, 0.35);
/* Needed to position the navbar */
}
.form-group{
color:white;
}
.no-border {
border: 0;
box-shadow: none; /* You may want to include this as bootstrap applies these styles too */
}
.contact{
color:#BF2626;
font-weight:bold;
margin-top:25px;
}
input,textarea{
margin-left:5px;
}
input:focus{
background-color:#b9dbe2;
color:black;
}
label{
color:black;
margin-top:4px;
}
.code{
color:black;
font-weight:bold;
margin-left:7px;
}
h3{
margin-left:-80px;
}
#securitycode{
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
<script src="formvali.js"></script>
<link rel="stylesheet" href="form.css">
</head>
<body onsubmit="loginload()">
<div class="col-sm-12 content">
<div class="col-sm-1"></div>
<div class="col-sm-4">
<h2 class="text-center">
Fill out this form and we will get back to you<span class="glyphicon glyphicon-hand-right"></span>
</h2>
<!-- <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d7245780.082381814!2d-88.29713116153964!3d27.53212533124578!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x88c1766591562abf%3A0xf72e13d35bc74ed0!2sFlorida!5e0!3m2!1sen!2s!4v1470659148428" class="img-responsive" frameborder="0" style="border:0" allowfullscreen></iframe>
-->
<h3 class="text-center"><strong>Bangalore Office</strong></h3>
<iframe src="http://maps.google.com/maps?q=12.987510,77.620491 &z=13&output=embed" width="300" height="200" frameborder="0" style="border:0"></iframe>
<h3 class="text-center"><strong>Kerala Office</strong></h3>
<iframe src="http://maps.google.com/maps?q=9.988126,76.295285 &z=13&output=embed" width="300" height="200" frameborder="0" style="border:0"></iframe>
</div>
<div class="col-sm-6" style="line-height:1.45;">
<h1 class="text-center contact"> Contact Us</h1>
<form action="#" method="POST" id="form_id" name="myform">
<div class="row form-group">
<div class="col-sm-2"></div>
<div class="col-sm-1">
<label>Name</label>
</div>
<div class="col-sm-9">
<input type="text" id="name" class="form-control" placeholder="Enter Your Name">
<i id="nameerror"></i>
</div>
</div><br>
<div class="row form-group">
<div class="col-sm-2"></div>
<div class="col-sm-1">
<label>Mobile</label>
</div>
<div class="col-sm-9">
<input type="text" id="mobile" class="form-control" placeholder="Enter Your Mobile Number">
<i id="moberror"></i>
</div>
</div><br>
<div class="row form-group">
<div class="col-sm-2"></div>
<div class="col-sm-1">
<label style="margin-left:0px;">Email </label>
</div>
<div class="col-sm-9">
<input type="email" id="email" class="form-control"placeholder="Enter Your Email Id">
<i id="emailerror"></i>
</div>
</div><br>
<div class="row form-group">
<div class="col-sm-2"></div>
<div class="col-sm-1">
<label>Country</label>
</div>
<div class="col-sm-9">
<input type="text" id="country" class="form-control" placeholder="Enter Your Country Name">
<i id="countryerror"></i>
</div>
</div><br>
<div class="row form-group">
<div class="col-sm-2"></div>
<div class="col-sm-1">
<label>City</label>
</div>
<div class="col-sm-9">
<input type="text" id="city" class="form-control"placeholder="Enter Your City Name">
<i id="cityerror"></i>
</div>
</div><br>
<div class="row form-group">
<div class="col-sm-2"></div>
<div class="col-sm-1">
<label>Query</label>
</div>
<div class="col-sm-9">
<textarea type="text" class="form-control" id="query"placeholder="Enter Your Query here(optional)"></textarea>
<i id="queryerror"></i>
</div>
</div>
<div class="row form-group">
<div class="col-sm-1"></div>
<div class="col-sm-2"></div>
<div class="col-sm-6">
<span class="code"></strong>Security Code <span id="securitycode"></span></span>
<input type="number" id="security" class="form-control" placeholder="Enter the security code">
<i id="codeerror"></i><br>
<div class="form-group text-center">
<div class="col-sm-2"></div>
<input type="button" class="btn btn-warning" name="sub" value="Submit" onclick="pagetest()"/>
<button id="Button1" style="display:none;">Please wait..</button>
</div>
</div>
</div>
</div>
</form>
<script>
var val =Math.floor(1000 + Math.random() * 9000);
document.getElementById("securitycode").innerHTML = val;
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCXRmYpTXDBP7vdQ-2fy11OqoKGUuGfcxI&callback=initMap">
</script>
</body>
</html>
function pagetest(){
var name= document.getElementById("name").value;
var filt = /^[a-zA-Z]+$/;
if (!name.match(filt)){
document.getElementById("name").style.borderColor="red";
document.getElementById("nameerror").innerHTML='Name should not contain any number or special characters';
document.getElementById("nameerror").style.color='red';
}
else{
document.getElementById("name").style.borderColor="green";
document.getElementById("nameerror").innerHTML='valid name';
document.getElementById("nameerror").style.color='green';
}
var number=document.getElementById("mobile").value;
if(number.length!=10)
{
document.getElementById("mobile").style.borderColor="red";
document.getElementById("moberror").innerHTML="Number should be exactly 10 digits and not less than or more than that";
document.getElementById("moberror").style.color='red';
}
else
{
document.getElementById("mobile").style.borderColor="green";
document.getElementById("moberror").innerHTML="valid number";
document.getElementById("moberror").style.color='green';
}
var email = document.getElementById("email").value;
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,3})+$/;
if (!filter.test(email)) {
document.getElementById("email").style.borderColor="red";
document.getElementById("emailerror").innerHTML="Please provide a valid email address";
document.getElementById("emailerror").style.color="red";
}
else{
document.getElementById("email").style.borderColor="green";
document.getElementById("emailerror").innerHTML='valid email address';
document.getElementById("emailerror").style.color='green';
}
var country= document.getElementById("country").value;
var filt = /^[a-zA-Z]+$/;
if (!country.match(filt)) {
document.getElementById("country").style.borderColor="red";
document.getElementById("countryerror").innerHTML='country should not contain any number or special characters';
document.getElementById("countryerror").style.color='red';
}
else{
document.getElementById("country").style.borderColor="green";
document.getElementById("countryerror").innerHTML='Valid Country name';
document.getElementById("countryerror").style.color='green';
}
var city= document.getElementById("city").value;
var filt = /^[a-zA-Z]+$/;
if (!city.match(filt)) {
document.getElementById("city").style.borderColor="red";
document.getElementById("cityerror").innerHTML='city should not contain any number or special characters';
document.getElementById("cityerror").style.color='red';
}
else{
document.getElementById("city").style.borderColor="green";
document.getElementById("cityerror").innerHTML='Valid city name';
document.getElementById("cityerror").style.color='green';
}
/* var reg = /[^A-Za-z]/;
if ((reg.test(query) == false) && (query ==""))
{
document.getElementById('query').style.borderColor="red";
document.getElementById('queryerror').innerHTML="This field is required";
}
else{
document.getElementById("query").style.borderColor="green";
document.getElementById("queryerror").innerHTML ="";
}*/
var security = document.getElementById("security").value;
var securitycode = document.getElementById("securitycode").innerHTML;
if(security ==securitycode){
document.getElementById("security").style.borderColor="";
document.getElementById("codeerror").innerHTML="Code matched";
document.getElementById("codeerror").style.color='green';
}
else{
document.getElementById("security").style.borderColor="red";
document.getElementById("codeerror").innerHTML="Code didn't match or emplty";
document.getElementById("codeerror").style.color='red';
var val =Math.floor(1000 + Math.random() * 9000);
document.getElementById("securitycode").innerHTML =val;
security.focus;
}
if( (name!="") && (email!="") && (number!="") && (country!="") && (city!="") && (security!="") && (name.match(filt)) && (number.length==10) && (filter.test(email)) && (country.match(filt)) && (city.match(filt)) && (security == securitycode))
{
alert("ok");
$('#submit_btn').val("Please wait");
document.getElementById("form_id").submit();//submit() is a predefined function in js.
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="formvali.js"></script>
<link rel="stylesheet" href="form.css">
</head>
<body onsubmit="loginload()">
<div class="col-sm-12 content">
<div class="col-sm-1"></div>
<div class="col-sm-4">
<h2 class="text-center">
Fill out this form and we will get back to you<span class="glyphicon glyphicon-hand-right"></span>
</h2>
<!-- <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d7245780.082381814!2d-88.29713116153964!3d27.53212533124578!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x88c1766591562abf%3A0xf72e13d35bc74ed0!2sFlorida!5e0!3m2!1sen!2s!4v1470659148428" class="img-responsive" frameborder="0" style="border:0" allowfullscreen></iframe>
-->
<h3 class="text-center"><strong>Bangalore Office</strong></h3>
<iframe src="http://maps.google.com/maps?q=12.987510,77.620491 &z=13&output=embed" width="300" height="200" frameborder="0" style="border:0"></iframe>
<h3 class="text-center"><strong>Kerala Office</strong></h3>
<iframe src="http://maps.google.com/maps?q=9.988126,76.295285 &z=13&output=embed" width="300" height="200" frameborder="0" style="border:0"></iframe>
</div>
<div class="col-sm-6" style="line-height:1.45;">
<h1 class="text-center contact"> Contact Us</h1>
<form action="" method="POST" id="form_id" name="myform">
<div class="row form-group">
<div class="col-sm-2"></div>
<div class="col-sm-1">
<label>Name</label>
</div>
<div class="col-sm-9">
<input type="text" id="name" class="form-control" placeholder="Enter Your Name">
<i id="nameerror"></i>
</div>
</div><br>
<div class="row form-group">
<div class="col-sm-2"></div>
<div class="col-sm-1">
<label>Mobile</label>
</div>
<div class="col-sm-9">
<input type="text" id="mobile" class="form-control" placeholder="Enter Your Mobile Number">
<i id="moberror"></i>
</div>
</div><br>
<div class="row form-group">
<div class="col-sm-2"></div>
<div class="col-sm-1">
<label style="margin-left:0px;">Email </label>
</div>
<div class="col-sm-9">
<input type="email" id="email" class="form-control"placeholder="Enter Your Email Id">
<i id="emailerror"></i>
</div>
</div><br>
<div class="row form-group">
<div class="col-sm-2"></div>
<div class="col-sm-1">
<label>Country</label>
</div>
<div class="col-sm-9">
<input type="text" id="country" class="form-control" placeholder="Enter Your Country Name">
<i id="countryerror"></i>
</div>
</div><br>
<div class="row form-group">
<div class="col-sm-2"></div>
<div class="col-sm-1">
<label>City</label>
</div>
<div class="col-sm-9">
<input type="text" id="city" class="form-control"placeholder="Enter Your City Name">
<i id="cityerror"></i>
</div>
</div><br>
<div class="row form-group">
<div class="col-sm-2"></div>
<div class="col-sm-1">
<label>Query</label>
</div>
<div class="col-sm-9">
<textarea type="text" class="form-control" id="query"placeholder="Enter Your Query here(optional)"></textarea>
<i id="queryerror"></i>
</div>
</div>
<div class="row form-group">
<div class="col-sm-1"></div>
<div class="col-sm-2"></div>
<div class="col-sm-6">
<span class="code"></strong>Security Code <span id="securitycode"></span></span>
<input type="number" id="security" class="form-control" placeholder="Enter the security code">
<i id="codeerror"></i><br>
<div class="form-group text-center">
<div class="col-sm-2"></div>
<input type="button" class="btn btn-warning" name="sub" value="Submit" onclick="pagetest()" id="submit_btn"/>
<button id="Button1" style="display:none;">Please wait..</button>
</div>
</div>
</div>
</div>
</form>
<script>
var val =Math.floor(1000 + Math.random() * 9000);
document.getElementById("securitycode").innerHTML = val;
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCXRmYpTXDBP7vdQ-2fy11OqoKGUuGfcxI&callback=initMap">
</script>
</body>
</html>
Replace your pagetest() function with this function code below and check, I'm using jQuery call here after validation check:
function pagetest(){
var name= document.getElementById("name").value;
var filt = /^[a-zA-Z]+$/;
if (!name.match(filt)){
document.getElementById("name").style.borderColor="red";
document.getElementById("nameerror").innerHTML='Name should not contain any number or special characters';
document.getElementById("nameerror").style.color='red';
}
else{
document.getElementById("name").style.borderColor="green";
document.getElementById("nameerror").innerHTML='valid name';
document.getElementById("nameerror").style.color='green';
}
var number=document.getElementById("mobile").value;
if(number.length!=10)
{
document.getElementById("mobile").style.borderColor="red";
document.getElementById("moberror").innerHTML="Number should be exactly 10 digits and not less than or more than that";
document.getElementById("moberror").style.color='red';
}
else
{
document.getElementById("mobile").style.borderColor="green";
document.getElementById("moberror").innerHTML="valid number";
document.getElementById("moberror").style.color='green';
}
var email = document.getElementById("email").value;
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,3})+$/;
if (!filter.test(email)) {
document.getElementById("email").style.borderColor="red";
document.getElementById("emailerror").innerHTML="Please provide a valid email address";
document.getElementById("emailerror").style.color="red";
}
else{
document.getElementById("email").style.borderColor="green";
document.getElementById("emailerror").innerHTML='valid email address';
document.getElementById("emailerror").style.color='green';
}
var country= document.getElementById("country").value;
var filt = /^[a-zA-Z]+$/;
if (!country.match(filt)) {
document.getElementById("country").style.borderColor="red";
document.getElementById("countryerror").innerHTML='country should not contain any number or special characters';
document.getElementById("countryerror").style.color='red';
}
else{
document.getElementById("country").style.borderColor="green";
document.getElementById("countryerror").innerHTML='Valid Country name';
document.getElementById("countryerror").style.color='green';
}
var city= document.getElementById("city").value;
var filt = /^[a-zA-Z]+$/;
if (!city.match(filt)) {
document.getElementById("city").style.borderColor="red";
document.getElementById("cityerror").innerHTML='city should not contain any number or special characters';
document.getElementById("cityerror").style.color='red';
}
else{
document.getElementById("city").style.borderColor="green";
document.getElementById("cityerror").innerHTML='Valid city name';
document.getElementById("cityerror").style.color='green';
}
/* var reg = /[^A-Za-z]/;
if ((reg.test(query) == false) && (query ==""))
{
document.getElementById('query').style.borderColor="red";
document.getElementById('queryerror').innerHTML="This field is required";
}
else{
document.getElementById("query").style.borderColor="green";
document.getElementById("queryerror").innerHTML ="";
}*/
var security = document.getElementById("security").value;
var securitycode = document.getElementById("securitycode").innerHTML;
if(security ==securitycode){
document.getElementById("security").style.borderColor="";
document.getElementById("codeerror").innerHTML="Code matched";
document.getElementById("codeerror").style.color='green';
}
else{
document.getElementById("security").style.borderColor="red";
document.getElementById("codeerror").innerHTML="Code didn't match or emplty";
document.getElementById("codeerror").style.color='red';
var val =Math.floor(1000 + Math.random() * 9000);
document.getElementById("securitycode").innerHTML =val;
security.focus;
}
$('#Button1').hide();
$('input[name=sub]').show();
if( (name!="") && (email!="") && (number!="") && (country!="") && (city!="") && (security!=""))
{
$('#Button1').show();
$('input[name=sub]').hide();
// $('#form_id').submit(); //uncomment if want to submit after validation
}
}

Step by Step Modal bootstrap

I'm trying to make a MODAL step by step validating each step, but I can only validate the input with error, but I can not validate the select.
wanted that when the value of the select is equal to ZERO (0) the validation occurs as well.
Could someone help me with this JS? I would be extremely grateful.
$(document).ready(function () {
var navListItems = $('div.setup-panel div a'),
allWells = $('.setup-content'),
allNextBtn = $('.nextBtn');
allWells.hide();
navListItems.click(function (e) {
e.preventDefault();
var $target = $($(this).attr('href')),
$item = $(this);
if (!$item.hasClass('disabled')) {
navListItems.removeClass('btn-primary').addClass('btn-default');
$item.addClass('btn-primary');
allWells.hide();
$target.show();
$target.find('input:eq(0)').focus();
$target.find('select:eq(0)').focus();
}
});
allNextBtn.click(function(){
var curStep = $(this).closest(".setup-content"),
curStepBtn = curStep.attr("id"),
nextStepWizard = $('div.setup-panel div a[href="#' + curStepBtn + '"]').parent().next().children("a"),
curInputs = curStep.find("input[type='text'],input[type='url'],select[type='text']"),
isValid = true;
$(".form-group").removeClass("has-error");
for(var i=0; i<curInputs.length; i++){
if (!curInputs[i].validity.valid){
isValid = false;
$(curInputs[i]).closest(".form-group").addClass("has-error");
}
}
if (isValid)
nextStepWizard.removeAttr('disabled').trigger('click');
});
$('div.setup-panel div a.btn-primary').trigger('click');
});
<div class="container">
<div class="row">
<h2>Multistep form wizard on modal</h2>
<div class="center"><button data-toggle="modal" data-target="#requestform" class="btn btn-primary center-block">Click Me</button></div>
</div>
</div>
<div class="modal fade" id="requestform" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h3 class="modal-title" id="lineModalLabel">Proposta</h3>
</div>
<div class="modal-body">
<!-- Steps starts here -->
<div class="requestwizard">
<div class="requestwizard-row setup-panel">
<div class="requestwizard-step">
1
<p>Selecione um contato</p>
</div>
<div class="requestwizard-step">
2
<p>Selecione um curso</p>
</div>
<div class="requestwizard-step">
3
<p>Forma de pagamento</p>
</div>
</div>
</div>
<br>
<form role="form">
<div class="row setup-content" id="step-1">
<div class="col-xs-12">
<div class="col-md-12">
<div class="form-group">
<input maxlength="100" type="text" required="required" class="form-control" placeholder="Contato" />
</div>
<hr>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button" >Próximo</button>
</div>
</div>
</div>
<div class="row setup-content" id="step-2">
<div class="col-xs-12">
<div class="col-md-12">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<select class="form-control custom-select" id="filtercountry">
<option value="0" class="selectcountry">Country</option>
<option value="201" class="selectcountry">Australia</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<select class="form-control custom-select" id="filtercity">
<option value="0" class="selectcity">City</option>
<option value="101" class="selectcity">California</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<select class="form-control custom-select" id="filterregion">
<option value="0" class="selectregion">Region</option>
<option value="3" class="selectregion">Brazil</option>
</select>
</div>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<input maxlength="200" type="text" required="required" class="form-control" placeholder="Curso" />
</div>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button" >Próximo</button>
</div>
</div>
</div>
<div class="row setup-content" id="step-3">
<div class="col-xs-12">
<div class="col-md-12">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="control-label"><spring:message code="label.firstinstallment"/></label>
<input type="text" class="form-control" placeholder="First installment" id="finstallment" name="finstallment" required>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label"><spring:message code="label.numberparcels"/></label>
<select class="form-control custom-select" name="parcels" required>
<option value="0">0</option>
<option value="1">1</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label"><spring:message code="label.firstinvoice"/></label>
<input type="date" class="form-control" placeholder="Invoice maturity" name="expiration_date" required>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label class="control-label"><spring:message code="label.selectpaymentplan"/></label>
<select class="form-control custom-select" name="payment_plan" required>
<option value="1">Bank slip</option>
</select>
</div>
</div>
</div>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button" >Enviar</button>
</div>
</div>
</div>
</form>
<!-- Form ends here -->
</div>
</div>
</div>
</div>
you need to check for the control type in the for loop inside allNextBtn.click event like this:
for(var i=0; i<curInputs.length; i++){
//if the control is select check the selected index if it is ZERO
if ( $(curInputs[i]).is('select') && (curInputs[i].selectedIndex === 0)
{
isValid = false;
}
//else check control validity
else if (!curInputs[i].validity.valid)
{
isValid = false;
}
if(!isValid)
{
$(curInputs[i]).closest(".form-group").addClass("has-error");
}
}
and change this line:
curInputs = curStep.find("input[type='text'],input[type='url'],select[type='text']"),
to this:
curInputs = curStep.find("input[type='text'],input[type='url'],select"),
here is the full js code:
$(document).ready(function () {
var navListItems = $('div.setup-panel div a'),
allWells = $('.setup-content'),
allNextBtn = $('.nextBtn');
allWells.hide();
navListItems.click(function (e) {
e.preventDefault();
var $target = $($(this).attr('href')),
$item = $(this);
if (!$item.hasClass('disabled')) {
navListItems.removeClass('btn-primary').addClass('btn-default');
$item.addClass('btn-primary');
allWells.hide();
$target.show();
$target.find('input:eq(0)').focus();
$target.find('select:eq(0)').focus();
}
});
allNextBtn.click(function(){
var curStep = $(this).closest(".setup-content"),
curStepBtn = curStep.attr("id"),
nextStepWizard = $('div.setup-panel div a[href="#' + curStepBtn + '"]').parent().next().children("a"),
curInputs = curStep.find("input[type='text'],input[type='url'],select"),
isValid = true;
$(".form-group").removeClass("has-error");
//BEGIN EDIT
for(var i=0; i<curInputs.length; i++){
//if the control is select check the selected index if it is ZERO
if ( $(curInputs[i]).is('select') && (curInputs[i].selectedIndex === 0))
{
isValid = false;
}
//else check control validity
else if (!curInputs[i].validity.valid)
{
isValid = false;
}
if(!isValid)
{
$(curInputs[i]).closest(".form-group").addClass("has-error");
}
}
//END EDIT
if (isValid)
nextStepWizard.removeAttr('disabled').trigger('click');
});
$('div.setup-panel div a.btn-primary').trigger('click');
});

document.getElementById().value returning empty string instead of value of textfield

I am surprised to see my code which was working fine earlier all of a sudden stopped returning value for document.getElementById('email').value and returning an empty string instead.
Element getting loaded properly :
Element value is coming empty string even with value being entered in textbox :
I don't understand I checked for redundant links or files being included and tried different elements in HTML but no luck.
Please help with this.
Here is the JavaScript code
var flagforvalidforPhone = false;
var flagforvalidforPass = true;
var flagforvalidforConfirm = true;
var flagforvalidforCompany = false;
var flagforvalidforAddr = false;
var flagforvalidforName = false;
var flagforvalidforEmail = true;
var flagforidentification = false;
function Details() {
this.email = "",
this.firstname = "",
this.companyname = "",
this.address = "",
this.city = "",
this.state = "",
this.zip = "",
this.txtPhone = "",
this.password = "",
this.confirm = "",
this.usertype = ""
}
function registerSuccess(val) {
if (val[0] == 1) {
$("#successmessage").show();
$("#successmessage").empty();
$("#successmessage").append('<strong>Success! </strong>' + val[1]);
$("#form1 :input").prop("disabled", true);
}
if (val[0] == 0) {
$("#errormessage").show();
$("#errormessage").empty();
$("#errormessage").append('<strong>Error! Some values are incorrect. </strong>' + val[1]);
}
}
function Fail(val) {
$("#errormessage").show();
$("#errormessage").empty();
$("#errormessage").append('<strong>Error! Some values are incorrect. </strong>' + val[1]);
}
function enabledisableSubmitbutton() {
$('#registerUserForm input').on('keyup blur', function() {
if (flagforvalidforPhone && flagforvalidforPass && flagforvalidforConfirm && flagforvalidforCompany && flagforvalidforAddr && flagforvalidforName && flagforvalidforEmail) {
$('button.btn').prop('disabled', false);
} else {
$('button.btn').prop('disabled', 'disabled');
}
});
}
function validatefields() {
$('#txtPhone').blur(function(e) {
if (document.getElementById('txtPhone').value != "") {
if (validatePhone('txtPhone')) {
$('#txtPhone').closest('.input-group').removeClass('has-error').addClass('has-success');
$('#txtPhoneerror').text("");
flagforvalidforPhone = true;
} else {
$('#txtPhone').closest('.input-group').removeClass('success').addClass('has-error');
$('#txtPhoneerror').text("Please enter correct telephone number");
flagforvalidforPhone = false;
}
}
});
$('#password').blur(function(e) {
if (document.getElementById('password').value != "" && document.getElementById('confirm').value != "") {
if (validatePassword()) {
$('#confirm').closest('.input-group').removeClass('has-error').addClass('has-success');
$('#confirmerror').text("");
flagforvalidforPass = true;
} else if (document.getElementById('password').value.length < 8) {
$('#password').closest('.input-group').removeClass('success').addClass('has-error');
$('#passworderror').text("");
flagforvalidforPass = false;
} else {
$('#confirm').closest('.input-group').removeClass('success').addClass('has-error');
$('#confirmerror').text("Passwords do not match");
flagforvalidforPass = false;
}
}
});
$('#confirm').blur(function(e) {
if (document.getElementById('password').value != "") {
if (validatePassword()) {
$('#confirm').closest('.input-group').removeClass('has-error').addClass('has-success');
$('#confirmerror').text("");
flagforvalidforConfirm = true;
flagforvalidforPass = true;
} else {
$('#confirm').closest('.input-group').removeClass('success').addClass('has-error');
$('#confirmerror').text("Passwords do not match");
flagforvalidforConfirm = false;
flagforvalidforPass = false;
}
}
});
$('#companyName').blur(function(e) {
if (document.getElementById('companyName').value.length < 2) {
$('#companyName').closest('.input-group').removeClass('success').addClass('has-error');
$('#companyNameerror').text("Please enter a valid company name");
flagforvalidforCompany = false;
} else {
$('#companyName').closest('.input-group').removeClass('has-error').addClass('has-success');
$('#companyNameerror').text("");
flagforvalidforCompany = true;
}
});
$('#Address').blur(function(e) {
if (document.getElementById('Address').value.length < 2) {
$('#Address').closest('.input-group').removeClass('success').addClass('has-error');
$('#Addresserror').text("Please enter a valid Address");
flagforvalidforAddr = false;
} else {
$('#Address').closest('.input-group').removeClass('has-error').addClass('has-success');
$('#Addresserror').text("");
flagforvalidforAddr = true;
}
});
$('#name').blur(function(e) {
if (document.getElementById('name').value.length < 2) {
$('#name').closest('.input-group').removeClass('success').addClass('has-error');
$('#nameerror').text("Please enter a valid name");
flagforvalidforName = false;
} else {
$('#name').closest('.input-group').removeClass('has-error').addClass('has-success');
$('#nameerror').text("");
flagforvalidforName = true;
}
});
$('#zipCode').blur(function(e) {
if (document.getElementById('zipCode').value.length < 5) {
$('#zipCode').closest('.input-group').removeClass('success').addClass('has-error');
$('#zipCodeerror').text("Please enter a valid zipcode");
return false;
} else {
$('#zipCode').closest('.input-group').removeClass('has-error').addClass('has-success');
$('#zipCodeerror').text("");
}
});
$('#email').blur(function(e) {
if (document.getElementById('email') != null && !isValidEmailAddress(document.getElementById('email').value)) {
$('#email').closest('.input-group').removeClass('success').addClass('has-error');
$('#emailerror').text("Please enter a correct email address");
flagforvalidforEmail = false;
} else {
$('#email').closest('.input-group').removeClass('has-error').addClass('has-success');
$('#emailerror').text("");
flagforvalidforEmail = true;
}
});
$('#state').blur(function(e) {
if (document.getElementById('state') != null && document.getElementById('state').value == "") {
$('#state').closest('.input-group').removeClass('success').addClass('has-error');
$('#stateerror').text("Please select a state");
return false;
} else {
$('#state').closest('.input-group').removeClass('has-error').addClass('has-success');
$('#stateerror').text("");
}
});
$('#city').blur(function(e) {
if (document.getElementById('city') != null && document.getElementById('city').value == "") {
$('#city').closest('.input-group').removeClass('success').addClass('has-error');
$('#cityerror').text("Please select a city");
return false;
} else {
$('#city').closest('.input-group').removeClass('has-error').addClass('has-success');
$('#cityerror').text("");
}
});
$('#identification').blur(function(e) {
if (document.getElementById('identification').value.length < 6) {
$('#identification').closest('.input-group').removeClass('success').addClass('has-error');
$('#identificationerror').text("Please enter valid identification number");
return false;
} else {
$('#identification').closest('.input-group').removeClass('has-error').addClass('has-success');
$('#identificationerror').text("");
}
});
}
function validatePassword() {
if (document.getElementById('password').value.length < 8 || document.getElementById('password').value != document.getElementById('confirm').value) {
return false;
} else {
return true;
}
}
function isValidEmailAddress(emailAddress) {
var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")#(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
return pattern.test(emailAddress);
}
function Signup() {
var atLeastOneIsChecked = $('input:checkbox:checked').map(function() {
return this.value;
}).get();
alert(atLeastOneIsChecked);
if (atLeastOneIsChecked == null) {
confirm("Please select the type of user..!!")
} else {
var det = null;
det = new Details();
det.email = document.getElementById('email').value;
det.firstname = document.getElementById('name').value;
det.companyname = document.getElementById('companyName').value;
det.address = document.getElementById('Address').value;
det.city = document.getElementById('city').value;
det.state = document.getElementById('state').value;
det.zip = document.getElementById('zipCode').value;
det.txtPhone = document.getElementById('txtPhone').value;
det.password = document.getElementById('password').value;
det.confirm = document.getElementById('confirm').value;
var usertypeVal = atLeastOneIsChecked[0];
for (var usrtype = 1; usrtype < atLeastOneIsChecked.length; usrtype++) {
usertypeVal += "," + atLeastOneIsChecked[usrtype];
}
det.usertype = usertypeVal;
var str = JSON.stringify(det);
PageMethods.RegisterUserDetails(str, onSucess, onError);
setTimeout(fade_out, 200);
function fade_out() {
$("#errormessage").fadeOut().empty();
$("#successmessage").fadeOut().empty();
}
}
}
function onSucess(val) {
if (val[0] == 1) {
$("#successmessage").show();
$("#successmessage").empty();
$("#errormessage").empty();
$("#successmessage").append('<strong>Success! </strong>' + val[1]);
//disableCropForm();
//setcolorforPolygon(drawnPolygon, valuefirst);
//$('#registerCropForm').trigger("reset");
}
if (val[0] == 0) {
$("#errormessage").show();
$("#errormessage").empty();
$("#errormessage").append('<strong>Error! Some values are incorrect. </strong>' + val[1]);
}
}
function onError(val) {
$("#errormessage").show();
$("#errormessage").empty();
$("#errormessage").append('<strong>Error! Some values are incorrect. </strong>' + val[1]);
}
$(document).ready(function() {
validatefields();
enabledisableSubmitbutton();
});
$(function() {
$('#search').on('keyup', function() {
var pattern = $(this).val();
$('.searchable-container .items').hide();
$('.searchable-container .items').filter(function() {
return $(this).text().match(new RegExp(pattern, 'i'));
}).show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<%# Page Language="C#" AutoEventWireup="true" CodeFile="RegisterNewUser.aspx.cs" Inherits="WebContent_RegisterNewUser" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="../CSS/bootstrap.css">
<link rel="stylesheet" type="text/css" href="css/Register.css">
<script type="text/javascript" src="../javascript/bootstrap.js"></script>
<script type="text/javascript" src="/WebContent/Javascript/registerNew.js"></script>
<script type="text/javascript" src="/WebContent/Javascript/countries.js"></script>
<!-- Website Font style -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css">
<!-- Google Fonts -->
<link href='https://fonts.googleapis.com/css?family=Passion+One' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Raleway' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="css/landingPage.css">
<title>Admin</title>
<script>
$.get("HeaderNav.html", function(data) {
$("#header").replaceWith(data);
});
</script>
</head>
<body>
<!-- /.header -->
<div id="header">
</div>
<!-- /.header end -->
<div class="container">
<div class="row main">
<div class="panel-heading">
<div class="panel-title text-center">
<h1 class="title" style="color: #1d0000">Hit the Target</h1>
<hr />
</div>
</div>
<div class="main-login main-center">
<div id="messages" class="hide" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span>
</button>
<div id="messages_content"></div>
</div>
<div class="alert alert-danger" id="errormessage" style="display: none"></div>
<div class="alert alert-success" id="successmessage" style="display: none"></div>
<form id="registerUserForm" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" ScriptMode="Release" EnablePageMethods="true"></asp:ScriptManager>
<div class="form-group">
<label for="name" class="cols-sm-2 control-label">Your Name</label>
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-user fa" aria-hidden="true"></i></span>
<input type="text" class="form-control" name="name" id="name" placeholder="Enter your Name" required="required" />
</div>
<span class="errorspan" id="nameerror"></span>
</div>
</div>
<div class="form-group">
<label for="email" class="cols-sm-2 control-label">Your Email</label>
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope fa" aria-hidden="true"></i></span>
<input type="text" class="form-control" name="email" id="email" placeholder="Enter your Email" />
</div>
<span class="errorspan" id="emailerror"></span>
</div>
</div>
<div class="form-group">
<label for="companyName" class="cols-sm-2 control-label">Company Name</label>
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-users fa" aria-hidden="true"></i></span>
<input type="text" class="form-control" name="companyName" id="companyName" placeholder="Enter your Company Name" />
<span class="glyphicon form-control-feedback"></span>
</div>
<span class="errorspan" id="companyNameerror"></span>
</div>
</div>
<div class="form-group">
<label for="Address" class="cols-sm-2 control-label">Address</label>
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-building fa" aria-hidden="true"></i></span>
<input type="text" class="form-control" name="Address" id="Address" placeholder="Enter your Address" required />
</div>
<span class="errorspan" id="Addresserror"></span>
</div>
</div>
<div class="form-group">
<label for="Address" class="cols-sm-2 "></label>
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon ">State</span>
<select onchange="print_city('city',this.selectedIndex);" id="state" name="state" class="form-control" required></select>
<span class="input-group-addon ">City</span>
<select id="city" name="city" class="form-control" required></select>
<script type="text/javascript ">
print_state("state");
</script>
<span class="input-group-addon">Zip</span>
<input type="text" class="form-control" name="zipCode" id="zipCode" placeholder="Enter your Zip" required />
</div>
<span class="errorspan" id="zipCodeerror"></span>
<span class="errorspan" id="cityerror"></span>
<span class="errorspan" id="stateerror"></span>
</div>
</div>
<div class="form-group">
<label for="txtPhone" class="cols-sm-2 control-label">Phone Number</label>
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-phone fa" aria-hidden="true"></i></span>
<input type="password" class="form-control" name="txtPhone" id="txtPhone" placeholder="Enter your Phone Number" required />
</div>
<span class="errorspan" id="txtPhoneerror"></span>
</div>
</div>
<div class="form-group">
<label for="password" class="cols-sm-2 control-label">Password</label>
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-lock fa" aria-hidden="true"></i></span>
<input type="password" class="form-control" name="password" id="password" placeholder="Enter your Password" required />
</div>
<span class="errorspan" id="passworderror"></span>
</div>
</div>
<div class="form-group">
<label for="confirm" class="cols-sm-2 control-label">Confirm Password</label>
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-lock fa" aria-hidden="true"></i></span>
<input type="password" class="form-control" name="confirm" id="confirm" placeholder="Confirm your Password" required />
</div>
<span class="errorspan" id="confirmerror"></span>
</div>
</div>
<div class="form-group">
<h5 style="font-weight: bold" class="control-label">Please select what type of user you are:- </h5>
<div class="searchable-container">
<div class="items col-xs-5 col-sm-5 col-md-3 col-lg-3">
<div class="info-block block-info clearfix">
<div data-toggle="buttons" class="btn-group bizmoduleselect">
<label class="btn btn-default">
<div class="bizcontent">
<input type="checkbox" name="var_id[]" autocomplete="off" value="1">
<span class="glyphicon glyphicon-ok glyphicon-lg"></span>
<h5>Producer</h5>
</div>
</label>
</div>
</div>
</div>
<div class="items col-xs-5 col-sm-5 col-md-3 col-lg-3">
<div class="info-block block-info clearfix">
<div data-toggle="buttons" class="btn-group bizmoduleselect">
<label class="btn btn-default">
<div class="bizcontent">
<input type="checkbox" name="var_id[]" autocomplete="off" value="2">
<span class="glyphicon glyphicon-ok glyphicon-lg"></span>
<h5>Applicator</h5>
</div>
</label>
</div>
</div>
</div>
<div class="items col-xs-5 col-sm-5 col-md-3 col-lg-3">
<div class="info-block block-info clearfix">
<div data-toggle="buttons" class="btn-group bizmoduleselect">
<label class="btn btn-default">
<div class="bizcontent">
<input type="checkbox" name="var_id[]" autocomplete="off" value="3">
<span class="glyphicon glyphicon-ok glyphicon-lg"></span>
<h5>Consultant</h5>
</div>
</label>
</div>
</div>
</div>
</div>
</div>
<div class="form-group" style="padding-top:7em">
<label for="confirm" class="cols-sm-2 control-label">Enter your Identification number</label>
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-lock fa" aria-hidden="true"></i></span>
<input type="text" class="form-control" id="identification" placeholder="Please provide your Identification number" required="required">
</div>
<span class="errorspan" id="identificationerror"></span>
</div>
</div>
<div class="form-group ">
<button type="button" class="btn btn-primary btn-lg btn-block login-button" id="userSubmit" disabled="disabled" onclick="Signup()">Register</button>
</div>
</form>
</div>
</div>
</div>
<!-- Footer -->
<div id="footer">
</div>
</body>
<script>
$.get("footer.html", function(data) {
$("#footer").replaceWith(data);
});
</script>
</html>
Found the issue..!!
The id of the email field cannot be 'email' and similarly for password field cannot be 'password' because these are reserved keywords by javascript I guess.!!

ADD button is still disabled, even after the validation is satisfied

I have been working on the below screen where I have a drop down for selecting a file/folder type(file type being default). When I Provide a valid file Path first, the ADD button is not getting enabled. After, I select the Folder from drop down and provide a valid folder path , then the ADD button is getting enabled. I think , the Problem is with the validation I'm using i.e.:ng-disabled="conditionForm.$invalid" Can you tell me where I am doing the mistake !!? Providing Code and screen shots below.
<form name="conditionForm" class="form-horizontal" role="form" novalidate="novalidate">
<div class="form-group">
<label class="col-sm-2 control-label no-padding-right">Type :</label>
<div class="col-sm-3" style="width:110px">
<select name="fileorfoldertype" id="ddlFileOrFolderType" class="form-control" ng-init="fileorfoldertype = fileorfoldertypes[0]" style="width:100px" ng-model="fileorfoldertype" ng-options="fileorfolderpath as fileorfolderpath.name for fileorfolderpath in fileorfoldertypes" ng-change="change()" required></select>
</div>
<div class="form-group" id="filepath">
<label class="col-sm-2 control-label no-padding-right">File Path:</label>
<div>
<div class="col-sm-3" style="border:0px solid red;">
<input name="filespath" id="txtfilepath" type="text" class="form-control" ng-model="filespath" ng-pattern="/^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.jpg|.txt|.doc|.xls|.gif|.GIF|.exe|.pdf|.xml|.cvv|.dll)$/" required>
</div>
<div class="col-sm-3">
<p ng-show="conditionForm.filespath.$error.required" class="help-block" style="display: inline; float: left;">File Path is required and cannot be empty.</p>
<p ng-show="conditionForm.filespath.$error.pattern" class="help-block" style="display: inline; float: left;">The input is not a valid File Path.</p>
</div>
</div>
</div>
<div class="form-group" id="folderpath" style="display:none">
<label class="col-sm-2 control-label no-padding-right">Folder Path:</label>
<div>
<div class="col-sm-3" style="border:0px solid red;">
<input name="folderspath" id="txtfolderpath" type="text" class="form-control" ng-model="folderspath" ng-pattern="/^([A-Z|a-z]:\\[^*|><>?\n]*)|(\\\\.*?\\.*)$/" required>
</div>
<div class="col-sm-3">
<p ng-show="conditionForm.folderspath.$error.required" class="help-block" style="display: inline; float: left;">Folder Path is required and cannot be empty.</p>
<p ng-show="conditionForm.folderspath.$error.pattern" class="help-block" style="display: inline; float: left;">The input is not a valid Folder Path.</p>
</div>
</div>
</div>
</div>
<div class="form-group">
<div id="addbutton" class="col-sm-3" style="padding-left:590px;">
<button style="width:70px" class="btn" type="submit" ng-disabled="conditionForm.$invalid" ng-click="add()">
Add
</button>
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<div class="col-sm-10 mail-container">
<div class="mail-header">
<ul class="header-buttons">
<li>
<a class="tooltip-primary" ng-click="deleteCondition()"><i class="glyphicon glyphicon-remove"></i></a>
</li>
</ul>
</div>
</div>
<div class="col-sm-10" id="divGrid">
<table id="jQFileManagement"></table>
<div id="jqGridPager"></div>
</div>
</div>
</div>
</form>
$scope.fileorfoldertypes = [
{ id: "0", name: "File" },
{ id: "1", name: "Folder" },
];
$scope.change = function () {
if ($scope.fileorfoldertype.id === '0')
{
$("#folderpath").hide();
$("#filepath").show();
document.getElementById('txtfilepath').value = "";
document.getElementById('txtfolderpath').disabled = true;
document.getElementById("txtfilepath").disabled = false;
}
else if ($scope.fileorfoldertype.id === '1') {
$("#folderpath").show();
$("#filepath").hide();
document.getElementById('txtfolderpath').value = "";
document.getElementById('txtfilepath').disabled = true;
document.getElementById("txtfolderpath").disabled = false;
}
}
$scope.add = function () {
var filetype;
if ($scope.fileorfoldertype.id == "1") {
filetype = 1;
folderOrFilePath = $scope.folderspath;
var folderdata = {
typeId: filetype,
folderOrFilePath: $scope.folderspath
}
}
else {
filetype = 2;
folderOrFilePath = $scope.filespath;
var folderdata = {
typeId: filetype,
folderOrFilePath: $scope.filespath
}
}
selectedfolders.unshift(folderdata);
if (selectedfolders != "") {
$("#jQFileManagement")
.jqGrid('setGridParam',
{
datatype: 'local',
data: selectedfolders
})
.trigger("reloadGrid");
}
$scope.filespath = '';
$scope.folderspath = '';
$scope.conditionForm.$invalid = true;
};

Form field values sum in jQuery

I can't seem to get this to work for a project I'm doing. Basically I'm trying to get the values in the "Revenue" fields to total at the bottom in the "Total Revenue" field.
I've made a JSFiddle which hopefully will make it easier to understand-
HTML markup:
<div class="form-group">
<label class="control-label col-md-2">April</label>
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">$</span><input class="form-control" name="AprilInput" placeholder="eg. 35,328" type="text" id="AprilInput"></input>
</div>
</div>
<label class="control-label col-md-1">Revenue</label>
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">$</span><input class="form-control" name="Output" id="AprilOutput" placeholder="0" type="text" readonly></input>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">May</label>
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">$</span><input class="form-control" name="MayInput" placeholder="eg. 35,328" type="text" id="MayInput"></input>
</div>
</div>
<label class="control-label col-md-1">Revenue</label>
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">$</span><input class="form-control1" name="Output" id="MayOutput" placeholder="0" type="text" readonly></input>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">June</label>
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">$</span><input class="form-control" name="JuneInput" placeholder="eg. 35,328" type="text" id="JuneInput"></input>
</div>
</div>
<label class="control-label col-md-1">Revenue</label>
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">$</span><input class="form-control1" name="Output" id="JuneOutput" placeholder="0" type="text" readonly></input>
</div>
</div>
</div>
<br/>
<span class="form-horizontal">
<div class="row">
<div class="col-lg-12">
<div class="widget-container fluid-height clearfix">
<div class="heading">
<i class="icon-reorder"></i>Annual Total
</div>
<div class="widget-content padded">
<div class="form-group">
<label class="control-label col-md-6">Total Revenue</label>
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">$</span><input class="form-control" name="TotalOutput" id="TotalOutput" placeholder="0" type="text" readonly></input>
</div>
</div>
</div>
You could tidy the code up a little:
function SetupInput(obj,output,sumfunction){
$(obj).keyup(function(){
var n = parseInt($(this).val());
var n = this.value.replace(/,/g, "");
if(n <= 155000) {
$(output).val(numberWithCommas((n/100*70).toFixed(0)));
}
else if(n <= 175000) {
$(output).val(numberWithCommas((n/100*75).toFixed(0)));
}
else {
$(output).val(numberWithCommas((n/100*80).toFixed(0)));
}
sumfunction();
});
}
SetupInput($('#AprilInput')[0],$('#AprilOutput')[0],calculateSum);
SetupInput($('#MayInput')[0],$('#MayOutput')[0],calculateSum);
SetupInput($('#JuneInput')[0],$('#JuneOutput')[0],calculateSum);
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");
}
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".form-control1").each(function() {
//add only if the value is number
var value=this.value.replace(',','');//remove ','
if(!isNaN(value) && value.length!=0) {
sum += parseFloat(value);
console.log(this.id,sum);
}
});
//.toFixed() method to roundoff the final sum
$("#TotalOutput").val(sum.toFixed(0));
}
Check out the jsfiddle: http://jsfiddle.net/2jY6P/43/
You are looping though Output tag. Change it to .form-contol:
$(".form-control").each(function() { /* ... */ }
And not .html, but .val():
`$("#TotalOutput").val(sum.toFixed(0));`
i edited you code: http://jsfiddle.net/2jY6P/38/
changed:
$(document).ready(function(){
//iterate through each textboxes and add keyup
//handler to trigger sum event
$("input[name='Output']").keyup(function(){
calculateSum();
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$("input[name='Output']").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method to roundoff the final sum
$("#TotalOutput").val(sum.toFixed(0));
}
$('Output') should be input $("[name='Output']")
$("#TotalOutput").html(sum.toFixed(0));
should be $("#TotalOutput").val(sum.toFixed(0));
I put some changes in
http://jsfiddle.net/2jY6P/39/
$(document).keyup(function() {
var sumRevenue = 0;
$.each($(".revenue"), function() {
var val = $.trim($(this).val());
if(val != "")
sumRevenue += parseFloat(val);
});
$("#sumrevenue").val(sumRevenue);
});
function calculateTotalREv(){
var totalRev = 0;
$("input[name='Output']").each(function() {
totalRev = eval(total+parseFloat($(this).val()));
});
alert(totalRev);
}
calculateTotalREv();

Categories

Resources