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('');
Related
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>
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.
I have 2 products and wanted to multiply with quantity and add up both price along with tax and to show the final price of both added and multiplied values I tried doing using jQuery but I am unable to multiply and add up both values can any one help me out
Here is the code for it:
$(document).ready(function(){
$('#sticker01').on('keyup', function() {
var sticker_01 = $('#sticker01').val();
var oldval = parseInt($('#order_total').text());
var total_val = (sticker_01 * 8 +1.30) + oldval;
$('#order_total').html(total_val);
});
});
$(document).ready(function(){
$('#sticker02').on('keyup', function() {
var sticker_02 = $('#sticker02').val();
var oldval = parseInt($('#order_total').text());
var total_val = (sticker_02 * 2 + 1.30) + oldval;
$('#order_total').html(total_val);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="form-group">
<label>MadEnoughToPayAttention Bumper Sticker</label>
<input type="number" name="bumper_sticker_01_qty" id="sticker01">
</div>
<div class="form-group">
<label>ChangeNotHope Bumper Sticker</label>
<input type="number" name="bumper_sticker_02_qty" id="sticker02">
</div>
<div class="order_total">
<span>Order Total : $<div id="order_total">0.00</div></span>
</div>
Here is a less verbose solution to your issue with minor changes to the HTML and a complete overhaul of the Javascript.
HTML:
I added the min attribute and set its value to 0 to prevent the input spinners from selecting negative values in both the sticker01 and sticker02 elements. I also set the order_total input to disabled as this is the calculation field which will get its value from the inline Javascript. These udpates are cosmetic and play no roll in the structural performance your app.
<div class="form-group">
<label>MadEnoughToPayAttention Bumper Sticker</label>
<input type="number" name="bumper_sticker_01_qty" min="0" id="sticker01">
</div>
<div class="form-group">
<label>ChangeNotHope Bumper Sticker</label>
<input type="number" name="bumper_sticker_02_qty" min="0" id="sticker02">
</div>
<div class="order_total">
<span>Order Total : $
<input type="text" name="bumper_sticker_total" id="order_total" disabled>
</span>
</div>
Javascript:
Here you can implement an anonymous function to handle the events .keyup() and .change() and use a delegated event on the input elements.
$('input').on('change keyup', function() {
sticker_01 = $('#sticker01').val(),
sticker_02 = $('#sticker02').val(),
total_val = $('#order_total');
if ((sticker_01) > 0 && (sticker_02) == 0) {
total_val.val(((sticker_01) * 8 + 1.30).toFixed(2));
} else if ((sticker_02) > 0 && (sticker_01) == 0) {
total_val.val(((sticker_02) * 2 + 1.30).toFixed(2));
} else if ((sticker_01) > 0 && (sticker_02) > 0) {
total_val.val(((((sticker_01) * 8 + 1.30) + ((sticker_02) * 2 + 1.30)).toFixed(2)));
} else {
total_val.val('');
};
});
That's everything you need. Here is a sample Code Snippet for your review.
$('input').on('change keyup', function() {
sticker_01 = $('#sticker01').val(),
sticker_02 = $('#sticker02').val(),
total_val = $('#order_total');
if ((sticker_01) > 0 && (sticker_02) == 0) {
total_val.val(((sticker_01) * 8 + 1.30).toFixed(2));
} else if ((sticker_02) > 0 && (sticker_01) == 0) {
total_val.val(((sticker_02) * 2 + 1.30).toFixed(2));
} else if ((sticker_01) > 0 && (sticker_02) > 0) {
total_val.val(((((sticker_01) * 8 + 1.30) + ((sticker_02) * 2 + 1.30)).toFixed(2)));
} else {
total_val.val('');
};
});
<div class="form-group">
<label>MadEnoughToPayAttention Bumper Sticker</label>
<input type="number" name="bumper_sticker_01_qty" min="0" id="sticker01">
</div>
<div class="form-group">
<label>ChangeNotHope Bumper Sticker</label>
<input type="number" name="bumper_sticker_02_qty" min="0" id="sticker02">
</div>
<div class="order_total">
<span>Order Total : $
<input type="text" name="bumper_sticker_total" id="order_total" disabled>
</span>
</div>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
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 :)
FIDDLE: http://jsfiddle.net/hReB3/6/
Javascript code:
$('#qty').keyup(function(){
if($(this).val() != '' && isNumber($(this).val()) && $(this).val() > 0)
{
var price = $('#real_price').val() * 1;
var qty = $(this).val() * 1;
var total = price * qty;
$('#price').html(total);
}
else
{
$('#price').html('500');
}
});
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
If I'm updating the price for the first field, it works fine, but for the second doesnt.
I'm new into javascript :).
JSFiddle
Using classes on your fields instead of IDs (IDs must be unique) and enclosing them within a parent DIV would allow you to use this code and gives you scope to add as many sections to your page as you need.
HTML
<div>
Price $<span class="price">500</span>
<input type="hidden" class="real_price" value="500" />
<input type="text" class="qty" value="1" />
</div>
<div>
Price $<span class="price">500</span>
<input type="hidden" class="real_price" value="500" />
<input type="text" class="qty" value="1" />
</div>
JS
$('.qty').keyup(function () {
var $me = $(this),
$parent = $me.parent('div'),
total = 500;
if (isNumber($me.val()) && $me.val() > 0)
{
var price = $parent.find('.real_price').val() * 1,
qty = $me.val() * 1;
total = price * qty;
}
$parent.find('.price').html(total);
});
You could also replace your hidden fields with data-price attributes as shown here JSFiddle
Can you try this, You can't able to use id value in more elements, instead that you can use classname etc, I have updated your fiddle code,
HTML:
Price $<span id="price_qty_1">500</span>
<input type="hidden" id="real_price_qty_1" value="500" />
<input type="text" id="qty_1" class="qty" value="1"/><br />
Price $<span id="price_qty_2">500</span>
<input type="hidden" id="real_price_qty_2" value="500" />
<input type="text" id="qty_2" class="qty" value="1"/>
Jquery:
$('.qty').keyup(function(){
if($(this).val() != '' && isNumber($(this).val()) && $(this).val() > 0)
{
var idAt = $(this).attr('id');
var price = $('#real_price_'+idAt).val() * 1;
var qty = $(this).val() * 1;
var total = price * qty;
$('#price_'+idAt).html(total);
}
else
{
$('#price_'+idAt).html('500');
}
});
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Demo : http://jsfiddle.net/hReB3/10/
Try this
<input type="text" id="qty1" value="1"/><br />
<input type="text" id="qty2" value="1"/>
$('#qty1,#qty2').keyup(function(){})
And in the price evaluation time replace this with
$('#price').html(total);
with
($(this).attr('id')=="qty1") ? $('#price1').html(total) : $('#price2').html(total);