jS code is not working, not showing total - javascript

I am trying to calculate three values using JS, but the total is not being calculated. it gets values from the form elements and then function calculateTotal() is called onchange. But the total is not being displayed.
*I am new on stackoverflow, please be kind!
I was trying to use method Post on the form, removed it.
Also removed any styling.
function getpkgPriceA() {
//Get a reference to the form id="Mangoform"
var theForm = document.forms["Mangoform"];
//Get a reference to the select id="qtyA"
var QuantityA = theForm.elements["qtyA"];
if (QuantityA == null || QuantityA === false) {
var totalpkgPriceA = 0;
return totalpkgPriceA;
} else {
var totalpkgPriceA = 5.99 * QuantityA.value;
return totalpkgPriceA;
}
}
function getpkgPriceB() {
//Get a reference to the form id="Mangoform"
var theForm = document.forms["Mangoform"];
//Get a reference to the select id="qtyB"
var QuantityB = theForm.elements["qtyB"];
if (QuantityB == null || QuantityB === false) {
var totalpkgPriceB = 0;
return totalpkgPriceB;
} else {
var totalpkgPriceB = 12.99 * QuantityB.value;
return totalpkgPriceB;
}
}
function getpkgPriceC() {
//Get a reference to the form id="Mangoform"
var theForm = document.forms["Mangoform"];
//Get a reference to the select id="qtyC"
var QuantityC = theForm.elements["qtyC"];
if (QuantityC == null || QuantityC === false) {
var totalpkgPriceC = 0;
return totapkgPriceC;
} else {
var totalpkgPriceC = 17.99 * QuantityC.value;
return totalpkgPriceC;
}
}
function calculateTotal() {
var TotalpkgPrice = getpkgPriceA() + getpkgPriceB() + getpkgPriceC() + 2;
//display the result
var divobj = document.getElementById('totalprice');
divobj.style.display = 'block';
divobj.innerHTML = "Your Total: £"
TotalpkgPrice.toFixed(2);
}
function hideTotal() {
var divobj = document.getElementById('totalprice');
divobj.style.display = 'none';
}
<form action="#" id="Mangoform">
<div>
<div>
<div>
<span>Small: 1.3kg</span>
<input type="number" id="qtyA" name="qtyA" placeholder="Quantity" onchange="calculateTotal()" min="1" max="100">
</div>
</br>
<div>
<span>Large: 3.3kg</span>
<input type="number" id="qtyB" name="qtyB" placeholder="Quantity" onchange="calculateTotal()" min="1" max="100">
</div>
</br>
<div>
<span>Small: 5.0kg</span>
<input type="number" id="qtyC" name="qtyC" placeholder="Quantity" onchange="calculateTotal()" min="1" max="100">
</div>
</div>
</div>
<span id="totalprice" name='totalprice'>Your Total:</span>
<div>
<input name="submit" type="submit" value="submit" onclick="calculateTotal()">
</div>
</form>
if value in qtyA=1, qtyB=1 and qtyC=1 and adding 2 then total should be displayed
as 38.97
(5.99*1)+(12.99*1)+(17.99*1)+2=38.97
if qtyA=2, qtyB=2 and qtyC=3 adding 2
(5.99*2)+(12.99*2)+(17.99*3)+2=93.93
Please point out the mistake. Thanks.

There is one extra closing curly bracket in getpkgPriceA function. You just need to remove it and also you need to add + sign while adding strings:
"Your Total: £" + TotalpkgPrice.toFixed(2);
Try this:
function getpkgPriceA(){
//Get a reference to the form id="Mangoform"
var theForm = document.forms["Mangoform"];
//Get a reference to the select id="qtyA"
var QuantityA=theForm.elements["qtyA"];
if(QuantityA==null || QuantityA===false){
var totalpkgPriceA = 0;
return totalpkgPriceA;
}
var totalpkgPriceA = 5.99 * QuantityA.value;
return totalpkgPriceA;
}
function getpkgPriceB(){
//Get a reference to the form id="Mangoform"
var theForm = document.forms["Mangoform"];
//Get a reference to the select id="qtyB"
var QuantityB=theForm.elements["qtyB"];
if(QuantityB==null || QuantityB===false){
var totalpkgPriceB = 0;
return totalpkgPriceB;
}
else{
var totalpkgPriceB = 12.99 * QuantityB.value;
return totalpkgPriceB;
}
}
function getpkgPriceC(){
//Get a reference to the form id="Mangoform"
var theForm = document.forms["Mangoform"];
//Get a reference to the select id="qtyC"
var QuantityC=theForm.elements["qtyC"];
if(QuantityC==null || QuantityC===false){
var totalpkgPriceC = 0;
return totapkgPriceC;
}
else{
var totalpkgPriceC = 17.99 * QuantityC.value;
return totalpkgPriceC;
}
}
function calculateTotal(){
var TotalpkgPrice = getpkgPriceA() + getpkgPriceB() + getpkgPriceC() +2;
//display the result
var divobj = document.getElementById('totalprice');
divobj.style.display='block';
divobj.innerHTML = "Your Total: £" + TotalpkgPrice.toFixed(2) ;
}
function hideTotal(){
var divobj = document.getElementById('totalprice');
divobj.style.display='none';
}
<form action="#" id="Mangoform">
<div >
<div>
<div>
<span>
Small: 1.3kg
</span>
<input type="number" id="qtyA" name="qtyA" placeholder="Quantity" onchange="calculateTotal()" min="1" max="100" >
</div>
</br>
<div>
<span>
Large: 3.3kg
</span>
<input type="number" id="qtyB" name="qtyB" placeholder="Quantity" onchange="calculateTotal()" min="1" max="100" >
</div>
</br>
<div>
<span>
Small: 5.0kg
</span>
<input type="number" id="qtyC" name="qtyC" placeholder="Quantity" onchange="calculateTotal()" min="1" max="100" >
</div>
</div>
</div>
<span id="totalprice" name='totalprice'>
Your Total:
</span>
<div>
<input name="submit" type="submit" value="submit" onclick="calculateTotal()" >
</div>
</form>

function getpkgPriceA() {
//Get a reference to the form id="Mangoform"
var theForm = document.forms["Mangoform"];
//Get a reference to the select id="qtyA"
var QuantityA = theForm.elements["qtyA"];
if (QuantityA == null || QuantityA === false) {
var totalpkgPriceA = 0;
return totalpkgPriceA;
} else {
var totalpkgPriceA = 5.99 * QuantityA.value;
return totalpkgPriceA;
}
}
function getpkgPriceB() {
//Get a reference to the form id="Mangoform"
var theForm = document.forms["Mangoform"];
//Get a reference to the select id="qtyB"
var QuantityB = theForm.elements["qtyB"];
if (QuantityB == null || QuantityB === false) {
var totalpkgPriceB = 0;
return totalpkgPriceB;
} else {
var totalpkgPriceB = 12.99 * QuantityB.value;
return totalpkgPriceB;
}
}
function getpkgPriceC() {
//Get a reference to the form id="Mangoform"
var theForm = document.forms["Mangoform"];
//Get a reference to the select id="qtyC"
var QuantityC = theForm.elements["qtyC"];
if (QuantityC == null || QuantityC === false) {
var totalpkgPriceC = 0;
return totapkgPriceC;
} else {
var totalpkgPriceC = 17.99 * QuantityC.value;
return totalpkgPriceC;
}
}
function calculateTotal() {
var TotalpkgPrice = getpkgPriceA() + getpkgPriceB() + getpkgPriceC() + 2;
var divobj = document.getElementById('totalprice');
divobj.style.display = 'block';
divobj.innerHTML = "Your Total: £" + TotalpkgPrice.toFixed(2);
}
function hideTotal() {
var divobj = document.getElementById('totalprice');
divobj.style.display = 'none';
}
<form id="Mangoform">
<div>
<div>
<div>
<span>
Small: 1.3kg
</span>
<input type="number" id="qtyA" name="qtyA" placeholder="Quantity" onchange="calculateTotal();" min="1" max="100">
</div>
</br>
<div>
<span>
Large: 3.3kg
</span>
<input type="number" id="qtyB" name="qtyB" placeholder="Quantity" onchange="calculateTotal();" min="1" max="100">
</div>
</br>
<div>
<span>
Small: 5.0kg
</span>
<input type="number" id="qtyC" name="qtyC" placeholder="Quantity" onchange="calculateTotal();" min="1" max="100">
</div>
</div>
</div>
<span id="totalprice" name='totalprice'>
Your Total:
</span>
<div>
<input name="submit" type="button" value="submit" onclick="calculateTotal();">
</div>
</form>
</body>
</html>
As it was pointed out previously with #Saurabh code. The other reason might be the missing + sign in divobj.innerHTML = "Your Total: £" TotalpkgPrice.toFixed(2) ; where it has to be corrected to divobj.innerHTML = "Your Total: £" + TotalpkgPrice.toFixed(2) ;

Related

How to create a link from button values for woocommerce order

I have to generate a add to cart link for a page from value inputed by our customer. For example, the customer wants to order 3 products from our site www.example.com, so the code generates a link to add these 3 product to cart on page www.example2.com/?add-to-cart=25&quantity=3″.
Any ideas? I would be very grateful.
Here is the qet quantity code which works like a charm.
<button class="plus" onclick="buttonClickUP();">+</button>
<input type="text" id="gumb2" value="1"></input>
<button class="plus" onclick="buttonClickDOWN();">-</button>
<input type="text" id="order" value="ORDER NOW"></input>
<script>
function spremembax() {
document.getElementById("gumb2").value = "2";
}
function spremembay() {
document.getElementById("gumb2").value = "3";
}
var i = 0;
function buttonClickUP() {
var el = document.getElementById('gumb2');
el.value = Number(el.value) + 1;
}
var i = 0;
function buttonClickDOWN() {
var el = document.getElementById('gumb2');
if(el.value == 1) return false;
el.value = Number(el.value) - 1;
}
</script>
Here is a code sample which I wrote for you which does the job:
JSBIN Snippet Link: https://jsbin.com/guborazuqu
function spremembax() {
document.getElementById("gumb2").value = "2";
}
function spremembay() {
document.getElementById("gumb2").value = "3";
}
var i = 0;
function buttonClickUP() {
var el = document.getElementById('gumb2');
el.value = Number(el.value) + 1;
}
var i = 0;
function buttonClickDOWN() {
var el = document.getElementById('gumb2');
if (el.value == 1) return false;
el.value = Number(el.value) - 1;
}
function generateAddToCartLink() {
var productID = document.getElementById('productID').value;
var quantity = document.getElementById('gumb2').value;
var generatedLink = `${location.protocol}//${location.hostname}/?add-to-cart=${productID}&quantity=${quantity}`;
window.location.href = generatedLink;
}
<button class="plus" onclick="buttonClickUP();">+</button>
<input id="productID" type="text" value="25">
<input id="gumb2" type="text" value="1">
<button class="plus" onclick="buttonClickDOWN();">-</button>
<button id="order" onclick="generateAddToCartLink()">ORDER NOW</button>

Uncaught TypeError: Cannot read property 'checked' of undefined, Checkboxes

I want to validate my checkboxes to make sure that the user checked at least one, however I keep getting this error:
Uncaught TypeError: Cannot read property 'checked' of undefined.
Here is part of the HTML:
<form name="userSurvey" onsubmit="return validAll()" action="mailto:suvery#worldbook.com" method="post">
Name (Required): <input type="text" name="userName" id="userName" required=""><br> E-Mail (Required): <input type="text" name="mail" id="mail" required=""><br> Phone (Required): <input type="text" name="phone" id="phone" required="" onchange="validNumber()"><br>
<br>
<p>Please choose your favourite types of books.(check all that apply)</p>
<input type="checkbox" name="books" value="Science Fiction">Science Fiction
<input type="checkbox" name="books" value="Travel Guide">Travel Guide
<input type="checkbox" name="books" value="Short Story Collection">Short Story Collection
<input type="checkbox" name="books" value="Other">Other <br>
<textarea></textarea><br>
<input type="submit" name="submit">
<input type="reset" name="reset">
</form>
and part of the JavaScript for the checkboxes:
function validChoice()
{
var bookChoice = document.userSurvey.books.value;
var x= "";
for (i=0;i< 4;i++)
{
if (document.userSurvey['bookChoice'+i].checked)
{
bookChoice = document.userSurvey['bookChoice'+i].value;
x = x +"\n"+ bookChoice;
}
}
if (bookChoice == "")
{
window.alert("You must select at least one book category.");
return false;
}
else
{
var userName = document.userSurvey.userName.value;
var eMail = document.userSurvey.email.value;
var phoneNo = document.userSurvey.phone.value;
return true;
}
}
I am currently learning in JavaScript therefore I would prefer help in JavaScript only.
Full Code on JSFiddle:
https://jsfiddle.net/7qh5segc/
You missed some tag names and missspell them in js function:
<h1>User Survey</h1>
<h2><strong>User Information</strong></h2>
<p>Please enter your details below</p>
<br>
<form name="userSurvey" onsubmit="return validAll()" action="mailto:suvery#worldbook.com" method="post">
Name (Required):
<input type="text" name="userName" id="userName" required="">
<br> E-Mail (Required):
<input type="text" name="email" id="email" required="">
<br> Phone (Required):
<input type="text" name="phone" id="phone" required="" onchange="validNumber()">
<br>
<br>
<p>Please choose your favourite types of books.(check all that apply)</p>
<input type="checkbox" name="books" value="Science Fiction">Science Fiction
<input type="checkbox" name="books" value="Travel Guide">Travel Guide
<input type="checkbox" name="books" value="Short Story Collection">Short Story Collection
<input type="checkbox" name="books" value="Other">Other
<br>
<textarea></textarea>
<br>
<input type="submit" name="submit">
<input type="reset" name="reset">
</form>
and js code goes like this:
function validName() {
var name = document.userSurvey.userName.value;
if (!/^[a-zA-Z]*$/g.test(name)) {
alert("Please enter letters a - z only");
document.userSurvey.userName.focus();
return false;
} else {
return true;
}
}
function validNumber() {
var theNumbersOnly = "";
var theChar = "";
var theInput = document.userSurvey.phone.value;
for (i = 0; i < theInput.length; i++) {
theChar = theInput.substring(i, i + 1);
if (theChar >= "0" && theChar <= "9") {
theNumbersOnly = "" + theNumbersOnly + theChar;
}
}
if (theNumbersOnly.length < 10) {
alert("You must enter 10 numbers.");
document.userSurvey.phone.focus();
} else {
var areacode = theNumbersOnly.substring(0, 3);
var exchange = theNumbersOnly.substring(3, 6);
var extension = theNumbersOnly.substring(6, 10);
var newNumber = "(" + areacode + ") ";
newNumber += exchange + "-" + extension;
document.userSurvey.phone.value = newNumber;
return true;
}
}
function validEmail() {
var email = document.userSurvey.email.value;
var atLoc = email.indexOf("#", 1);
var dotLoc = email.indexOf(".", atLoc + 2);
var len = email.length;
if (atLoc > 0 && dotLoc > 0 && len > dotLoc + 2) {
return true;
} else {
alert("Please enter your e-mail address properly.");
return false;
}
}
function validChoice() {
//var bookChoice = document.userSurvey.books.value;
var bookChoice;
var x = "";
for (var i = 0; i < 4; i++) {
if (document.userSurvey.books[i].checked) {
console.log(document.userSurvey);
bookChoice = document.userSurvey.books[i].value;
x = x + "\n" + bookChoice;
}
}
if (bookChoice == "") {
window.alert("You must select at least one book category.");
return false;
} else {
var userName = document.userSurvey.userName.value;
var eMail = document.userSurvey.email.value;
var phoneNo = document.userSurvey.phone.value;
console.log(userName);
console.log(eMail);
console.log(phoneNo);
return true;
}
}
function validAll() {
if ((validName() == true) && (validEmail() == true) && (validNumber() == true) && (validChoice() == true)) {
return true;
} else {
return false;
}
}
You missed email tag name too. regards
You can fix the checkbox issue using the following code. A sensible way to get all the checkboxes in this case is using their shared "name" attribute. There are other ways if your structure was different - e.g. using a CSS class, or adding some other custom attribute to the elements.
function validChoice() {
var bookChoices = "";
var checkboxes = document.getElementsByName("books"); //get all elements named "books" into an array
for (i = 0; i < checkboxes.length; i++) { //loop the array
if (checkboxes[i].checked) { //if the array item at this index is checked, then add it to the list
bookChoices += "\n" + checkboxes[i].value;
}
}
if (bookChoices == "") {
window.alert("You must select at least one book category.");
return false;
} else {
alert(bookChoices); //just for testing
return true;
}
}
See https://jsfiddle.net/7qh5segc/3/ for a demo using the changed validChoice() function.

trying to do calculation of 2 input fields update in real-time

I am trying to calculate 2 input fields and display the result in real-time in div totalPrice
no matter what I've tried can't get it to work
thx
<script src="jquery-1.11.1.min.js">
jQuery('#field2').on('input propertychange paste', function() {
var op1 = document.getElementById('field1');
var op2 = document.getElementById('field2');
var result = document.getElementById('totalPrice');
if (op1.value == "" || op1.value != parseFloat(op1.value)) op1.value = 0;
if (op2.value == "" || op2.value != parseFloat(op2.value)) op2.value = 0;
result.value = 0;
result.value = parseInt(result.value);
result.value = parseInt(result.value) + parseInt(op1.value) + parseInt(op2.value);
}
var divobj = document.getElementById('totalPrice'); divobj.style.display = 'block'; divobj.innerHTML = "Total $" + result.value;
});
</script>
<form action="" id="cakeform" onsubmit="return false;">
<input type="text" value="" size="20" name="field1" id="field1" class="rsform-input-box">
<input type="text" value="" size="20" name="field2" id="field2" class="rsform-input-box">
<div id="totalPrice"></div>
</form>
What about this http://jsfiddle.net/20Lgz8ey/2/
$('#field1,#field2').on('input propertychange paste', function() {
$('#totalPrice').html(parseFloat($("#field1").val()!=''?$("#field1").val():0)+parseFloat($("#field2").val()!=''?$("#field2").val():0));
});
also
<script src="jquery-1.11.1.min.js"></script>
<script>
code ....
</script>
$(document).ready(function () {
jQuery('#field2, #field1').on('input propertychange paste', function () {
var op1 = document.getElementById('field1');
var op2 = document.getElementById('field2');
var result = document.getElementById('totalPrice');
if (op1.value == "" || op1.value != parseFloat(op1.value)) op1.value = 0;
if (op2.value == "" || op2.value != parseFloat(op2.value)) op2.value = 0;
result.value = 0;
result.value = parseInt(result.value);
result.value = parseInt(result.value) + parseInt(op1.value) + parseInt(op2.value);
var divobj = document.getElementById('totalPrice'); divobj.style.display = 'block'; divobj.innerHTML = "Total $" + result.value;
})
});
try this if it helps you.

How to get an input value dynamically and perform arithmetic operations using javascript

I have created two input text fields by which the user have to give two values. Using javascript, I need to get those values perform addition, subtraction, multiplication and division based on the checkbox checked. How to do that?
Here is my code..
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JS Assignment</title>
<script>
function changeCheckBox() {
try {
var max = document.myform.check.length;
var count = 0;
for (var i = 0; i < max; i++) {
if (document.myform.check[i].checked == true) {
count++;
serNoChecked = i;
}
}
if (count == 1) {
for (var i = 0; i < max; i++) {
if (document.myform.check[i].checked == false) {
document.myform.check[i].disabled = true;
}
}
} else if (count == 0) {
for (var i = 0; i < max; i++) {
document.myform.check[i].disabled = false;
}
}
if (null == max) return false;
if (count == 0) {
return true;
} else if (count > 0) {
return false;
}
} catch (e) {
alert(e.message);
}
}
</script>
<script type="text/javascript">
function arith()
{
var number1 = document.getElementById('num1').value;
var number2 = document.getElementById('num2').value;
x=num1 + num2;
var demoP=document.getElementById("demo")
demoP.innerHTML="x=" + x;
}
</script>
</head>
<body background="photo.jpg" onload="arith()">
<h3>Simple JavaScript Arithmetic Operations</h3>
<form name="myform" method="get">
Value 1 <input type ="text" id="num1"> <br><br>
Value 2 <input type="text" id="num2"> <br><br>
<input type="checkbox" name="check" value="check1" id="check1" onclick="changeCheckBox()">Addition<br>
<input type="checkbox" name="check" value="check2" id="check2" onclick="changeCheckBox()">Subtraction<br>
<input type="checkbox" name="check" value="check3" id="check3" onclick="changeCheckBox()">Multiplication<br>
<input type="checkbox" name="check" value="check4" id="check4" onclick="changeCheckBox()">Division<br><br>
<input type="submit" value="Submit">
</form>
<p id="demo"></p>
</body>
</html>
Try sending the value of the HTML into the function, and then use those as an if statement check (or switch statement).
<form name="myform" method="get">
Value 1 <input type ="text" id="num1"> <br><br>
Value 2 <input type="text" id="num2"> <br><br>
<input type="checkbox" name="check" id="check1">Addition<br>
<input type="checkbox" name="check" id="check2">Subtraction<br>
<input type="checkbox" name="check" id="check3">Multiplication <br>
<input type="checkbox" name="check" id="check4">Division<br><br>
<input type="submit" value="Submit">
<p id="demo"></p>
Notice the value attributes now have unique value. And you're sending that into the function as a parameter.
Now just have a function that returns what you want
var newVal = "Unset";
var plus = document.getElementById("check1");
var minus = document.getElementById("check2");
var times = document.getElementById("check3");
var divide = document.getElementById("check4");
var demoP=document.getElementById("demo");
plus.onclick = function() {
var n1 = parseFloat(document.getElementById('num1').value);
var n2 = parseFloat(document.getElementById('num2').value);
newVal = n1+n2;
demoP.innerHTML="x=" + newVal;
}
minus.onclick = function() {
var n1 = parseFloat(document.getElementById('num1').value);
var n2 = parseFloat(document.getElementById('num2').value);
newVal = n1-n2;
demoP.innerHTML="x=" + newVal;
}
times.onclick = function() {
var n1 = parseFloat(document.getElementById('num1').value);
var n2 = parseFloat(document.getElementById('num2').value);
newVal = n1*n2;
demoP.innerHTML="x=" + newVal;
}
divide.onclick = function() {
var n1 = parseFloat(document.getElementById('num1').value);
var n2 = parseFloat(document.getElementById('num2').value);
newVal = n1/n2;
demoP.innerHTML="x=" + newVal;
}

Jquery filtering through a multiple range of numbers

Think I'm getting stuck... I'm attempting to take a list of items and create filters based on attributes to the object. I stripped it down into an easier example of books with a cost and year. I currently have a list of books on the page and filters (checkboxes) that can be selected to only show books within a range of cost and/or year. Here is the code I have so far:
<div id="filters">
<h1>FILTERS</h1>
<div class="filter filter_cost">
<input class="target" type="checkbox" min="0" max="9" />Under $10.00<br/>
<input class="target" type="checkbox" min="10" max="19" />$10-$19<br/>
<input class="target" type="checkbox" min="20" max="29" />$20-$29<br/>
<input class="target" type="checkbox" min="30" max="39" />$30-$39<br/>
<input class="target" type="checkbox" min="40" max="1000" />$40 and Over<br/>
</div>
<div class="filter filter_year">
<input class="target" type="checkbox" min="1700" max="1799" />18th Century<br/>
<input class="target" type="checkbox" min="1800" max="1899" />19th Century<br/>
<input class="target" type="checkbox" min="1900" max="1999" />20th Century<br/>
<input class="target" type="checkbox" min="2000" max="2999" />21st Centruy<br/>
</div>
</div>
<div id="books">
<h1>BOOKS</h1>
<div class="book">
<h1>Book 1</h1>
<input type="hidden" name="cost" value="13" />
<input type="hidden" name="year" value="1997" />
</div>
<div class="book">
<h1>Book 2</h1>
<input type="hidden" name="cost" value="22" />
<input type="hidden" name="year" value="1872" />
</div>
</div>
And my jQuery (using 1.6.2):
$(document).ready(function () {
$("input.target").change(function () {
filterResults();
});
});
function filterResults(){
$(".book").each(function () {
var cost = $(this).find("input[name='cost']").val();
var year = $(this).find("input[name='year']").val();
var cover = $(this).find("input[name='cover']").val();
var isHidden = false;
//console.log("Cost in Range: "+filterRange(cost, ".filter_cost"));
//console.log("Year in Range: "+filterRange(year, ".filter_year"));
var filterCost = filterRange(cost, ".filter_cost")?showBook($(this)):hideBook($(this));
var filterYear = filterRange(year, ".filter_year")?showBook($(this)):hideBook($(this));
isHidden?"":filterCost;
isHidden?"":filterYear;
function showBook(obj) {
obj.show();
}
function hideBook(obj) {
isHidden = true;
obj.hide();
}
})
}
function filterRange(amount, elem) {
var checkedInputs = $(elem).find("input:checked").length;
var totalInputs = $(elem).find("input").length;
var inRange = function(){
$(elem).find("input:checked").each(function () {
var min = $(this).attr('min');
var max = $(this).attr('max');
if(amount >= min && amount <= max){
return true;
} else {
return false;
}
});
};
if(checkedInputs == 0 || totalInputs == checkedInputs ){
return true;
}
if(inRange()){
return true;
} else {
return false;
}
}
My issue is that in the filterRange function I'm not sure how to create a range of conditionals based on each input that is checked. So that a price range could be 10-19 and 30-39. My attempt (var inRange) was to go through each checked input, check if the cost was with in the range, then return true, else return false. I think I'm just fundamentally getting off track and unsure if this method would work at all. Any input would be much appreciated.
In the jquery each loop on dom element return statement breaks out of the loop. So your implemenation is wrong. Try this.
function filterRange(amount, elem) {
var checkedInputs = $(elem).find("input:checked").length;
var totalInputs = $(elem).find("input").length;
var returnValue = false;
$(elem).find("input:checked").each(function () {
var min = $(this).attr('min');
var max = $(this).attr('max');
if(amount >= min && amount <= max){
returnValue = true;
return true;
}
});
return (checkedInputs == 0 || totalInputs == checkedInputs || returnValue );
}
Try:
function filterRange(amount, elem) {
var checkedInputs = $(elem).find("input:checked").length;
var totalInputs = $(elem).find("input").length;
var inRange = false;
$(elem).find("input:checked").each(function () {
var min = $(this).attr('min');
var max = $(this).attr('max');
if (amount >= min && amount <= max) {
inRange = true;
return false;
}
});
if (checkedInputs == 0 || totalInputs == checkedInputs) {
return true;
}
if (inRange) {
return true;
} else {
return false;
}
}

Categories

Resources