change value upon select - javascript

what i'm aiming is to show the other div when it selects one of the two options
Full time and Part Time
and if possible compute a different value for each
When the user selects Part time
the value of PrcA will change to PrcB
this is the code i used
<!====================================================================================>
<script language="javascript">
<!--//
function dm(amount)
{
string = "" + amount;
dec = string.length - string.indexOf('.');
if (string.indexOf('.') == -1)
return string + '.00';
if (dec == 1)
return string + '00';
if (dec == 2)
return string + '0';
if (dec > 3)
return string.substring(0,string.length-dec+3);
return string;
}
function calculate()
{
QtyA = 0;
TotA = 0;
PrcA = 1280;
PrcB = 640;
if (document.form1.qtyA.value > "")
{ QtyA = document.form1.qtyA.value };
document.form1.qtyA.value = eval(QtyA);
TotA = QtyA * PrcA;
document.form1.totalA.value = dm(eval(TotA));
Totamt =
eval(TotA) ;
document.form1.GrandTotal.value = dm(eval(Totamt));
}
//-->
</script>
<!====================================================================================>
<p>
<label for="acct" style="margin-right:90px;"><strong>Account Type<strong><font color=red size=3> * </font></strong></label>
<select name="acct" style="background-color:white;" class="validate[custom[serv]] select-input" id="acct" value="">
<option value="Full Time">Full-Time</option>
<option value="Part Time">Part-Time</option>
<option selected="selected" value=""></option>
</select></p>
<!====================================================================================>
<script>
$(document).ready(function() {
$("input[name$='acct']").select(function() {
var test = $(this).val();
$("div.desc").hide();
$("#acct" + test).show();
});
});
</script>
<!====================================================================================>
<p>
<table><tr><td>
<lable style="margin-right:91px;"># of Agent(s)<font color=red size=3> * </font></lable>
</td><td>
<input style="width:25px; margin-left:5px;" type="text" class="validate[custom[agnt]] text-input" name="qtyA" id="qtyA" onchange="calculate()" />
</td><td>
<div id="acctFull Time" class="desc">
x 1280 =
</div>
<div id="acctPart Time" class="desc" style="display:none">
x 640 =
</div>
</td><td>
$<input style="width:80px; margin-left:5px;" type="text" readonly="readonly" name="totalA" id="totalA" onchange="calculate()" />
</p>
</td></tr></table>
is there any way for me to achieve this?

Check this [FIDDLE] ..
Added two classes to the div's which show the amount.. This should make like easier to access them..
$(document).ready(function() {
$("#acct").on('change', function() {
var selVal = $(this).val();
if (selVal == '1') { // Full Time
$('.parttime').hide();
$('.fulltime').show();
$('.agent').show();
$('.error').hide();
}
else if (selVal == '2') { // Part Time
$('.parttime').show();
$('.fulltime').hide();
$('.agent').show();
$('.error').hide();
}
else {
$('.parttime').hide();
$('.fulltime').hide();
$('.agent').hide();
$('.error').show();
}
});
$('#qtyA').on('change', function() {
var selVal = $("#acct").val();
if (!isNaN($(this).val())) {
var total = 0;
if (selVal == '1') {
total = parseInt($(this).val()) * 1280;
}
else if (selVal == '2') {
total = parseInt($(this).val()) * 640;
}
$('#totalA').val(total.toFixed(2));
}
else {
$(this).val('0');
$('#totalA').val('0.00');
}
});
});​
Also you can completely eliminate the vanilla javascript and go with jQuery that should be lot easier..

got the answer this is what i used
<script type="text/javascript">
$(document).ready(function(){
$('#acct').change(function() {
$('.box').hide();
$('#acct' + $(this).val()).show();
});
});
</script>

A jsfiddle would help tremendously here. However, it sounds like you're trying to:
Show/hide content containers based on a pulldown selection, and
Process a field value based on the pulldown selection.
These two problems could generally be addressed like so (assuming jQuery, per your snippit):
<select id="time-select">
<option value="full">Full-Time</option>
<option value="part">Part-Time</option>
</select>
<div id="full-detail" class="detail">
Full-time info.
</div>
<div id="part-detail" class="detail">
Part-time info.
</div>
<input type="text" id="computed-value"/>
<script>
$(function() {
"use strict";
function computeValueBasedOn( opt ) {
// Evaluate the computed value here...
return opt ? "do" : "stuff";
}
$("#time-select").change(function(evt) {
$(".detail").hide();
$("#"+ this.value +"-detail").show();
$("#computed-value").val( computeValueBasedOn( this.value ) );
});
});
</script>

Related

How to get the value from N dynamic inputs

I have a select with an options, this options have the number of inputs that user want to draw, after that user can type information in that inputs and finally they have to click a button to display that values, right now I'm doing this like this:
var value1 = $('#Input1').val();
The problem here is that the user can create a maximum of 200 inputs, so if I keep doing this in the above way I'll need to do that with the 200 inputs and it's a lot of code lines, my question is if exits a way to get the value of N inputs, I draw the inputs dynamically with a for loop, so all the input ID is something like Input(MyForVariable), Input1, Input2... etc, so maybe I'm thinking in create another loop to get the value of that inputs, here is my code:
$(document).ready(function () {
$('#sel').change(function () {
draw();
});
$('#btn').click(function () {
show();
});
});
function draw() {
var selected = $('#sel').val();
var html = "";
for (i = 1; i <= selected; i++) {
html += '<input type="text" id="Imput' + i + '" />';
}
$('#forms').html(html);
}
function show() {
var total = $('#sel').val();
if (total == 2) {
var val1 = $('#Imput1').val();
var val2 = $('#Imput2').val();
alert(val1 + val2);
}
if (total == 3) {
var val1 = $('#Imput1').val();
var val2 = $('#Imput2').val();
var val3 = $('#Imput3').val();
alert(val1 + val2 + val3);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sel">
<option value="2">A</option>
<option value="3">B</option>
<option value="4">C</option>
<option value="5">D</option>
</select>
<div id="forms">
</div>
<button id="btn">Click</button>
Put all your inputs inside a container, and loop through them:
$('#add').on('click', function () {
$('<input />').appendTo('#myinputs');
});
$('#get').on('click', function () {
var values = [];
$('#myinputs input').each(function () {
values.push(this.value);
});
console.log(values);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="myinputs">
<input />
</div>
<button id="add">Add another input</button>
<hr />
<button id="get">Get values</button>
You can set some attribute and get all elements that has it:
$(document).ready(function () {
$('#sel').change(function () {
draw();
});
$('#btn').click(function () {
show();
});
});
function draw() {
var selected = $('#sel').val();
var html = "";
for (i = 1; i <= selected; i++) {
html += '<input type="text" id="Imput' + i + '" to-count />';
}
$('#forms').html(html);
}
function show() {
var total = $('#sel').val();
var sum = "";
var inputs = $('[to-count]');
console.log(inputs.length);
for (let i=0; i < inputs.length ; i++){
sum += inputs[i].value;
}
alert(sum);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sel">
<option value="2">A</option>
<option value="3">B</option>
<option value="4">C</option>
<option value="5">D</option>
</select>
<div id="forms">
</div>
<button id="btn">Click</button>
You can get the values for each of the Select options by using the following code:
$("#sel option").each(function() {
console.log($(this).val());
});
You can always loop throw your inputs like this:
var myInputArray = [];
$('input[type="text"]').each(function(){
myInputArray.push($(this).val());
}
Then you can get your values by locking in the array:
alert(myInputArray[0]) //The first value of the array => first input

Cannot use text in option value with keyup function

I want be able to capture to name=formdesc an option value that is text and not numbers, but I need numbers to calculate price point below. Is there a way to change it, so that it calculates properly (below JS) and capture option values as text only instead numbers (HTML)?
Sample of what I need:
<select id="apparelType" name="formdesc">
<option selected="selected" value="na">Select</option>
<option value="tshirt">T-Shirt</option>
BUT Breakes my JS!
HTML: (what I have now)
<select id="apparelType" name="formdesc">
<option selected="selected" value="na">Select</option>
<option value="0">T-Shirt</option>
<option value="1">Shorts</option>
<option value="2">Hat</option>
<option value="3">Bag</option>
</select>
<input id="numb" type="number" name="formterm">
<id="tot"><Total: $0.00 >
JS:
<script type="text/javascript">// <![CDATA[
//
$(document).ready(function(){
$('#numb').keyup(function(){
var appVal = new Array();
appVal[0] = 15; <--[tshirt]
appVal[1] = 20;
appVal[2] = 25;
appVal[3] = 30;
var cost = 0;
var fmapVal = $('#apparelType').val();
if (fmapVal == 'na')
{ alert ('Please select an apparel type.');
}
else
{
cost = appVal[fmapVal];
};
//alert(cost);
var getNumb = $('#numb').val();
var baseTotal = cost * getNumb;
var getTax = baseTotal * .06;
var getTotal = baseTotal + getTax;
$('#tot').html('Total: $' + getTotal.toFixed(2));
$('#formbal').val(getTotal.toFixed(2));
});
});
// ]]></script>
<form>
<select id="apparelType" name="apparelType">
<option selected="selected" value="na">Select</option>
<option value="0">T-Shirt</option>
<option value="1">Shorts</option>
<option value="2">Hat</option>
<option value="3">Bag</option>
</select>
<label for="numb">Total: <span>$</span></label>
<input id="numb" type="number" name="formterm" value="0.00" >
<input id="pretaxTotal" type="hidden" value="0.00" >
<br>
<textarea id="formdesc" name="formdesc" rows="12" cols="20"></textarea>
</form>
<script type="text/javascript">
$('#apparelType').change(function(){
var apparelType = $('#apparelType');
var fmapVal = apparelType.val();
if (fmapVal == 'na') {
alert('Please select an apparel type.');
} else {
var appVal = [ 15, 20, 25, 30 ];
var description = apparelType.find('option:selected').text();
var cost = appVal[fmapVal];
var pretaxTotal = parseInt($('#pretaxTotal').val());
var subtotal = pretaxTotal + cost;
var updatedTotal = ( subtotal * 1.06 ).toFixed(2);
$('#pretaxTotal').val(subtotal);
$('#numb').val(updatedTotal);
$('#formdesc').append(description + '\n');
}
});
/* The following code is cosmetic. Makes dollar sign appear to be inside the input field */
$('label > span').css('position','relative').css('left','20px').css('font-size','80%');
$('input[type=number]').css('padding-left','15px');
</script>
If you need to take option name then val is not what you need. Instead try this:
var optionName = $('#apparelType').find('option:selected').text();
Hope I understood you correctly (although it's hard).
Could use a function with a case statement to get the cost from passed text strings:
function getVal(value) {
switch(value) {
case 'tshirt':
cost = 15;
break;
case 'shorts':
cost = 15;
break;
case 'hat':
cost = 15;
break;
case 'bag':
cost = 15;
break;
default:
cost = 'Please select an option...';
break;
}
return cost;
}
Then in your if statement use cost = getVal(fmapVal);.

How could I accomplish this with Jquery?

How can I make it so Jquery checks that ESNStart and ESNEND in the HTML form are in the same range otherwise it throws an alert saying that both numbers need to be in the same range to the user after typing in the value for ESNEnd ??
I still don't understand how I could also make it so ESNList gets checked for all its multiple values entered in the text field to be in the same range otherwise it also throws an alert to the user to enter a number in the same range as shown by the if statements ? A fiddle demonstrating this would help me learn so much , thanks a bunch !
<html>
<head>
<script type="text/javascript" src="jquery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function() {
$(":text").css("border", "2px solid red");
$(":text").keyup(function() {
var enteredData = $(this).val()
console.log(enteredData);
if (enteredData == "") {
$(this).css("border", "2px solid red");
} else {
$(this).css("border", "inherit");
}
if ($(this).attr("id") == "ESNList") {
esnList = parseInt(enteredData);
switch (true) {
case (esnList >= 986329 && esnList <= 999999):
$("#ddl_StxName").val("stx2");
$("#ddl_rtumodel").val("globalstar");
break;
case (esnList >= 660000 && esnList <= 699999):
$("#ddl_StxName").val("mmt");
$("#ddl_rtumodel").val("globalstar");
break;
case (esnList >= 200000 && esnList <= 299999):
$("#ddl_StxName").val("stm3");
$("#ddl_rtumodel").val("stmcomtech");
break;
case (esnList >= 1202114 && esnList <= 1299999):
$("#ddl_StxName").val("smartone");
$("#ddl_rtumodel").val("globalstar");
break;
}
}
});
});
</script>
</head>
<body>
<form id="provision">ESNList:
<input type="text" id="ESNList" name="ESNList" size="30" />
<br />ESN Start:
<input type="text" id="ESNStart" name="ESNStart" size="10" />
<br />ESN End:
<input type="text" id="ESNStart" name="ESNStart" size="10" />
<br />UnitName:
<input type="text" id="STxName" name="STxName" size="30" />
<br />Unit Model:
<select name="STxName" id="ddl_StxName">
<option value="stx2">STX2</option>
<option value="stm3" selected>STM3</option>
<option value="acutec">Acutec</option>
<option value="trackpack">Trackpack</option>
<option value="mmt">MMT</option>
<option value="smartone">Smartone</option>
<option value="smartoneb">SmartOneB</option>
</select>
<br />RTU Model Type:
<select name="rtumodel" id="ddl_rtumodel">
<option value="globalstar">GlobalStar</option>
<option value="both">Both</option>
<option value="comtech">Comtech</option>
<option value="stmcomtech">STMComtech</option>
</select>
<br />
<input type="submit" value="submit" />
</form>
</body>
</html>
I created some methods that seem to work, although I haven't created groups of numbers that are out of range.
I strongly suggest you don't allow user to enter comma separated lists as it will be hard to point to user the invalid entries. It would be a lot cleaner having each number in it's own input. You can easily add a button for "Add new number" and create a new input for it.
I used arrays to store ranges and the values for the valid range that get changed for other fields. This module is not trivial and suggest you create a testing sandbox with a wide variety of numbers you can test with.
$('#ESNList').keyup(function(){
var enteredData = $(this).val();
$(this).removeClass('valid');
if( enteredData == ''){
return;
}
if(hasMultipleValues(enteredData)){
var range=rangeCheckMultipleNumbers(enteredData)
if( range===false){
log('Numbers not in same range');
return;
} else{
setRangeValues(range);
$(this).addClass('valid');
}
}
var rangeIdx = getRangeIndex(enteredData);
if(rangeIdx===false){
log('Number not in range');
}else{
setRangeValues(rangeIdx);
$(this).addClass('valid');
}
});
function hasMultipleValues( str){
/* second test for a singel entry with comma at end*/
return str.indexOf(',') !=-1 && str.indexOf(',') != str.length-1;
}
var ranges = [
[986329, 999999],
[660000, 699999],
[200000, 299999],
[1202114, 1299999]
];
var rangeText = [
["stx2", "globalstar"],
["mmt", "globalstar"],
["stm3", "stmcomtech"],
["smartone", "globalstar"]
]
/* returns range index if all in same range, otherwise returns false*/
function rangeCheckMultipleNumbers(str) {
var nums = str.split(',');
var rangeMatch = true; /* clean array to remove empty values if extra commas*/
nums = $.grep(array, function(item, index) {
return parseInt(item);
});
var groupRange = getRangeIndex(nums[0]);
if(nums.length > 1) {
for(i = 1; i < nums.length; i++) {
if(!checkSameRange(nums[i - 1], nums[i])) {
rangeMatch = false;
}
}
}
return rangeMatch ? groupRange : false;
}
function setRangeValues(rangeIndex) {
$("#ddl_StxName").val(rangeText[rangeIndex][0]);
$("#ddl_rtumodel").val(rangeText[rangeIndex][1]);
}
function checkSameRange(num1, num2) {
return getRangeIndex(parseInt(num1, 10)) == getRangeIndex(parseInt(num2, 10));
}
/* returns false if out of range, otherwise returns range index*/
function getRangeIndex(num) {
var idx = false;
$.each(ranges, function(i, range) {
if(num >= range[0] && num <= range[1]) {
idx = i;
return false;
}
});
return idx;
}
DEMO: http://jsfiddle.net/hXsQ8/1/

JavaScript Giving 'Object Expected' Error

I am writing some code that shows or hides a calendar based on a drop down select form. I have it set to run my showHideCalendar() function as an onchange action on the drop down selection. When I change the selected option I receive an "Object expected" error. I have included the relevant HTML and JavaScript code.
<script type="text/javascript" language="javascript">
function showHideCalendar(element) {
document.getElementById("calendar").style.display = "none";
if (document.getElementById("dropdown").selectedIndex === 13) {
cal5.popup();
document.getElementById("textField").value = "";
document.getElementById("calendar").style.display = "inline";
}
}
</script>
<FORM NAME='Labs' METHOD='POST' ACTION="">
<select id="dropdown" name='TimeFrame0' onchange='showHideCalendar(document.Labs.TimeFrame0)'>
<option value='NoReorder'>Do Not Reorder</option>
<option value='2012-06-14 08:40:39.067'>Today</option>
<option value='2012-06-21 08:40:39.067'>1 Week</option>
<option value='2012-06-28 08:40:39.067'>2 Weeks</option>
<option value='2012-07-05 08:40:39.067'>3 Weeks</option>
<option value='2012-07-12 08:40:39.067'>4 Weeks</option>
<option value='2012-07-26 08:40:39.067'>6 Weeks</option>
<option value='2012-07-14 08:40:39.067' selected>1 Month</option>
<option value='2012-08-14 08:40:39.067'>2 Months</option>
<option value='2012-09-14 08:40:39.067'>3 Months</option>
<option value='2012-10-14 08:40:39.067'>4 Months</option>
<option value='2012-12-14 08:40:39.067'>6 Months</option>
<option value='2013-03-14 08:40:39.067'>9 Months</option>
<option value='custom' id='custom'>Calendar Select</option>
</select>
<div id='calendar' style='display:inline'>
<input type=text name='StartDate' value='' size=20 onchange='inputChanged()' onkeydown='inputChanged()' onblur='inputChanged()' id='textField'>
<a href='javascript:cal5.popup();' onmousedown='inputChanged()'> <img src='/jscalendar/img/cal.gif' width='16' height='16' border='0' alt='Click Here to Pick up the date'></a>
</div>
<input type=checkbox name=SameDate value='on' checked onClick='SetTimeFrame(document.Labs.TimeFrame0)'> Use Same Date For All Labs
<input class='btnsave' type=button name=Save value='Reorder Labs' onClick=javascript:document.Labs.action='/LabReview/Reorder.php?PROV=PROVID&MaxCount=2&Text=1';document.Labs.submit();>
<input class='btncancel' type=button name=Cancel value=Cancel onClick=javascript:top.window.close()>
</FORM>
Does anyone see any reason why this is not working. The error is thrown on the line <select id="dropdown" name='TimeFrame0' onchange='showHideCalendar(document.Labs.TimeFrame0)'>.
One of the answerers thinks the error isn't in my new code, but rather something else on the page. I am editing my question to add the rest of the javascript that is on the page.
<script type="text/javascript" language="javascript">
function showHideCalendar(element) {
document.getElementById("calendar").style.display = "none";
if (document.getElementById("dropdown").selectedIndex === 13) {
cal5.popup();
document.getElementById("textField").value = "";
document.getElementById("calendar").style.display = "inline";
}
}
function inputChanged() {
document.getElementById("dropdown").selectedIndex = 13;
}
function SetTimeFrame(element)
{
if (document.Labs.SameDate.checked==true)
{
var Elements=document.Labs.elements.length;
for (var i=0; i<Elements; i++)
{
if (document.Labs.elements[i].type=='select-one')
{
document.Labs.elements[i].options[element.selectedIndex].selected=true;
}
}
}
}
if (top.window.opener.document.getElementById("Complete<?php echo($_GET['Item']); ?>"))
{
if ('<?php echo($Reviewed); ?>' == 'yes')
{
window.opener.document.getElementById("Complete<?php echo($_GET['Item']); ?>").style.visibility='visible';
window.opener.document.getElementById("Partial<?php echo($_GET['Item']); ?>").style.visibility='hidden';
}
else if ('<?php echo($Reviewed); ?>' == 'partial')
{
window.opener.document.getElementById("Partial<?php echo($_GET['Item']); ?>").style.visibility='visible';
window.opener.document.getElementById("Complete<?php echo($_GET['Item']); ?>").style.visibility='hidden';
}
}
else
{
var temp=top.window.opener.location.href;
top.window.opener.location.href=temp;
top.window.opener.top.window.location.reload();
}
function DateCheck(element)
{
var xx = element.value;
var re = new RegExp("^[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]$");
var re2 = new RegExp("^[0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]$");
var re3 = new RegExp("^[0-9][0-9]/[0-9]/[0-9][0-9][0-9][0-9]$");
var re4 = new RegExp("^[0-9]/[0-9]/[0-9][0-9][0-9][0-9]$");
var error = "";
var maxdays = new Array(0,31,29,31,30,31,30,31,31,30,31,30,31);
var retval = true;
if(element.value != "")
{
if(xx.search(re) < 0 && xx.search(re2) < 0 && xx.search(re3) < 0 && xx.search(re4) < 0)
{
error = "Invalid Date Format " + xx + ". Please enter dates in the format mm/dd/yyyy."
retval = false;
element.value = ""
}
else
{
var list = xx.split("/");
var month = list[0];
if(month.charAt(0) == "0")
month = month.substr(1);
if( list[0] < 1 || list[0] > 12)
{
error = "Invalid Month " + list[0];
retval = false;
element.value = ""
}
else
if(list[1] < 1 || list[1] > maxdays[month])
{
error = "Invalid Day " + list[1];
retval = false;
element.value = ""
}
else
if(list[2] < 1900)
{
error = "Invalid Year (Must be greater than 1900) " + list[2];
retval = false;
element.value = ""
}
}
if(!retval)
alert(error);
return retval;
}
}
</script>
Change:
<select id="dropdown" name='TimeFrame0' onchange='showHideCalendar(document.Labs.TimeFrame0)'>
To:
<select id="dropdown" name='TimeFrame0' onchange='showHideCalendar(this)'>
It turns out the problem was caused by the following block of code.
if (top.window.opener.document.getElementById("Complete<?php echo($_GET['Item']); ?>")) {
if ('<?php echo($Reviewed); ?>' == 'yes')
{
window.opener.document.getElementById("Complete<?php echo($_GET['Item']); ?>").style.visibility='visible';
window.opener.document.getElementById("Partial<?php echo($_GET['Item']); ?>").style.visibility='hidden';
}
else if ('<?php echo($Reviewed); ?>' == 'partial')
{
window.opener.document.getElementById("Partial<?php echo($_GET['Item']); ?>").style.visibility='visible';
window.opener.document.getElementById("Complete<?php echo($_GET['Item']); ?>").style.visibility='hidden';
}
}
else
{
var temp=top.window.opener.location.href;
top.window.opener.location.href=temp;
top.window.opener.top.window.location.reload();
}
When I removed that from the code, it worked like a charm. Thanks to everyone for their suggestions and thoughts.

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