Am JavaScript newbie, and i wanted some help.
the above script can validate valid and invalidate credit card / debit
my problem is that, how can i clear the "invalid credit / debit card number" error message when user has started typing again the card
its like i want to auto clear error message when user has re-type again
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<h2>Payment
<img style="visibility: hidden" class="mastercard" src="https://img.icons8.com/color/48/000000/mastercard.png">
<img style="visibility: hidden" class="visacard" src="https://img.icons8.com/color/48/000000/visa.png">
<img style="visibility: hidden" class="discovercard" src="https://img.icons8.com/color/48/000000/discover.png">
<img style="visibility: hidden" class="amexcard" src="https://img.icons8.com/color/48/000000/amex.png">
</h2>
<div class="form-group">
<label for="name-on-card">Name on Card</label>
<input class="cc_name" type="text" name="card-name" class="form-control" placeholder="">
</div>
<div class="form-group">
<label for="cc-number">Credit card number</label>
<input type="text" class="form-control" id="cc_number" name="cc_number" placeholder="" maxlength="20">
<span id="loginError"></span>
</div>
<!--<div class="">
<select class="month_year_select" name="month" id="month">
<option value="">exp month</option>
</select>
</div>
<div class="">
<select class="month_year_select" id="year" name="year">
<option value="">exp year</option>
</select>
</div>-->
<div class="CVV">
<label for="cc-cvv">CVV</label>
<input type="text" class="form-control" id="cc-cvv" name="cc-cvv" placeholder="" maxlength="4">
</div>
<script type="text/javascript">
document.getElementById('cc-cvv').addEventListener('change', CWcheck); //recommended way
document.getElementById('cc_number').onchange = creditCheck; //it is OK too
function CWcheck() { //function name should conventionally start with lower case but isn't big deal
//"this" is the element which fired the event
if (!/^\d{3,4}$/.test(this.value)) {
this.value = '';
this.focus();
alert('CVV is 3 or 4 digits');
}
}
function creditCheck() {
// hide cc logos
var ccImgs = document.querySelectorAll('h2 img');
for (var i = 0, ccImg; ccImg = ccImgs[i]; ++i) {
ccImg.style.visibility = 'hidden';
}
var ccNum = this.value.replace(/\D/g, ''); //remove all non-digits
if (ccNum.length < 15 /*15 is amex*/ || ccNum.length > 16) {
document.getElementById("loginError").innerHTML = "invalid credit / debit card number";
this.focus();
return false;
}
//implement Luhn algorithm
var check = ccNum.split('') //get array
.reverse()
.map(function(el, index) {
return el * (index % 2 + 1); //multiply even positions by 2
})
.join('') //combine array of strings
.split('')
.reduce(function(a, b) { //sum digits
return a + (b - 0);
}, 0);
if (!check || (check % 10)) { //checksum should be none-zero and dividable by 10
document.getElementById("loginError").innerHTML = "invalid credit / debit card number";
this.focus();
return false;
}
//test passed. show card logo
if (/^5[1-5]/.test(ccNum))
document.querySelector('h2 img.mastercard').style.visibility = 'visible';
else if (/^4/.test(ccNum))
document.querySelector('h2 img.visacard').style.visibility = 'visible';
else if (ccNum.length == 15 && /^3[47]/.test(ccNum))
document.querySelector('h2 img.amexcard').style.visibility = 'visible';
else if (/^6011/.test(ccNum))
document.querySelector('h2 img.discovercasd').style.visibility = 'visible';
//and so on
else {
document.getElementById("loginError").innerHTML = "invalid credit / debit card number";
this.focus();
return false;
}
//test passed. format the string
this.value = ccNum
.replace(/^(\d{4})(\d{4})(\d{4})(\d+)$/, '$1 $2 $3 $4');
}
</script>
</body>
</html>
I have added a input event listener to the input, and based on the length of text present in input, I clear the error message (if its length is greater than 0, which marks user has started typing again.)
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<h2>Payment
<img style="visibility: hidden" class="mastercard" src="https://img.icons8.com/color/48/000000/mastercard.png">
<img style="visibility: hidden" class="visacard" src="https://img.icons8.com/color/48/000000/visa.png">
<img style="visibility: hidden" class="discovercard" src="https://img.icons8.com/color/48/000000/discover.png">
<img style="visibility: hidden" class="amexcard" src="https://img.icons8.com/color/48/000000/amex.png">
</h2>
<div class="form-group">
<label for="name-on-card">Name on Card</label>
<input class="cc_name" type="text" name="card-name" class="form-control" placeholder="">
</div>
<div class="form-group">
<label for="cc-number">Credit card number</label>
<input type="text" class="form-control" id="cc_number" name="cc_number" placeholder="" maxlength="20">
<span id="loginError"></span>
</div>
<!--<div class="">
<select class="month_year_select" name="month" id="month">
<option value="">exp month</option>
</select>
</div>
<div class="">
<select class="month_year_select" id="year" name="year">
<option value="">exp year</option>
</select>
</div>-->
<div class="CVV">
<label for="cc-cvv">CVV</label>
<input type="text" class="form-control" id="cc-cvv" name="cc-cvv" placeholder="" maxlength="4">
</div>
<script type="text/javascript">
document.getElementById('cc-cvv').addEventListener('change', CWcheck); //recommended way
document.getElementById('cc_number').onchange = creditCheck; //it is OK too
function CWcheck() { //function name should conventionally start with lower case but isn't big deal
//"this" is the element which fired the event
if (!/^\d{3,4}$/.test(this.value)) {
this.value = '';
this.focus();
alert('CVV is 3 or 4 digits');
}
}
function creditCheck() {
// hide cc logos
var ccImgs = document.querySelectorAll('h2 img');
for (var i = 0, ccImg; ccImg = ccImgs[i]; ++i) {
ccImg.style.visibility = 'hidden';
}
var ccNum = this.value.replace(/\D/g, ''); //remove all non-digits
if (ccNum.length < 15 /*15 is amex*/ || ccNum.length > 16) {
document.getElementById("loginError").innerHTML = "invalid credit / debit card number";
this.focus();
return false;
}
//implement Luhn algorithm
var check = ccNum.split('') //get array
.reverse()
.map(function(el, index) {
return el * (index % 2 + 1); //multiply even positions by 2
})
.join('') //combine array of strings
.split('')
.reduce(function(a, b) { //sum digits
return a + (b - 0);
}, 0);
if (!check || (check % 10)) { //checksum should be none-zero and dividable by 10
document.getElementById("loginError").innerHTML = "invalid credit / debit card number";
this.focus();
return false;
}
//test passed. show card logo
if (/^5[1-5]/.test(ccNum))
document.querySelector('h2 img.mastercard').style.visibility = 'visible';
else if (/^4/.test(ccNum))
document.querySelector('h2 img.visacard').style.visibility = 'visible';
else if (ccNum.length == 15 && /^3[47]/.test(ccNum))
document.querySelector('h2 img.amexcard').style.visibility = 'visible';
else if (/^6011/.test(ccNum))
document.querySelector('h2 img.discovercasd').style.visibility = 'visible';
//and so on
else {
document.getElementById("loginError").innerHTML = "invalid credit / debit card number";
this.focus();
return false;
}
//test passed. format the string
this.value = ccNum
.replace(/^(\d{4})(\d{4})(\d{4})(\d+)$/, '$1 $2 $3 $4');
}
document.querySelector("#cc_number").addEventListener("input", function() {
if (document.querySelector("#cc_number").value.length > 0) {
document.getElementById("loginError").innerHTML = "";
}
})
</script>
</body>
</html>
Based on your code, I'd suggest adding a line to clear the error message into your event handler:
document.getElementById('cc-cvv').addEventListener('change', function() {
document.getElementById("loginError").innerHTML = "";
CWcheck();
});
This will reset the message to an empty string every time a keystroke is read. It'll also show error messages when the check comes back as invalid.
Hopes this helps.
There are multiple ways of doing this. With your current setup you could use a class to show and hide the error rather than adding the innerHTML. This class could just be removed after each change. Example with your code, attached.
document.getElementById('cc-cvv').addEventListener('change', CWcheck); //recommended way
document.getElementById('cc_number').onchange = creditCheck; //it is OK too
function CWcheck() { //function name should conventionally start with lower case but isn't big deal
//"this" is the element which fired the event
if (!/^\d{3,4}$/.test(this.value)) {
this.value = '';
this.focus();
alert('CVV is 3 or 4 digits');
}
}
function creditCheck() {
document.getElementById("loginError").classList.remove('card-error--active')
// hide cc logos
var ccImgs = document.querySelectorAll('h2 img');
for (var i = 0, ccImg; ccImg = ccImgs[i]; ++i) {
ccImg.style.visibility = 'hidden';
}
var ccNum = this.value.replace(/\D/g, ''); //remove all non-digits
if (ccNum.length < 15 /*15 is amex*/ || ccNum.length > 16) {
document.getElementById("loginError").classList.add('card-error--active')
this.focus();
return false;
}
//implement Luhn algorithm
var check = ccNum.split('') //get array
.reverse()
.map(function(el, index) {
return el * (index % 2 + 1); //multiply even positions by 2
})
.join('') //combine array of strings
.split('')
.reduce(function(a, b) { //sum digits
return a + (b - 0);
}, 0);
if (!check || (check % 10)) { //checksum should be none-zero and dividable by 10
document.getElementById("loginError").classList.add('card-error--active')
this.focus();
return false;
}
//test passed. show card logo
if (/^5[1-5]/.test(ccNum))
document.querySelector('h2 img.mastercard').style.visibility = 'visible';
else if (/^4/.test(ccNum))
document.querySelector('h2 img.visacard').style.visibility = 'visible';
else if (ccNum.length == 15 && /^3[47]/.test(ccNum))
document.querySelector('h2 img.amexcard').style.visibility = 'visible';
else if (/^6011/.test(ccNum))
document.querySelector('h2 img.discovercasd').style.visibility = 'visible';
//and so on
else {
document.getElementById("loginError").innerHTML = "invalid credit / debit card number";
this.focus();
return false;
}
//test passed. format the string
this.value = ccNum
.replace(/^(\d{4})(\d{4})(\d{4})(\d+)$/, '$1 $2 $3 $4');
}
.card-error{
display:none;
}
.card-error--active{
display:block;
}
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<h2>Payment
<img style="visibility: hidden" class="mastercard" src="https://img.icons8.com/color/48/000000/mastercard.png">
<img style="visibility: hidden" class="visacard" src="https://img.icons8.com/color/48/000000/visa.png">
<img style="visibility: hidden" class="discovercard" src="https://img.icons8.com/color/48/000000/discover.png">
<img style="visibility: hidden" class="amexcard" src="https://img.icons8.com/color/48/000000/amex.png">
</h2>
<div class="form-group">
<label for="name-on-card">Name on Card</label>
<input class="cc_name" type="text" name="card-name" class="form-control" placeholder="">
</div>
<div class="form-group">
<label for="cc-number">Credit card number</label>
<input type="text" class="form-control" id="cc_number" name="cc_number" placeholder="" maxlength="20">
<span id="loginError" class="card-error">invalid credit / debit card number</span>
</div>
<!--<div class="">
<select class="month_year_select" name="month" id="month">
<option value="">exp month</option>
</select>
</div>
<div class="">
<select class="month_year_select" id="year" name="year">
<option value="">exp year</option>
</select>
</div>-->
<div class="CVV">
<label for="cc-cvv">CVV</label>
<input type="text" class="form-control" id="cc-cvv" name="cc-cvv" placeholder="" maxlength="4">
</div>
</body>
</html>
Related
My find matches function does not seem to be working.
I want to get an array ([]) element by id and do comparisons with it.
The function is supposed to go into the array and generate a random person, then display the match in the text area "showmatches".
I am not sure if the random person is being generated nor if the criteria are being matched in the comparison.
<html>
<head>
<script>
var records = [];
function calculateAge()
{
var dob = document.getElementById('dob').value;
var dobInput = new Date(dob);
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth();
var day = now.getDate();
var birthyear = dobInput.getFullYear();
var birthmonth = dobInput.getMonth();
var birthday = dobInput.getDate();
var bYear = year - birthyear;
var bMonth = month - birthmonth;
var bDay = day - birthday;
if (bYear < 18 || bYear > 75)
{
alert("Age cannot be less than 18 or greater than 75");
return false;
}else{
document.getElementById("age").value = bYear + "years old";
}
//document.getElementById("age").value = bYear + "years old";
}
function showAll()
{
show = document.getElementById("showallpersons").innerHTML=records;
show.value = records.join("\n");
}
(window.onload = () => {
var findmatches=document.getElementById('findmatches');
if(findmatches){
findmatches.addEventListener('click', findMatches, false);
}
function findMatches(e)
{
e.preventDefault();
for(var counter=0; counter<records.length; counter++)
{
var currposn = records[counter].value;
var show = document.getElementById("showallmatches").innerHTML= currposn.fname + currposn.lname;
show.value = currposn.join("\n");
do
{
//From here
var randpson = Math.random() * records.length;
randpson = Math.floor(randpson); //To here works, I know that for sure
//I'm not sure if the conditions for the if statements are correct
if(((randpson.age - currposn.age) <= 10) || ((randpson.age - currposn.age) >= 20))
{
if(((randpson.height - currposn.height) <= 10) || ((randpson.height - currposn.height) >= 20))
{
var display = document.getElementById("showmatches").innerHTML= "Matched to: " +randpson.fname + randpson.lname;
//display.value = "Matched to: " + randpson.fname + randpson.lname;
break;
}
}
} while(counter < 10){
//var newDisplay = document.getElementById("showallmatches").innerHTML= null;
}
//console.log(findMatches());
}
}
})()
(window.onload = () => {
var submit = document.getElementById('submit');
if(submit){
submit.addEventListener('click', addnew, false);
}
function addnew(event)
{
//Prevents default submit event
event.preventDefault();
//Accept values entered in form
var fname = document.getElementById('fname').value;
var mname = document.getElementById('mname').value;
var lname= document.getElementById('lname').value;
var dob= document.getElementById('dob').value;
var gender = document.forms['Information']['gender'].value;
var age = document.getElementById('age').value;
parseInt(age);
var bodyType = document.getElementById('Body Type').value;
var occu= document.getElementById('occu').value;
var height= document.getElementById('height').value;
if (fname==null || fname=="")
{
alert("A first name is required");
return false;
}
if(mname==null || mname=="")
{
alert("A middle initial is required");
return false;
}
if (lname==null || lname=="")
{
alert("A last name is required");
return false;
}
if(dob==null || dob=="")
{
alert("A DOB is required");
return false;
}
if (gender == "")
{
alert("Please select a gender");
return false;
}
if(height <= 170 || height >= 200)
{
alert("A height between 170, not less and 200, not more is required");
return false;
}
if(bodyType==null || bodyType==""){
alert("Please choose a body type");
return false;
}
if(occu==null || occu=="")
{
alert("Please enter an occupation");
return false;
}
//Append To array
records.push(fname);
records.push(mname);
records.push(lname);
records.push(gender);
records.push(age);
records.push(bodyType);
records.push(occu);
records.push(height);
for(i=0;i<records.length;i++)
{
console.log(records[i]);
}
document.getElementById("Information").reset();
}
})()
</script>
</head>
<body>
<div class="wrapper">
<header class="page-header">
<nav>
<button class="cta-contact">Contact Us</button>
</nav>
</header>
</div>
<div class="space">
<h1>
<marquee behavior="scroll" direction="right">What are you waiting for? Find your "one" now.</marquee>
</h1>
</div>
<div class="container">
<form name="Information" id="Information">
<fieldset>
<legend>Personal Information</legend>
First Name:
<input id="fname" type="text" size=40 placeholder='First Name' minlength=4 maxlength=40 required />
<br/><br/>
Middle Initial:
<input id="mname" type="text" size=3 placeholder='M Intial' maxlength=1 required />
<br/><br/>
Last Name:
<input id="lname" type="text" size='40' placeholder='Last Name' minlength='4' maxlength='40' required />
<br/><br/>
Date of Birth
<input id="dob" type="date" onchange="calculateAge()"/>
<br/><br/>
Gender:
<input id="male" type="radio" value='M' name="gender" required/> Male
<input id="female" type="radio" value='F' name="gender" required/> Female
<br/><br/>
Age: <input type="text" id="age" disabled />
<br/>
Body Type:
<select id="Body Type">
<optgroup label="Female" id="FemaleOpt">
<option value="Apple"> Apple </option>
<option value="Pear"> Pear </option>
<option value="Pencil"> Pencil </option>
<option value="Hourglass"> Hourglass </option>
<option value="Round"> Round </option>
</optgroup>
<optgroup label="Male" id="MaleOpt">
<option value="Oval"> Oval </option>
<option value="Triangle"> Triangle </option>
<option value="Rectangle"> Rectangle </option>
<option value="Rhomboid">Rhomboid </option>
<option value="Inverted">Inverted Triangle</option>
</optgroup>
</select>
<br/><br/>
Occupation:
<input id="occu" type="text" size=30 maxlength=30 required />
<br/><br/>
Height(in cm):
<input id="height" type="number" size="3" min="171" max="199" value="" required /><br>
<br/><br/>
<textarea id="showallpersons" name="Show All Persons" onclick="showAll()" disabled></textarea>
<textarea id="showmatches" name="Show All Matches" onclick="findMatches()" disabled></textarea>
<br/><br/>
<button id="submit" type="submit">Submit</button>
<button id="findmatches" type="button">Find Matches</button>
</fieldset>
</form>
</div>
</body>
</html>
Do these steps. First you have two window.onload = () (As you are not using addEventListener only one event will be attached).
Steps:
Keep everything intact, just remove the window.onload from both places. Keep all code inside load intact.
Move the entire code block just to the bottom of the html above closing tag. (Doing so, will make window.onload redundant.)
Put console.log() in the click handler and see if it's working (it will)
Let us know.
NOTE: On other hand there are better way to code this, for e.g wait for DOMContentLoaded for attaching event etc., but it's too big to discuss here. First make this work, then we can recommend better approaches.
Here is the code:
<form class="ui form attached fluid loading segment" onsubmit="return contact(this)">
<div class="field">
<label>Preferred Tour</label>
<div class="field">
<?php
$conn=mysqli_connect('####','####','####','####');
echo '<select required id="tourInfo">';
echo '<option value="" selected disabled>--Preferred Tour--</option>';
$db = mysqli_query($conn, "SELECT `id`,`tourprice`,`tourname` FROM `available_tours`");
while ($d=mysqli_fetch_assoc($db)) {
echo "<option value=".$d['id']." id=".$d['tourname']. " data-price=".$d['tourprice'].">".$d['tourname']."</option>";
}
echo "</select>";
?>
</div>
</div>
<div class="field" id="hiddenTortu" style="display: none;">
<label>Attention</label>
<div class="ui icon">
<p><b>The minimum of people for this tour is 5, less than 5 the tour is not realisable</b></p>
</div>
</div>
<div class="field">
<label>Available Time</label>
<div class="field">
<?php
$conn=mysqli_connect('####','####','####','####');
echo '<select name="gender" required id="timeInfo">';
echo '<option value="" selected disabled>--Preferred Time--</option>';
$db = mysqli_query($conn, "SELECT `time_real` FROM `available_time`");
while ($d=mysqli_fetch_assoc($db)) {
echo "<option value=".$d['time_real'].">".$d['time_real']."</option>";
}
echo "</select>";
?>
</div>
</div>
<div class="two fields">
<div class="field" id="pax">
<label>Please specify the number of People according to the perred tour selection</label>
Here starts the problem with the following script according to the tour selection I'm trying to set up a minimum and maximum so that the user can't choose more numbers for the people on the tour.
The problem is that when the user select first one option, and then realised that the best option is another one, when he/she does another selection the input created with jQuery that was appended remains and because of the new selection a new input is created.
The intention is that if the user chooses option 1 the input append appears according to option one, but if the user regrets and prefers option 2 that the input for the option 1 disappears and a new input according to option 2 appears and so on for the entire if conditions.
<script>
$(document).ready(function(){
$('#tourInfo').on('change', function() {
if ( this.value == '1')
{
$("#pax").append($('<input placeholder="Number of People" type="number" id="peopleInfo" min="1" max="2" value="1" required>'));
(function ($) {
$.fn.restrict = function () {
return this.each(function(){
if (this.type && 'number' === this.type.toLowerCase()) {
$(this).on('change', function(){
var _self = this,
v = parseFloat(_self.value),
min = parseFloat(_self.min),
max = parseFloat(_self.max);
if (v >= min && v <= max){
_self.value = v;
}
else {
_self.value = v < min ? min : max;
}
});
}
});
};
})(jQuery);
$('#peopleInfo').restrict();
}
else if (this.value == '2')
$("#pax").append($('<input placeholder="Number of People" type="number" id="peopleInfo" min="3" max="5" value="3" required>'));
(function ($) {
$.fn.restrict = function () {
return this.each(function(){
if (this.type && 'number' === this.type.toLowerCase()) {
$(this).on('change', function(){
var _self = this,
v = parseFloat(_self.value),
min = parseFloat(_self.min),
max = parseFloat(_self.max);
if (v >= min && v <= max){
_self.value = v;
}
else {
_self.value = v < min ? min : max;
}
});
}
});
};
})(jQuery);
$('#peopleInfo').restrict();
}
else if (this.value == '3')
{
$("#pax").append($('<input placeholder="Number of People" type="number" id="peopleInfo" min="6" max="15" value="6" required>'));
(function ($) {
$.fn.restrict = function () {
return this.each(function(){
if (this.type && 'number' === this.type.toLowerCase()) {
$(this).on('change', function(){
var _self = this,
v = parseFloat(_self.value),
min = parseFloat(_self.min),
max = parseFloat(_self.max);
if (v >= min && v <= max){
_self.value = v;
}
else {
_self.value = v < min ? min : max;
}
});
}
});
};
})(jQuery);
$('#peopleInfo').restrict();
}...
...});
};
})(jQuery);
$('#peopleInfo').restrict();
}
});
});
</script>
</div>
<div class="field">
<label><br>Date of Tour</label>
<input type="text" readonly required id="tourDate" class="datepicker-here form-control" placeholder="ex. August 03, 1998">
</div>
</div>
<div style="text-align:center">
<div>
<label>Ensure all details have been filled correctly</label>
</div>
<button class="ui green submit button">Submit Details</button>
</div>
</form>
</div>
Move your script out from inside the div with id pax, then
Clear your html of the element with id pax before appending:
//Using JQuery
$('#pax').html('');
I have a HTML form that is for payment status in my panel. In this form if i select payment status Advance Paid Then displays The another input box that i can enter for the advanced paid price. There is another input box is available that is remaining price if i entered the value of advance paid the remaining price should be display the remaining value using java script. If I choose payment status is Null then display total price in remaining price input box and if i choose Paid then display 0 in remaining price input box...all things run good ...but only one thing is not working that is if i enter the value of advance price the remaining price is not displyed. Here is my HTML Code
<div class="col-md-6">
<div class="form-group">
<label>Final Total</label>
<input type="text" value="100" name="total" id="Ftotal" class="form-control" >
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="paymentstatus">Payment Status</label>
<select class="form-control" name="paymentstatus" style="height: 40px;" onchange="yesnoCheck(this);">
<option value=""> ---Select Payment Status---</option>
<option>Advance</option>
<option>Null</option>
<option>Paid</option>
</select>
</div>
</div>
<div class="col-md-6" id="ifYes" style="display: none;">
<div class="form-group">
<label for="advancepaid">Advanced Paid</label>
<input type="text" name="advancedPiad" id="advancedPiad" onKeyUp="remaining()" class="form-control">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="remainingammount">Remaining Ammount</label>
<input type="text" name="remaining" id="remaining" class="form-control remaining" >
</div>
</div>
this is my javascript
function yesnoCheck(that) {
if (that.value == "Advance") {
document.getElementById("ifYes").style.display = "block";
} else {
document.getElementById("ifYes").style.display = "none";
}
if (that.value == "Null") {
a = Number(document.getElementById('Ftotal').value);
document.getElementById('remaining').value = a;
}
if (that.value == "Paid") {
a = 0;
document.getElementById('remaining').value = a;
}
}
function remaining()
{
a = Number(document.getElementById('Ftotal').value);
b = Number(document.getElementById('advancedPiad').value);
c = a - b;
document.getElementsByClassName("remaining").value = c;
}
Try
document.getElementsByClassName("remaining")[0].value = c;
document.getElementsByClassName gives you the array of the elements with the class name specified. In your case just set the value of first element.
Try to use js parseInt() method to convert it into integer
function remaining()
{
a=parseInt(document.getElementById('Ftotal').value);
b = parseInt(document.getElementById('advancedPiad').value);
c = a - b;
document.getElementsByClassName("remaining").value = c;
}
I am trying to debug a function call in my JSP program and really confused on the ordering of how things worked. I am using NetBeans. When I run the project in debug mode, it goes into my '$("#searchEFT").mouseup(function ()' function and trace through all of it. 'searchEFT' is a button that I am using to access my servlet. When I process the page and then click the 'searchEFT' button, it hits the function call based on getting the right alert but doesn't trace in the debug. Why is it doing that? Is the first call of the function on load setting up the check when the user does the mouseclick?
This function is outside of the '$(document).ready(function ()' at the top and the function call is after the button declaration in the JSP.
EDIT: here is the JSP code:
<head>
<script>
$(document).ready(function ()
{
$(function ()
{
$("#CMDCreationDate").datepicker({
dateFormat: "yy-mm-dd"
});
});
}) ;
window.onbeforeunload = confirmExit;
function confirmExit()
{
alert("Alert-- leaving this page.");
}
function numbersonly(myfield, e, dec) {
//function to check that only numeric values are entered
var key;
var keychar;
if (window.event)
key = window.event.keyCode;
else if (e)
key = e.which;
else
return true;
keychar = String.fromCharCode(key);
// control keys
if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13) || (key == 27))
return true;
// numbers
else if ((("0123456789").indexOf(keychar) > -1))
return true;
// decimal point jump
else if (dec && (keychar == ".")) {
myfield.form.elements[dec].focus();
return false;
} else
return false;
}
</script>
</head>
<body>
<header>
<?audit suppress oracle.ide.xml.validation-error?>
<div class="floatL appTTL">SAMS - EFT Schedule Number Search/Update Screen</div>
<div id="navWrap">
<nav class="floatR">
<ul>
<li>
Home
</li>
<li>
Search
</li>
<li>
Help
</li>
<li>
Help
</li>
</ul>
</nav>
</div>
<div class="clear"></div>
</header>
<main class="mainWrapper">
<form id="formID" method="POST" action="EFTscreen?action=searchEFT" >
<div class="commandcontainer">
<div id="divBox">
<h1 class="formTTL">Please Enter Schedule Number/Contract Year or either Schedule
Status/Creation Date value</h1>
<label class="labelTTL">Schedule Number</label>
<label class="labelTTL3">Contract Year</label>
<label class="labelTTL3">Status</label>
<label class="labelTTL">Creation Date</label>
<br/>
<input id="CMDScheduleNumber" name="CMDScheduleNumber" type="number" class="textsmall" maxlength="5"
value="${ScheduleNum}" onKeyPress="return numbersonly(this, event)"/>
<input id="CMDContractYear" name="CMDContractYear" type="number" class="textsmall" maxlength="4"
value="${ContractYear}" onKeyPress="return numbersonly(this, event)"/>
<select size="1" id="CMDSchedStatus" name="CMDSchedStatus" class="combosmall">
<c:forEach items="${statusList}" var="current">
<option value="${current}"
<c:if test="${current == Status}"> selected="selected"</c:if>
>${current}</option>
</c:forEach>
</select>
<input id="CMDCreationDate" name="CMDCreationDate" type="text" class="textsmall"
value="${CreationDate}" maxlength="10"/>
<br/>
<button id="searchEFT" class="btn smBtn">Search</button>
</div>
<div id="divButton">
<button id="searchMEFTS" type="submit" formaction="EFTscreen?action=searchMEFTS&screen=mainEFT"
class="btn midBtn">Update Schedule Status</button>
<button id="clearMenu" type="submit" formaction="EFTscreen?action=clearMenu"
class="btn midBtn Space">Return to Menu</button>
</div>
<div id="clear"></div>
</div>
<article class="divBoxdet">
<fmt:formatNumber var="trdettotal" value="${detResults.getTOTAL_AMOUNT()}" pattern="$##,###,##0.00"/>
<label class="labelTTLdet floatL">
Schedule Number
<input id="txtScheduleNumber" type="number" class="textdet"
value="${detResults.getSCHEDULE_NUMBER()}" readonly/>
</label>
<label class="labelTTLdet floatL">
Contract Year
<input id="txtContractYear" type="number" class="textdet"
value="${detResults.getEFT_CONTRACT_YEAR()}" readonly/>
</label>
<label class="labelTTLdet floatL">
Date Created
<input id="txtCreationDate" type="text" class="textdet"
value="${detResults.getCREATION_DATE()}" readonly/>
</label>
<div class="clear"></div>
<br/>
<br/>
<label class="labelTTLdet floatL">
Num of Records
<input id="txtNumRecords" type="number" class="textdet"
value="${detResults.getNUM_OF_PAY_RECORDS()}" readonly/>
</label>
<label class="labelTTLdet floatL">
Status
<br/>
<input id="txtStatus" type="text" class="textdet"
value="${detResults.getSTATUS()}" maxlength="2"/>
</label>
<label class="labelTTLdet floatL">
Status Date
<input id="txtStatusDate" type="text" class="textdet"
value="${detResults.getSTATUS_DATE()}" maxlength="10"/>
</label>
<div class="clear"></div>
<br/>
<br/>
<label class="labelTTLdet floatL">
Schedule Total
<input id="txtScheduleTotal"
type="text" class="textdet" value="${trdettotal}" readonly/>
</label>
<label class="labelTTLdet floatL">
Schedule Post Date
<input id="txtPostDate" type="text" class="textdet"
value="${detResults.getSCHEDULE_POST_DATE()}" maxlength="10"/>
</label>
<label class="labelTTLdet floatL">
Reel Number
<input id="txtReelNumber" type="text" class="textdet"
value="${detResults.getREEL_NUMBER()}" maxlength="8"/>
</label>
<div class="clear"></div>
<br/>
<br/>
<button id="pullMEFTD"
class="btn largeBtn Space floatL">Update Schedule Payment Status</button>
<script>
$("#searchEFT").mouseup(function ()
{
var Cmd_Sched_Number = $('#CMDScheduleNumber').val();
var schedLen = Cmd_Sched_Number.length;
//var Cmd_Contract_Year = document.getElementById("CMDContractYear").value;
var Cmd_Contract_Year = $('#CMDContractYear').val();
var yearLen = Cmd_Contract_Year.length;
//var Cmd_Status = document.getElementById("CMDSchedStatus").value;
var Cmd_Status = $('#CMDSchedStatus').val();
var statStr = Cmd_Status.replace(/\s/g, "");
var statLen = statStr.length;
//var Cmd_Creation_Date = document.getElementById("CMDCreationDate").value;
var Cmd_Creation_Date = $('#CMDCreationDate').val();
var createLen = Cmd_Creation_Date.length;
if ((schedLen > 0 && yearLen === 0) || (schedLen === 0 && yearLen > 0))
{
alert("Schedule Number and EFT Contract Year must be both populated");
}
;
if ((statLen === 0) && (createLen === 0) && (schedLen === 0) && (yearLen === 0))
{
var r = confirm("Are you sure you want to pull all EFT schedule numbers?");
if (r === false)
{
alert("Please enter information in any of the command line fields");
return false;
}
else
{
$('#formID').submit();
}
} ;
});
$("#pullMEFTS").mouseup(function ()
{
var Det_Sched_Number = $('#txtScheduleNumber').val();
var detschedLen = Det_Sched_Number.length;
//var Cmd_Contract_Year = document.getElementById("CMDContractYear").value;
var Det_Contract_Year = $('#txtContractYear').val();
var detyearLen = Det.length;
var Det_Status = $('#txtStatus').val();
if (detschedLen > 0)
{
alert("Schedule Number not found. Please investigate");
}
;
if ( holdStatus.matches("RP") ||
holdStatus.matches("VP") ||
holdStatus.matches("CP") )
{
alert("User can only update schedule number in NP status");
}
});
</script>
</article>
</form>
</main>
</body>
Thanks
The line:
$("#searchEFT").mouseup(function ()
is the function call that sets the mouseup handler; it is not the mouseup handler itself.
If you want to break inside the mouseup handler then you need to set a breakpoint somewhere inside the handler function itself, e.g.,
// First executable line of the mouseup handler
var Cmd_Sched_Number = $('#CMDScheduleNumber').val();
Unrelated, but I would break up the handler function into much smaller pieces, roughly:
function getFormData() {
return {
number: $('#CMDScheduleNumber').val().trim(),
year: $('#CMDContractYear').val().trim(),
status: $('#CMDSchedStatus').val().replace(/\s/g, '').trim(),
date: $('#CMDCreationDate').val().trim()
};
}
function invalidNumberAndYear(formData) {
return ((formData.number !== '') && (formData.year === '')) ||
((formData.year !== '') && (formData.number === ''));
}
function isPullAll(formData) {
return formData.number === '' &&
formData.year === '' &&
formData.status === '' &&
formData.date === '';
}
function searchEftMouseup(e) {
e.preventDefault();
var formData = getFormData();
if (invalidNumberAndYear(formData)) {
alert('Schedule Number and EFT Contract Year must be both populated');
return;
}
if (isPullAll(formData)) {
if (confirm('Are you sure you want to pull all EFT schedule numbers?')) {
$('#formID').submit();
} else {
alert('Please enter information in any of the command line fields');
}
}
}
$('#searchEFT').on('mouseup', searchEftMouseup);
This allows small stuff to be thought about easily, and begins to reveal your validation needs, and suggests a shape for your remaining code.
(Most of which, btw, was not relevant to the question–it's good to post only the minimum amount necessary to help people understand the issue :)
I need to do a Javascript verification of the fields. I need to know how to make for each span of every label how to make it display the write message.
At the moment the html code is:
<form method="post" id="contactForm" onclick="return main();">
<fieldset>
<div class="subscribe">
<label for="firstName">First name:</label>
<input type="text" name="firstName" id="firstName"/>
<span id="fnameMessage" class="infomessage">
Your first name should contain at least 2 alpha characters.
</span>
</div>
<div class="subscribe">
<label for="lastName">Last name:</label>
<input type="text" name="lastName" id="lastName"/>
<span id="lnameMessage" class="infomessage">
Your last name should contain at least 2 alpha characters.
</span>
</div>
<div class="subscribe">
<label for="title">Title:</label>
<select name="title" id="title">
<option value="1"> Mr. </option>
<option value="2"> Ms. </option>
<option value="3"> Mrs. </option>
<option value="4"> Miss. </option>
<option value="5"> Master. </option>
</select>
</div>
<div class="subscribe">
<label for="hNumber">Health Authority Number:</label>
<input type="text" name="number" id="hNumber"/>
<span id="hanMessage" class="infomessage">
Your ZHA number should be in the form of 6 digit integer prefixed wit the letters ZHA.
</span>
</div>
<div class="subscribe">
<label for="email">Email address: </label>
<input type="email" name="email" id="email"/>
<span id="emailMessage" class="infomessage">
Your email address should be as example: example#difexample.com.
</span>
</div>
<div class="subscribe">
<label for="phoneNumber">Telephone number:</label>
<input type="text" name="phoneNumber" id="phoneNumber"/>
<span id="phoneMessage" class="infomessage">
Your phone number should contain 11 numeric characters.
</span>
</div>
<div class="button">
<input id="btn1" type="submit" value="Submit" />
</div>
</fieldsed>
</form>
The javascript code that I've done it's:
function main() {
document.getElementById("contactForm").onsubmit = validateAll,
document.getElementById("firstName").onblur = validateName,
document.getElementById("lastName").onblur = validateName,
document.getElementById("phoneNumber").onblur = validatePhone;
}
function validateName() {
var test1 = fieldEmpty(this);
var test2 = fieldLength(this,2,50);
var test3 = fieldCharacters(this, "A");
var result = test1&&test2&&test3;
return result;
}
function validatePhone() {
var test1 = fieldEmpty(this);
var test2 = fieldLength(this,11,11);
var test3 = fieldCharacters(this,"N");
var result = test1&&test2&&test3;
return result;
}
function fieldEmpty(id) {
var valid = true;
if (id.value == "") {
valid = false;
alert("Field Empty");
}
return valid;
}
function fieldLength(id,min,max) {
var valid = true;
var lng = id.value.length;
if (lng < min || lng > max) {
valid = false;
alert("Field Length");
}
return valid;
}
function fieldCharacters(id,character) {
var letters = /[a-zA-Z]/;
var numbers = /[0-9]/;
var patternTest;
var valid = true;
if(character == "N") {
patternTest = numbers;
}
else if(character == "A") {
patternTest = letters;
}
valid = patternTest.test(id.value);
if (!valid) {
alert("Pattern Fail");
}
return valid;
}
function validateField() {
var noErrors = true;
// var input = document.getElementById(this);
if(this.value.length<2) {
noErrors = false;
alert("You need to input more than 1 character in " + this.id);
}
if(noErrors==false) {
var temp = document.getElementById(this.id + "firstnamemessage");
temp.className = "infomessage";
}
}
function validateAll() {
return false;
}
window.onload = main();