So I have something like this...
I have a form where you select your gender and input your weight. each gender has different ranges of prices for example if your a male and your weight is greater than 200 your price is 20, if your a female and your weight is greater than 200 your price is 15, and if your male and your weight is less than 200 your price is 10, for the female if her weight is less than 200 her price is 7 . i have been trying to make it possible with jquery and PHP but it only seems to work with select option and won't work with input data.
this is my index.php
<div class="container">
<div class="row">
<div class="col-xs-3 col-xs-offset-2">
<h3>gender:</h3>
<!-- select gender -->
<select class="form-control" id="gender">
<option>female</option>
<option>male</option>
</select>
</div>
<div class="col-xs-3">
<h3>weight </h3>
<!-- input weight -->
<input type="" name="weight" id="weight">
</div>
</div>
<div id="ticketInfo">
<h3 id="yourTicket">No gender Selected</h3>
</div>
</div>
<script src="js/jquery-1.12.2.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/scripts.js"></script>
this is my script
function Ticket(gender, weight) {
this.gender=gender;
this.weight=weight;
}
Ticket.prototype.getPrice=function() {
var price;
if((this.gender==="male ")||(this.weight=>"200 ")){
price=20;
}
if((this.gender==="female ")||(this.weight=>"200 ")) {
price=15;
}
if((this.gender==="male ")||(this.weight=<"200 ")) {
price=10;
}
if((this.gender==="female ")||(this.weight=<"200 ")) {
price=7;
}
return price;
}
$("select").change(function() {
var genderOptions=[];
$("select option:selected").each(function() {
genderOptions.push($(this).text() + " ");
});
var newTicket = new
Ticket(genderOptions[0],genderOptions[1],genderOptions[2]);
$("#yourTicket").text(newTicket.gender + newTicket.weight + " $" +
newTicket.getPrice().toFixed(2));
});
at the end in trying to multiply the price by the weight. any help will be really appreciated, thanks in advance.
Try this with Syed's solution.
Logic should be using && operator not ||
function Ticket(gender, weight) {
this.gender=gender;
this.weight=weight;
}
Ticket.prototype.getPrice=function() {
var price;
if(this.gender==="male" && this.weight > 200){
price=20;
}
else if(this.gender==="female" && this.weight > 200) {
price=15;
}
else if(this.gender==="male" && this.weight <= 200) {
price=10;
}
else if(this.gender==="female" && this.weight <= 200) {
price=7;
}
return price;
}
$("#calculate").click(function() {
var genderOptions=[];
$("select option:selected").each(function() {
genderOptions.push($(this).text() + " ");
});
var newTicket = new
Ticket($("#gender").val(),$('#weight').val());
var multiplyVal = newTicket.weight * newTicket.getPrice();
$("#yourTicket").text("Gender: " + newTicket.gender + " Weight: " + newTicket.weight + " $" + newTicket.getPrice().toFixed(2) + " and your multiplied value is " + multiplyVal);
});
<div class="col-xs-3 col-xs-offset-2">
<h3>gender:</h3>
<!-- select gender -->
<select class="form-control" id="gender">
<option value="female" selected>female</option>
<option value="male">male</option>
</select>
</div>
<div class="col-xs-3">
<h3>weight </h3>
<!-- input weight -->
<input type="" name="weight" id="weight">
</div>
<div id="ticketInfo">
<h3 id="yourTicket">No gender Selected</h3>
</div>
<button id="calculate" >Calculate</button>
Your question is unclear.as per my understanding I provide you a solution.
You have mistakes in your if condition. for eg. you need to check as >= instead you checked as => which is wrong.
Also it should be && instead of ||
And you missed to pass the weight variable to the Ticket class.
remove quotes around 200 in your if condition
you have pushed a space in genderOptions. so I removed it.
I fixed these issues.
function Ticket(gender, weight) {
this.gender=gender;
this.weight=weight;
}
Ticket.prototype.getPrice=function() {
var price;
if(this.gender==="male" && this.weight > 200 ){
price=20;
}
else if(this.gender==="female" && this.weight > 200 ) {
price=15;
}
else if(this.gender==="male" && this.weight <= 200 ) {
price=10;
}
else if(this.gender==="female" && this.weight <= 200 ) {
price=7;
}
return price;
}
$("select").change(function() {
var genderOptions=[];
$("select option:selected").each(function() {
genderOptions.push($(this).text());
});
var newTicket = new Ticket(genderOptions[0] , $('#weight').val());
var multiplyVal = newTicket.weight * newTicket.getPrice();
$("#yourTicket").text(newTicket.gender + newTicket.weight + " $" + newTicket.getPrice().toFixed(2) + " and your multiplied value is " + multiplyVal);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="row">
<div class="col-xs-3 col-xs-offset-2">
<h3>gender:</h3>
<!-- select gender -->
<select class="form-control" id="gender">
<option value="female">female</option>
<option value="male">male</option>
</select>
</div>
<div class="col-xs-3">
<h3>weight </h3>
<!-- input weight -->
<input type="" name="weight" id="weight">
</div>
</div>
<div id="ticketInfo">
<h3 id="yourTicket">No gender Selected</h3>
</div>
</div>
Remove the empty string added in gender options.push.Afterwards ,working fine
genderOptions.push($(this).text())
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.
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 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 have this small bit of HTML and JS and I cannot for the life of me get the function to work with the button. I have tried many things and changed different styles of creating buttons and text boxes but I cannot figure out how to fix it.
Here is the Code:
<div id="orderForm">
<form name="orderingForm" action="form_action.asp">
<p>Complete this form to order Bags
<br>
<br> How many of each bag do you want (3p/ea)</p>
<p>Number of Blue bags:
<input type="text" name="blueBags" value=0>
</p>
<p>Number of Red bags:
<input type="text" name="redBags" value=0>
</p>
<p>Number of Yellow bags:
<input type="text" name="yellowBags" value=0>
</p>
<p>Number of Green bags:
<input type="text" name="greenBags" value=0>
</p>
<p>Enter Desired Text:
<input type="text" name="textBags" value="Enter Your text here">
<p>Minimum order 100 bags</p>
<input type="button" value="Click to Order" onClick="Order()">
</form>
</div>
<!--Script for the ordering system-->
<script>
<!-- extra functions to check if input is an integer -->
function isInt(n) {
return n % 1 === 0;
}
function Order() {
var amountB = document.orderingForm.blueBags.value;
var amountR = document.orderingForm.redBags.value;
var amountY = document.orderingForm.yellowBags.value;
var amountG = document.orderingForm.greenBags.value;
var text = document.orderingForm.textBags.value;
var total = amountB + amountR + amountY + amountG;
if (isInt(form1.blueBags.value) == true && isInt(form1.redBags.value) == true && isInt(form1.yellowBags.value) == true && isInt(form1.greenBags.value) == true) {
if (total > 100) {
var cost = (total * 0.03);
//if (confirm("CONFIRM ORDER: /n blue bags: " + form1.blueBags.value + "/n red bags: " + form1.redBags.value + "/n yellow bags: " + form1.yellowBags.value + "/n green bags: " + form1.greenBags.value + "/n Desired Text: " + text)) {
alert("Order Confirmed");
} else {
alert("Order Cancelled");
}
} else {
alert("Minimum order is 100 bags.");
}
} else {
alert("One or more of the forms doesn't contain a quantity for order.");
}
}
</script>
Here you miss handled with '{}' and your form name is "orderingForm" not "form1"
try this:
<html>
<body>
<div id="orderForm">
<form name="orderingForm" action="form_action.asp">
<p>Complete this form to order Bags
<br>
<br> How many of each bag do you want (3p/ea)</p>
<p>Number of Blue bags:
<input type="text" name="blueBags" value=0>
</p>
<p>Number of Red bags:
<input type="text" name="redBags" value=0>
</p>
<p>Number of Yellow bags:
<input type="text" name="yellowBags" value=0>
</p>
<p>Number of Green bags:
<input type="text" name="greenBags" value=0>
</p>
<p>Enter Desired Text:
<input type="text" name="textBags" value="Enter Your text here">
<p>Minimum order 100 bags</p>
<input type="button" value="Click to Order" onClick="Order()">
</form>
</div>
</body>
<!--Script for the ordering system-->
<script>
<!-- extra functions to check if input is an integer -->
function isInt(n) {
return n % 1 === 0;
}
function Order() {
console.log("hai")
var amountB = document.orderingForm.blueBags.value;
var amountR = document.orderingForm.redBags.value;
var amountY = document.orderingForm.yellowBags.value;
var amountG = document.orderingForm.greenBags.value;
var text = document.orderingForm.textBags.value;
var total = amountB + amountR + amountY + amountG;
if (isInt(orderingForm.blueBags.value) == true && isInt(orderingForm.redBags.value) == true && isInt(orderingForm.yellowBags.value) == true && isInt(orderingForm.greenBags.value) == true) {
if (total > 100) {
var cost = (total * 0.03);
alert("Order Confirmed");
} else {
alert("Minimum order is 100 bags.");
}
} else {
alert("One or more of the forms doesn't contain a quantity for order.");
}
}
</script>
</html>
hope it will help for you.
You used .. and missed }. Try this
<div id="orderForm">
<form name="orderingForm" action="form_action.asp">
<p>Complete this form to order Bags
<br>
<br> How many of each bag do you want (3p/ea)</p>
<p>Number of Blue bags:
<input type="text" name="blueBags" value=0>
</p>
<p>Number of Red bags:
<input type="text" name="redBags" value=0>
</p>
<p>Number of Yellow bags:
<input type="text" name="yellowBags" value=0>
</p>
<p>Number of Green bags:
<input type="text" name="greenBags" value=0>
</p>
<p>Enter Desired Text:
<input type="text" name="textBags" value="Enter Your text here">
<p>Minimum order 100 bags</p>
<input type="button" value="Click to Order" onClick="Order()">
</form>
</div>
<!--Script for the ordering system-->
<script>
<!-- extra functions to check if input is an integer -->
function isInt(n) {
return n % 1 === 0;
}
function Order() {
var amountB = document.orderingForm.blueBags.value;
var amountR = document.orderingForm.redBags.value;
var amountY = document.orderingForm.yellowBags.value;
var amountG = document.orderingForm.greenBags.value;
var text = document.orderingForm.textBags.value;
var total = amountB + amountR + amountY + amountG;
//if (isInt(form1.blueBags.value) == true && isInt(form1.redBags.value) == true && isInt(form1.yellowBags.value) == true && isInt(form1.greenBags.value) == true) {
if (total > 100) {
// var cost = (total * 0.03);
//if (confirm("CONFIRM ORDER: /n blue bags: " + form1.blueBags.value + "/n red bags: " + form1.redBags.value + "/n yellow bags: " + form1.yellowBags.value + "/n green bags: " + form1.greenBags.value + "/n Desired Text: " + text)) {
alert("Order Confirmed");
// } else {
// alert("Order Cancelled");
// }
} else {
alert("Minimum order is 100 bags.");
}
//}else {
// alert("One or more of the forms doesn't contain a quantity for order.");
// }
}
</script>
First-off, don't use HTML Comments between your <script> tags, as you have:
<!-- extra functions to check if input is an integer -->
And you have a syntax error at .. should be . "single dot", as you have:
var text = document.orderingForm..textBags.value;
This should be something like this:
var text = document.orderingForm.textBags.value;
And finally, you didn't close your Order() function ending bracket.
Checkout this fiddle: http://jsfiddle.net/c5496q92/
Updated for Understanding Comments in HTML and JavaScript:
When you wants to add some Comments in HTML, you can use:
<!-- Your Comments -->
And if you are working in .js file or between <script></script> tags you should use:
/* For multi-line comments */
// For singular line comment
You can read about this more at:
http://www.inmotionhosting.com/support/edu/website-design/website-design-basics/comment-php-javascript-html-css-code
Replace the line as follows:
var text = document.orderingForm.textBags.value;
and to add two values use parseInt(value) or parseFloat(value) as:
var r = parseInt(amountB) + parseInt(amountR);
Remove . from this line
var text = document.orderingForm..textBags.value;
write
var text = document.orderingForm.textBags.value;
and close the } end of your code