Disable textbox when two textbox is equal - javascript

How can i disable textbox when selected (textbox name) and quantity (textbox name) is equal. i used this codes its working but when selected (textbox name) is equal to 3 the txtCombo (textbox name) is not disabled but when equal to 4 it became disabled how should i work on this ? thank you in advance.
// disable button if equal
// $('#button').click(function(){
$('#button').click(function() {
var firstValue = $("#quantitytotransfer").val();
var secondValue = $("#selected").val();
if ((firstValue == secondValue)) {
$("#txtCombo").prop("disabled", true);
}
});
function addCombo() {
var textb = document.getElementById("txtCombo");
var combo = document.getElementById("combo");
var option = document.createElement("option");
option.text = textb.value.trim();
option.value = textb.value.trim();
option.selected = true;
if ($('#combo option[value="' + textb.value.trim() + '"]').text() == textb.value.trim()) {
alert("Duplicate found or you entered empty value");
return false;
}
try {
combo.add(option, null); //Standard
} catch (error) {
combo.add(option); // IE only
}
textb.value = "";
}
$("#txtCombo").on("keydown", function(e) {
return e.which !== 32;
});
$(document).ready(function() {
$('#button').click(function() {
var data = [];
$.each($("#combo option:selected"), function() {
data.push($(this).attr("value"));
});
$('#imei').val(data.join(","));;
var count = $("#combo :selected").length;
$('#selected').val(count);
});
});
$(document).ready(function() {
$('#button').click(function() {
var data = [];
$.each($("#combo option:selected"), function() {
data.push($(this).attr("value"));
});
$('#imei').val(data.join(","));;
var count = $("#combo :selected").length;
$('#selected').val(count);
});
});
$("#combo").on('change', function() {
var count = $("#combo :selected").length;
$('#selected').val(count);
});
var text = $("#text").val();
var previousOption;
$('select[name=combo] option').each(function() {
if (this.text == previousOption) $(this).remove();
previousOption = this.text;
});
// separated by comma to textbox
$(document).ready(function() {
$("#combo").change(function() {
var data = [];
$.each($("#combo option:selected"), function() {
data.push($(this).attr("value"));
});
$('#imei').val(data.join(","));;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<BODY style="font-family: sans-serif">
<fieldset>
<legend>Combo box</legend>
Add to Combo:
<input type="text" name="txtCombo" id="txtCombo" />Selected:
<input type="text" name="selected" id="selected" />IMEI Selected:
<input type="text" name="imei" id="imei" />Quantity:
<input type="text" name="quantity" value="3" id="quantitytotransfer" />
<br>
<input type="button" id="button" value="Add" onclick="addCombo()">
<br/>Combobox:
<select name="combo" multiple id="combo"></select>
</fieldset>
</BODY>

You can achieve this easily :
function checkIfEqual(){
if($("#selected").val() === $("#quantitytotransfer").val())
$("#txtCombo").prop("disabled", true);
else
$("#txtCombo").prop("disabled", false);
}
$("#button").click(function(){
$("#selected").val($("#combo option:selected").length);
checkIfEqual();
});
demo here

Have you tried this:
function addCombo() {
var txtSelected = $('#selected').val();
var qty = $('#quantitytotransfer').val();
if(parseInt(txtSelected) == parseInt(qty)) {
alert('Equal');
document.getElementById('txtCombo').disabled = true;
} else {
alert('Not equal');
document.getElementById('txtCombo').disabled = false;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<BODY style="font-family: sans-serif">
<fieldset>
<legend>Combo box</legend>
Add to Combo: <input type="text" name="txtCombo" id="txtCombo"/><br>
Selected: <input type="text" name="selected" id="selected" class="toggle"/><br>
IMEI Selected: <input type="text" name="imei" id="imei"/><br>
Quantity: <input type="text" name="quantity" value="3" id="quantitytotransfer" class="toggle"/><br>
<input type="button" id="button" value="Add" onclick="addCombo()"><br>
Combobox: <select name="combo" multiple id="combo"></select>
</fieldset>
</BODY>

Related

Disable Select Option if already selected

I have created a table which clones its last row if all the text boxes are filled and select is changed in the previous row. I am trying to add a condition that the newly dropdown options should be disabled if they were already selected in previous rows .
Demo Fillde
disable option code:
$('select').change(function() {
var value = $(this).val();
$(this).siblings('select').children('option').each(function() {
if ( $(this).val() === value ) {
$(this).attr('disabled', true).siblings().removeAttr('disabled');
}
});
});
Full JS:
$('#results').append('<table width="100%" border="1" cellspacing="0" cellpadding="5" id="productanddates" class="border"> <tr><td> <input type="text" name="to1" id="to1" value="" /> </td> <td> <select class="dd" name="Phonenumberdd1" id="Phonenumberdd1"> <option value="test">test </option><option value="test2">test 2</option></select></td> <td> <input type="text" name="renewal_by1" id="renewal_by1" /> </td> <td> <input type="text" name="Renivaul_to1" id="Renivaul_to1" value="" /> </td></TR></TABLE>'
);
$('select').change(function() {
var value = $(this).val();
$(this).siblings('select').children('option').each(function() {
if ( $(this).val() === value ) {
$(this).attr('disabled', true).siblings().removeAttr('disabled');
}
});
});
$('#results').on('focus', ':input', function() {
$(this).closest('tr').filter(function() {
return !$(this).data('saved');
})
.find(':input').each(function() {
$(this).data('value', this.value);
$(this).closest('tr').data('saved', true);
});
})
.on('input change', ':input', function() {
$(this).data('filled', this.value != $(this).data('value'))
var tr = $(this).closest('tr');
all = tr.find(':input'),
fld = all.filter(function() {
return $(this).data('filled');
});
if( all.length == fld.length ) {
if( !tr.data('done') ) {
$('#buttonclck')[0].click();
tr.data('done', true);
}
} else {
if( tr.data('done') ) {
tr.data('done', false);
}
}
});
$('#buttonclck').on('click', function () {
var lastRow = $('#productanddates').closest('#productanddates').find("tr:last-child");
var lastRowInputs = lastRow.find('input');
var isClone = false;
lastRowInputs.each(function() {
if($(this).val().length) {
isClone = true;
}
});
if(!isClone)
return false;
var cloned = lastRow.clone();
cloned.find('input, select').each(function () {
var id = $(this).attr('id');
var regIdMatch = /^(.+)(\d+)$/;
var aIdParts = id.match(regIdMatch);
var newId = aIdParts[1] + (parseInt(aIdParts[2], 10) + 1);
$(this).attr('id', newId);
$(this).attr('name', newId);
});
cloned.find("input[type='text']").val('');
cloned.insertAfter(lastRow);
});
HTML:
<div id="results"></div>
<input id="buttonclck" type="button" class="hide" value="button"/>
Your mistake was here:
$(this).siblings('select').children('option').each(function() { ... }
It should be :
$(this).children('option').each(function() { ... }
Why do you select siblings of the select element? You should directly descend to its options. I do not know if it is intended, but such code will make option disabled in both rows: previous and newly generated.
Here is the fiddle:
http://jsfiddle.net/99pvwypp/19/

Finding closest input text after select dropdown was chosen

So what I'm trying to do is change value of the input with id championSpell[] whenever something from dropdown select name="change[]" id="change[] is chosen. Inputs are generated dynamically. Test variable in function val() is responsible for that change and is the one I have problems with.
<script src="LeagueNotes/js/jquery.min.js"></script>
<script src="LeagueNotes/js/champions_list.js"></script>
<script src="LeagueNotes/js/jquery.validate.min.js"></script>
<style>
* { font-family:Arial; }
h2 { padding:0 0 5px 5px; }
h2 a { color: #224f99; }
a { color:#999; text-decoration: none; }
a:hover { color:#802727; }
p { padding:0 0 5px 0; }
input { padding:5px; border:1px solid #999; border-radius:4px; -moz-border-radius:4px; -web-kit-border-radius:4px; -khtml-border-radius:4px; }
</style>
<h2>
Add Another Champion
</h2>
<form name="second_form" id="second_form" action="#" method="POST" style="margin: 0;" >
<div id="p_scents">
<p>
<label for="p_scnts">
<input type="text" id="champion[]" size="20" list="champions" value="" placeholder="Enter Champion's name">
<datalist id="champions"></datalist>
Add General Change<a></a>
Add Spell<a></a>
</label>
</p>
</div>
<br/><input type="submit" value="submit">
</form>
<script>
for(var key in champions){
if(champions.hasOwnProperty(key)){
$('#champions').append('<option value="' + key + '">');
}
}
var config = {
fillAll: true
};
document.forms["second_form"].oninput = function(e) {
var champion = this["champion[]"];
//Force into array
if (champion[0] === undefined)
champion = [this["champion[]"]];
var reached = {
valid: 0,
unique: 0
};
var inputs = [].map.call(champion, function(n) {
return n.value
}).filter(function(n) {
return n.length
});
var valid = [].every.call(champion, function(n, i) {
n.setCustomValidity("");
if (config.fillAll) return (reached.valid = i, champions.hasOwnProperty(n.value));
else return n.value ? (
reached.valid = i,
champions.hasOwnProperty(n.value) > -1
) : true;
});
var unique = inputs.slice(0).sort().every(function(n, i, a) {
reached.unique = inputs.lastIndexOf(n);
return n != a[i - 1];
});
//Check for valid champions
if (!valid) {
champion[reached.valid].setCustomValidity("This is not a valid champion, please correct this field and resubmit.")
}
//Check for duplicates
if (!unique) {
champion[reached.unique].setCustomValidity("This champion has already been entered.")
}
this.checkValidity();
};
function change(x, dblchamp){
if(dblchamp===true){
if(x==="Passive"){x=0;}
if(x==="Q"){x=1;}
if(x==="Q2"){x=2;}
if(x==="W"){x=3;}
if(x==="W2"){x=4;}
if(x==="E"){x=5;}
if(x==="E2"){x=6;}
if(x==="R"){x=7;}
if(x==="R2"){x=8;}
}else if(dblchamp===false){
if(x==="Passive"){x=0;}
if(x==="Q"){x=1;}
if(x==="W"){x=2;}
if(x==="E"){x=3;}
if(x==="R"){x=4;}
}
console.log(x);
return x;
}
function val(elm) {
var championsWithExtraSpells = ["Aatrox", "Elise", "Fizz", "Heimerdinger", "Jayce", "Lee Sin", "Nidalee", "Rek'Sai","Twisted Fate"];
//var championName = $("#change").closest('input').val();
//var championName =$("#champion\\[\\]").val();
var championName = $(elm).closest("label").find("input").val();
//document.getElementById("champion[]").value;
console.log(championName);
if($.inArray(championName, championsWithExtraSpells)==-1){
var existsInArray = false;}
else{
var existsInArray = true;}
var d = $(elm).val();
var spellname = document.getElementById("championSpell[]");
var z = champions[""+championName+""][change(d, existsInArray)];
test = $(elm).nextAll("input").first().val('test');
test.value=champions[""+championName+""][change(d, existsInArray)];
}
$(function() {
var scntDiv = $('#p_scents');
var i = $('#p_scents label').size() + 1;
var j =0;
$('body').on('click', '#addChampion', function() {
$('<p>Remove<br><label for="p_scnts"><input type="text" id="champion[]" size="20" list="champions" name="champion[]" value="" placeholder="Enter Champion\'s name" /><datalist id="champions"></datalist>Add General Change Add Spell<a></a></label></p>').appendTo(scntDiv);
i++;
return false;
});
$('body').on('click', '#remScnt', function() {
if( i >2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
$('body').on('click', '#addGeneral',function() {
$(
'<p><label for="var"><textarea type="text" id="champion[]" size="20" name="GeneralChange[]" value="" placeholder="Enter Description" /><select><option value="buff">Buff</option><option value="nerf">Nerf</option><option value="new">New</option><option value="change">Change</option><option value="bugfix">Bugfix</option></select></label> Remove Change</p>').appendTo($(this).next());
j++;
return false;
});
$('body').on('click', '#remVar',function() {
$(this).parent('p').remove();
return false;
});
$('body').on('click', '#addSpell',function() {
$(
'<p><select name="change[]" id="change[]" onchange="val(this)"><option value="Passive">Passive</option><option value="Q" selected>Q</option><option value="W">W</option><option value="E">E</option><option value="R">R</option></select><label for="var"><input type="text" id="championSpell[]" readOnly="true"><br><textarea type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Enter Description" /><select><option value="buff">Buff</option><option value="nerf">Nerf</option><option value="new">New</option><option value="change">Change</option><option value="bugfix">Bugfix</option></select></label> Add Change Remove Spell</p>').appendTo($(this).next());
return false;
});
});
</script>
Your post is really confusing but if you're trying to get the value of an input text witch is at the same time your drop-down menu and can contains different values. You just need to use a select function in your jQuery code.
Something similar to this:
$('#dropdown :selected').text();
You could use a change method alongside with a switch statement, something like this:
HTML:
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<input type="text" id="champion" size="20" list="champions" value="" placeholder="Enter Champion's name">
jQuery
var inputValue;
$('select').on('change', function() {
var selectedValue = $(this).val();
switch(selectedValue) {
case 'volvo':
inputValue = 'volvo';
break;
case 'saab':
inputValue = 'saab';
break;
case 'mercedes':
inputValue = 'mercedes';
break;
case 'audi':
inputValue = 'audi';
break;
default:
break;
}
$('#champion').val(inputValue);
});
Here is a working example:
http://jsfiddle.net/5spaa6kj/

How to seperate the values of textbox so that I can sort by each value

I have a textbox where the user can input a value into a listbox. Then, I have buttons to either Delete that value, or Sort the value.
My problem is that I want the value to be sorted by those 2 separated values. For example, the user would enter City=Chicago in the textbox. And there would be 2 sort buttons, to 'Sort by City' and 'Sort by Value' where value in this case is Chicago.
So after hours of trying I can't figure out how to:
1. Restrict the user to only be able to enter a value like %=% (e.g. City=Chicago)
2. Have separate sort buttons for the values on either side of the equal sign
http://jsfiddle.net/uudff585/6/
<div class='teststyles'>
<h3>Test</h3>
Name/Value Pair
<br />
<input id="PairTextbox" type="text" value="city" />=<input id="PairTextbox1" type="text" />
<input type="button" value="Add" id="addButton" />
<br />
<br />Name/Value Pair List
<br />
<select multiple="multiple" id="PairListbox"></select>
<input type="button" value="Sort By Name" sort-type="0" id="sortName">
<input type="button" value="Sort By Value" sort-type="1" id="sortValue"><br>
<input type="button" value="Delete" id="deleteButton" />
Script:
var listArray = [];
function addNewItem() {
console.log("ok2");
var textbox = document.getElementById('PairTextbox');
var textbox1 = document.getElementById('PairTextbox1');
var listbox = document.getElementById('PairListbox');
var newOption = document.createElement('option');
newOption.value = listArray.length-1; // The value that this option will have
newOption.innerHTML = textbox.value + "=" + textbox1.value; // The displayed text inside of the <option> tags
listbox.appendChild(newOption);
listArray.push([textbox.value, textbox1.value, ]);
}
function deleteItem() {
var listbox = document.getElementById('PairListbox');
if (listbox.selectedIndex != -1) {
console.log(listbox.selectedIndex);
delete listArray[listbox.value];
listbox.remove(listbox.selectedIndex);
}
}
function sortItems(e) {
var sorttype = e.target.getAttribute("sort-type");
var $listbox = document.getElementById('PairListbox');
var $options = listArray.map(function (option) {
return option;
});;
$options.sort(function (a, b) {
var an = a[sorttype],
bn = b[sorttype];
if (an > bn) {
return 1;
}
if (an < bn) {
return -1;
}
return 0;
});
$listbox.innerHTML = "";
$options.forEach(function ($option, index) {
var newOption = document.createElement('option');
newOption.value = index; // The value that this option will have
newOption.innerHTML = $option[0] + "=" + $option[1]; // The displayed text inside of the
$listbox.appendChild(newOption);
});
}
document.getElementById('addButton').addEventListener('click', addNewItem);
document.getElementById('sortName').addEventListener('click', sortItems);
document.getElementById('sortValue').addEventListener('click', sortItems);
document.getElementById('deleteButton').addEventListener('click', deleteItem);
For those who would like to use jQuery, validation and auto-sorting this FIDDLE. The HTML is:
<div class='teststyles'>
<h3>Test</h3>
<p>Name/Value Pair</p>
<p><input id="PairTextbox" type="text" /> <input type="button" value="Add" id="addButton" /></p>
<p>Name/Value Pair List</p>
<p><select multiple="multiple" id="PairListbox"></select></p>
<p>
<input id="byname" type="radio" name="sortby" value="name" checked="checked" /> <label for="byname">sort by name</label><br />
<input id="byvalue" type="radio" name="sortby" value="value" /> <label for="byvalue">sort by value</label>
</p>
<p><input type="button" value="Delete selected" id="deleteButton" /></p>
</div>
and the script:
// Keep your pairs in memory
var pairs = [];
// Keep record of dynamic elements
var listbox = $('#PairListbox');
var textbox = $('#PairTextbox');
var sortInput = $('input[name=sortby]');
function sortItems() {
sortType = sortInput.filter(':checked').val();
if ( sortType=='name' ) {
// Sort by key
console.log( 'sort by key' );
pairs = pairs.sort(function (a, b) {
return a.k.localeCompare(b.k);
});
} else {
// Sort by value
console.log( 'sort by val' );
pairs = pairs.sort(function (a, b) {
return a.v.localeCompare(b.v);
});
};
console.log( pairs );
console.log( '----------' );
};
function printItems() {
var optionsHtml = '';
$.each(pairs, function(i, item) {
optionsHtml += '<option value="' + item.k + '=' + item.v + '">' + item.k + '=' + item.v + '</option>';
});
listbox.html(optionsHtml);
};
// Customize validation of new input
function validateInput() {
var str = textbox.val().replace(/\s+/g, '_');
var splited = str.split('=');
if (splited.length == 2 && splited[0] && splited[1]) {
// Maybe also check if pair already exists in array?
pairs.push({
k: splited[0],
v: splited[1]
});
return true;
} else {
false;
};
}
function addNewItem() {
if (validateInput()) {
sortItems();
printItems();
} else {
alert('Wrong input value!');
}
}
function deleteItem() {
var selectedItems = listbox.find('option:selected');
selectedItems.each(function(i) {
var thisItem = $(this);
var thisValueSplit = thisItem.val().split('=');
pairs = pairs.filter(function (el) {
return !(el.k==thisValueSplit[0] && el.v==thisValueSplit[1]);
});
printItems();
});
}
$('#addButton').on('click', addNewItem);
$('#deleteButton').on('click', deleteItem);
sortInput.on('change', function(e) {
sortItems();
printItems();
});

Check,reset buttons active after all inputs were completed

how can i make check and reset buttons active after 6 inputs were completed? I have tryed:
if($('.input') == ""){
checkBtn.disabled = true;
resetBtn.disabled = true;
}
else{
checkBtn.disabled = false;
resetBtn.disabled = false;
}
EDIT 2 with fiddle : http://jsfiddle.net/usPMd/88/
Edit : Your Jsfiddle return error 404... So I developed a basic example (it is not perfect).
Jsfiddle
Javascript solution :
<body>
<form>
<input type="text" onChange="checkInput()" onKeyup="checkInput()"/>
<input type="text" onChange="checkInput()" onKeyup="checkInput()"/>
<input type="text" onChange="checkInput()" onKeyup="checkInput()"/>
<input type="text" onChange="checkInput()" onKeyup="checkInput()"/>
<input type="text" onChange="checkInput()" onKeyup="checkInput()"/>
<input type="text" onChange="checkInput()" onKeyup="checkInput()"/>
<input id="send" type="submit" disabled/>
<input id="reset" type="reset" disabled/>
</form>
<script type="text/javascript">
var checkBtn = document.getElementById("send");
var resetBtn = document.getElementById("reset");
var inputTag, lengthInputTag, nbCompleted;
function forEach( a, fn ) {
return [].forEach.call(a, fn);
};
function checkInput(){
inputTag = document.getElementsByTagName("input");
lengthInputTag = inputTag.length;
nbCompleted = 0;
console.log(inputTag);
forEach(inputTag, function(el) {
if(el.value != ""){
nbCompleted++;
}
});
if(nbCompleted < 6){
checkBtn.disabled = true;
resetBtn.disabled = true;
}else{
checkBtn.disabled = false;
resetBtn.disabled = false;
}
};
</script>
</body>
if($('.input').length == 6){
checkBtn.disabled = false;
resetBtn.disabled = false;
}else{
checkBtn.disabled = true;
resetBtn.disabled = true;
}
So, use length then:
if($('.input').length == 7){ //after 6 is 7th input
checkBtn.disabled = true;
resetBtn.disabled = true;
}
And also there might be a typo .input should be input but not 100% sure because this might also be class.
Ok, Here you go:
Workign demo: JSFiddle
HTML (partial):
<button id="validateButton" class="validateButton" type="button" disabled="disabled">Check</button>
<button id="resetButton" class="resetButton" type="button" disabled="disabled">Reset</button>
JS:
$(document).on('change blur', '.input', function(){
var count = 0;
$('.input').each(function(){
var elem_v = $.trim ( $(this).val() );
if (elem_v != "") {
count++;
}
})
$('button').prop('disabled', true);
if (count===6){
$('button').prop('disabled', false);
}
});

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