I have a little bit complicated html structure.
I parse it to get this stuff:
Option1: value
Option2: value
from this like html:
<div class="option" id="option-691">
<span class="required">*</span>
<b>Option:</b><br>
<input type="radio" checked="" id="option-value-1250" value="1250" price="1156.0000" name="option[691]">
<label for="option-value-1250">2,35 xx - 1156.00 </label>
<br>
<input type="radio" onchange="recalculateprice();reloadpr();" id="option-value-1251" value="1251" price="506.0000" price_prefix="" points="0" name="option[691]">
<label for="option-value-1251">900 xx - 506.00</label>
<br>
</div>
and this too
<div class="option" id="option-690">
<span class="required">*</span>
<b>Option:</b><br>
<select name="option[690]">
<option price="1156.0000" price_prefix="+" points="0" value="1249">value01
(+1156.00)
</option>
<option price="1156.0000" price_prefix="+" points="0" value="1248">value02
(+1156.00)
</option>
<option price="1156.0000" price_prefix="+" points="0" value="1247">value03
(+1156.00)
</option>
</select>
</div>
And using this I can get data from both types (inputs + selects).
$('#product_options > div.option').each(function() {
var Opt01 = ( $(this).find('option:selected').parent().parent().find('b').text() + $(this).find('option:selected').text() );
var Opt02 = ( $(this).find('input:checked').parent().find('b').text() + $(this).find('input:checked').next().text() );
console.log(Opt01);
console.log(Opt02);
});
But, I want to get Opt01 and Opt02 outside the .each() loop. How I can do this?
Variables declared within functions can't be accessed outside of them. Just declare them outside of the loop:
var Opt01;
var Opt02;
$('#product_options > div.option').each(function() {
Opt01 = ( $(this).find('option:selected').parent().parent().find('b').text() + $(this).find('option:selected').text() );
Opt02 = ( $(this).find('input:checked').parent().find('b').text() + $(this).find('input:checked').next().text() );
console.log(Opt01);
console.log(Opt02);
});
I want to get Opt01 and Opt02 outside the .each() loop
Since the variables are local in that context (by using var keyword), outside of the each callback the variables are undefined. You could define them outside of the each callback, e.g. var opt1, opt2;, but what will happen? In each iteration the values are overridden and the last values win. If the selector returns 1 element then each shouldn't be used in the first place.
You could define a function and pass the values to it.
$('#product_options > div.option').each(function() {
var Opt1 = '...';
var Opt2 = '...';
doSomething(Opt1, Opt2);
});
Or use the map method and create an array of objects:
var options = $('#product_options > div.option').map(function() {
var opt01 = '...';
var opt02 = '...';
return {
opt1: opt01,
opt2: opt02
}
}).get();
Just declare the variable outside the each loop. Variables declared inside the function can be accessed only from inside. JsFiddle
var Opt01, Opt02;
function find(){
$('#product_options > div.option').each(function() {
var option1 = ( $(this).find('option:selected').parent().parent().find('b').text() + $(this).find('option:selected').text() );
var option2 = ( $(this).find('input:checked').parent().find('b').text() + $(this).find('input:checked').next().text() );
if(option1){
Opt01 = option1;
console.log("inside: "+Opt01);
}
if(option2){
Opt02 = option2;
console.log("inside: "+Opt02);
}
});
console.log("outside: "+Opt01);
console.log("outside: "+Opt02);
}
It's very simple,
You have to declare your variables outside of your function as global.
But don't declare only,assign some value
Var opt1=0;
Thanks guys. I've added another validation rule before loop and code looks like this, so far. And it works fine:
if ($('#product_options div.option').length) {
$('#product_options > div.option').each(function () {
//defining
OptionTitle = $(this).find('option:selected').parent().parent().find('b').text();
OptionValue = $(this).find('option:selected').text();
InputTitle = $(this).find('input:checked').parent().find('b').text();
InputValue = $(this).find('input:checked').next().text();
//
if (OptionTitle != '' && OptionValue != '') {
Opt01 = (OptionTitle + OptionValue)
}
if (InputTitle != '' && InputValue != '') {
Opt02 = (InputTitle + InputValue)
}
});
//get values outside the loop
console.log('Options detected');
if (typeof Opt01 === 'undefined') {
Opt01 = ''
}
if (typeof Opt02 === 'undefined') {
Opt02 = ''
}
console.log('Opt01 = ' + Opt01);
console.log('Opt02 = ' + Opt02);
}
else {
console.log('Options are empty');
var Opt01 = '';
var Opt02 = '';
console.log('Opt01 = ' + Opt01);
console.log('Opt02 = ' + Opt02);
}
Also, fiddle is here http://jsfiddle.net/caLj2xbe/
Related
Basically I'm creating a chrome extension that can pull data from a webpage to speed up data entry. I'm trying to make this as easy for the users as possible, which is causing me some headache myself. I'm allowing them to put an id or a name for a field to lookup, and on my end, I have to determine if it's an input, or just text they're wanting pulled and see if the element exists with the id, and if not, check for an element with their provided value as a name. This has to be done with multiple fields that they provide.
I've tried a few iterations of code to do this. Currently I'm stuck on trying to get this code below to do the trick, but obviously it isn't working. Is there a better way to accomplish this via javascript only?
var msg = {
"first": "first_name_id_name",
"last": "last_name_id_name",
"email": "email_id_name",
"phone": "phone_id_name"
}
var fields_to_find = JSON.parse(msg);
var data_to_push = {};
var current;
var ele;
for (var key in fields_to_find) {
if (fields_to_find.hasOwnProperty(key)) {
console.log(fields_to_find[key]);
ele = document.getElementById(fields_to_find[key]);
if (!ele.value) {
ele = document.getElementById(fields_to_find[key]);
if (ele.innerHTML.length == 0) {
ele = document.getElementsByName(fields_to_find[key]);
if (!ele.value) {
ele = document.getElementsByName(fields_to_find[key]);
if (ele.innerHTML.length == 0) {
current = "";
} else {
current = ele.innerHTML;
}
} else {
current = ele.value;
}
} else {
current = ele.innerHTML;
}
} else {
current = ele.value;
}
data_to_push[key] = current;
}
}
console.log(data_to_push);
<input type="text" id="first_name_id_name" value="John">
<p name="last_name_id_name">Doe</p>
<input type="text" name="email_id_name" value="johndoe#example.com">
<p id="phone_id_name">123-555-1234</p>
Any help you can provide would be awesome and much appreciated.
Thanks for your time!
You could strip off a lot of the superfluous nested if statements with a couple backup values like below. Also, because JSON is a native object in JS, you don't have to do a JSON.parse on your msg object.
var msg = {
first: "first_name_id_name",
last: "last_name_id_name",
email: "email_id_name",
phone: "phone_id_name"
};
var data_to_push = {};
var current;
var ele;
for (var key in msg) {
if (msg.hasOwnProperty(key)) {
console.log(msg[key]);
ele = document.getElementById(msg[key]) || document.getElementsByName(msg[key])[0];
if (ele) {
current = ele.value || ele.innerHTML || '';
} else {
current = '';
}
data_to_push[key] = current;
}
}
console.log(data_to_push);
<input type="text" id="first_name_id_name" value="John">
<p name="last_name_id_name">Doe</p>
<input type="text" name="email_id_name" value="johndoe#example.com">
<p id="phone_id_name">123-555-1234</p>
1 : Use ' for msg variable.
2 : You do not need a lot of conditions.
There are a lot of Incorrect codes, to see all the changes check full code :
var msg = '{ "first": "first_name_id_name","last": "last_name_id_name","email": "email_id_name", "phone": "phone_id_name"}' ;
var fields_to_find = JSON.parse( msg ),
data_to_push = {},
current ,
ele ;
for ( var key in fields_to_find ) {
if ( fields_to_find.hasOwnProperty ( key ) ) {
console.log( fields_to_find[key] );
ele = document.getElementById( fields_to_find[key] ) ? document.getElementById( fields_to_find[key] ) : document.getElementsByName( fields_to_find[key] )[0];
if ( ele ) { data_to_push[key] = ( ele.innerHTML ) ? ele.innerHTML : ( ele.value ? ele.value : '' ) ; }
}
}
console.log(data_to_push);
<input type="text" id="first_name_id_name" value="John">
<p name="last_name_id_name">Doe</p>
<input type="text" name="email_id_name" value="johndoe#example.com">
<p id="phone_id_name">123-555-1234</p>
When I dynamically create checkbox and div, I want to have different id for each of them (like id_1, id_2...).
The first value of my array is erased by the next value.
Currently, I create checkbox for each value I have in my array:
var containerCheckbox = $('#listCheckboxCategories');
// var listCheckboxCategories = $('#listCheckboxCategories');
var CheckboxCreate = '<input id="catCheckbox" type="checkbox" name="categoriesCheckbox" required/>';
var categoriesName = '<span id="catName"/>';
if (tileConfig.isThereFilterRadios == "Yes" && res !== undefined) {
$('#ShowCategories').show();
$('#containerCategories').show();
$.each(res.list, function(index, cat) {
//ToDo: inserer cat.name dans le span
// categoriesName.html(cat.name)
containerCheckbox.append(CheckboxCreate, categoriesName);
$("#catName").html(cat.name);
});
}
Can someone help me ?
You could create a function to return the checkbox element, that way you could pass a variable into the function (eg index) to add to the html to make each id unique
for example
createCheckbox = function (index) {
return '<input id="catCheckbox_' + index + '" type="checkbox" name="categoriesCheckbox" required/>';
}
var containerCheckbox = $('#listCheckboxCategories');
var categoriesName = '<span id="catName"/>';
if (tileConfig.isThereFilterRadios == "Yes" && res !== undefined) {
$('#ShowCategories').show();
$('#containerCategories').show();
$.each(res.list, function(index, cat) {
containerCheckbox.append(createCheckbox(index), categoriesName);
$("#catName").html(cat.name);
});
}
I'm trying to build a query parameter for when doing a search, I managed to build it with input field however there's a select dropdown menu to select other values.
<input type="text" id="dd">
<select name="" class="sel">
<option value=""></option>
<option value="Prepare">Prepare</option>
<option value="Ready">Ready</option>
<option value="Cancel">Cancel</option>
</select>
<button onclick="buildQuery()">Build query</button>
jQuery code for query building the query param
function buildQuery(){
var result = "?";
var getVal = $('input#dd').val();
console.log('Input > ', getVal);
var getSelectVal = $('select#sel').val();
if (getVal != null && (getVal != "")) {
let inputValues = getVal
.split("\n")
.filter(function (str) { return str !== "" })
.join("&test=");
// then add it to the overall query string for all searches
result = result + 'test' + "=" + inputValues + "&";
console.log('Results > ', result);
}
Not sure how can I get the value from the select and construct it similar way to my input console.log output Results > ?test=f&
So if you fill in the input and select an option it the queryParam should say something like ?test=inputVal&test=selectVal or individual ?test=inputVal or ?test=selectVal
What I can do is copy the whole if() statement and replace the getVal with getSelectVal but it seems inefficient and duplicating the code.
Actual code --
newSearchParams.properties.forEach(function (inputSearch) {
// first reparse the input values to individual key value pairs
// Checks which field is not null and with empty string (space)
var getVal = $('textarea.input_' + inputSearch.name).val();
var getSelectVal = $('select.select_' + inputSearch.name).val();
if (getVal != null && (getVal != "")) {
let inputValues = getVal
.split("\n")
.filter(function (str) { return str !== "" })
.join("&" + inputSearch.name + "=");
// then add it to the overall query string for all searches
result = result + inputSearch.name + "=" + inputValues + "&";
}
}, this);
// remove trailing '&'
result = result.slice(0, result.length - 1);
return result;
Sample Fiddle
In case Shibi's answer passing test as array is not fine for some reasons,
The following serializes your two form elements' values into id=value&id2=value2 using jQuery.param():
function buildQuery(){
var $elements = $('#dd, #sel'), //or your selector
result = {};
$elements.each(function(){
if(this.value !== '')
result[this.id] = this.value; //uses id attribute as variable name
});
document.getElementById('log').innerHTML = '?' + $.param(result); //see jQuery.param() docs
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="text" id="dd">
<select name="" id="sel">
<option value=""></option>
<option value="Prepare">Prepare</option>
<option value="Ready">Ready</option>
<option value="Cancel">Cancel</option>
</select>
<button onclick="buildQuery()">Build query</button>
<p id="log">(This element is here just for logging the result)</p>
I will do it like this and then you can add more inputs as you wish..
function buildQuery(){
var result = '?test=';
var getVal = $('input#dd').val();
var getSelectVal = $('select#sel').val();
var resultArray = [getVal, getSelectVal]; // all values array
resultArray = resultArray.filter(v=>v!=''); // filter empty results
if(resultArray.length > 1) {
result += resultArray.join("&test=");
} else {
result += resultArray[0];
}
result = encodeURI(result);
console.log(result);
}
https://jsfiddle.net/3wdecqe9/6/
i want to perform keyup event via textbox id, and all textbox are dynamically created with onclick button event. for this i have to make 20 keyup function. if i use 20 keyup function then my code will become too lengthy and complex. instead of this i want to use a common function for all textbox. can anybody suggest me how to do it..thanks
here is what i am doing to solve it:
<div class="input_fields_wrap">
<button class="add_field_button">Add Booking</button></div>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
var counter = 2;
$(".add_field_button").click(function() {
if (counter > 10) {
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<div id="target"><label>Textbox #' + counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="firsttextbox' + counter + '" value="" > <input type="text" name="textbox' + counter +
'" id="secondtextbox' + counter + '" value="" > Remove<input type="text" id="box' + counter + '" value="">sum</div>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
function check(a, b) {
var first = a;
var second = b;
var temp = temp;
var novalue = "";
result = parseInt(first) + parseInt(second);
if (!isNaN(result)) {
return result;
} else {
return novalue;
}
}
$(this).on("keyup", "#firsttextbox2", function(e) {
e.preventDefault();
var a = document.getElementById('firsttextbox2').value;
var b = document.getElementById('secondtextbox2').value;
var number = 2;
result = check(a, b);
document.getElementById('box2').value = result;
});
$(this).on("keyup", "#firsttextbox3", function(e) {
var number = 3;
e.preventDefault();
var a = document.getElementById('firsttextbox3').value;
var b = document.getElementById('secondtextbox3').value;
result = check(a, b);
document.getElementById('box3').value = result;
});
$(this).on("keyup", "#firsttextbox4", function(e) {
var number = 4;
e.preventDefault();
var a = document.getElementById('firsttextbox4').value;
var b = document.getElementById('secondtextbox4').value;
result = check(a, b);
final = document.getElementById('box4').value = result;
});
$(this).on("keyup", "#secondtextbox2", function(e) {
e.preventDefault();
var a = document.getElementById('firsttextbox2').value;
var b = document.getElementById('secondtextbox2').value;
result = check(a, b);
document.getElementById('box2').value = result;
});
$(this).on("keyup", "#secondtextbox3", function(e) {
e.preventDefault();
var a = document.getElementById('firsttextbox3').value;
var b = document.getElementById('secondtextbox3').value;
result = check(a, b);
document.getElementById('box3').value = result;
});
$(this).on("keyup", "#secondtextbox4", function(e) {
e.preventDefault();
var a = document.getElementById('firsttextbox4').value;
var b = document.getElementById('secondtextbox4').value;
result = check(a, b);
document.getElementById('box4').value = result;
});
$(this).on("click", "#remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('#target').remove();
counter--;
});
});
</script>
See the snippet below to see how you can make this implementation more modular and useable. The trick is to think: what do I want to do? I want to be able to add multiple inputs and add their value, printing the result in another input.
It comes down to using classes - since we are going to use the same kind of thing for every row. Then apply something that works for all classes. No IDs whatsoever! You can even use the name property of the input that contains the value you want to save. Using the [] in that property will even pass you back a nice array when POSTING!
I know this looks like a daunting lot, but remove my comments and the number of lines reduces dramatically and this kind of code is almost infinitely extendable and reusable.
But have a look, this works and its simple and - most of all - it's DRY (don't repeat yourself 0 once you do, re-evaluate as there should be a better way!)!
Update
You could also use a <ol>as a wrapper and then add an <li> to this every time, so you get automatic counting of boxes in the front end without any effort from your end! Actually, thats so nice for this that I have changed my implementation.
var add = $('#add_boxes');
var all = $('#boxes');
var amountOfInputs = 2;
var maximumBoxes = 10;
add.click(function(event){
// create a limit
if($(".box").length >= maximumBoxes){
alert("You cannot have more than 10 boxes!");
return;
}
var listItem = $('<li class="box"></li>');
// we will add 2 boxes here, but we can modify this in the amountOfBoxes value
for(var i = 0; i < amountOfInputs; i++){
listItem.append('<input type="text" class="input" />');
}
listItem.append('<input type="text" class="output" name="value" />');
// Lets add a link to remove this group as well, with a removeGroup class
listItem.append('<input type="button" value="Remove" class="removeGroup" />')
listItem.appendTo(all);
});
// This will tie in ANY input you add to the page. I have added them with the class `input`, but you can use any class you want, as long as you target it correctly.
$(document).on("keyup", "input.input", function(event){
// Get the group
var group = $(this).parent();
// Get the children (all that arent the .output input)
var children = group.children("input:not(.output)");
// Get the input where you want to print the output
var output = group.children(".output");
// Set a value
var value = 0;
// Here we will run through every input and add its value
children.each(function(){
// Add the value of every box. If parseInt fails, add 0.
value += parseInt(this.value) || 0;
});
// Print the output value
output.val(value);
});
// Lets implement your remove field option by removing the groups parent div on click
$(document).on("click", ".removeGroup", function(event){
event.preventDefault();
$(this).parent(".box").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<ol id="boxes">
</ol>
<input type="button" value="Add a row" id="add_boxes" />
You can target all your textboxes, present or future, whatever their number, with a simple function like this :
$(document).on("keyup", "input[type=text]", function(){
var $textbox = $(this);
console.log($textbox.val());
})
$("button").click(function(){
$("#container").append('<input type="text" /><br>');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<input type="text" /><br>
<input type="text" /><br>
<input type="text" /><br>
</div>
<button>Create one more</button>
You don't need complicated generated IDs, not necessarily a class (except if you have other input[type=text] you don't want to conflict with). And you don't need to duplicate your code and write 20 times the same function. Ever. If you're duplicating code, you're doing wrong.
Add classes "a" and "b" to the textboxes and "box" to the box. Then add data-idx attribute with the index (unused!?). Finally register the event handlers:
$('.a').on('keyup', function(e){
e.preventDefault();
var $this = $(this)
var $p = $this.parent()
var a= this.value;
var b= $p.find('.b').val()
var number =$this.data('idx') //unused!?
var result = check(a,b)
$p.find('.box').val(result)
})
$('.b').on('keyup', function(e){
e.preventDefault();
var $this = $(this)
var $p = $this.parent()
var a= $p.find('.a').val()
var b= this.value
var result = check(a,b)
$p.find('.box').val(result)
})
Or a general one:
$('.a,.b').on('keyup', function(e){
e.preventDefault();
var $p = $(this).parent()
var a= $p.find('.a').val()
var b= $p.find('.b').val()
var result = check(a,b)
$p.find('.box').val(result)
})
You can assign a class to all textboxes on which you want to perform keyup event and than using this class you can attach the event on elements which have that class. Here is an example
var html="";
for (var i = 0; i < 20; i++)
{
html += "<input type='text' id='txt" + i + "' class='someClass' />";
}
$("#testDiv").html(html);
Attach keyup event on elements which have class someClass.
$(".someClass").keyup(function () {
alert($(this).attr("id"));
});
A little helper to combine with your favorite answer:
var uid = function () {
var id = 0;
return function () {
return ++id;
};
}();
Usage:
uid(); // 1
uid(); // 2
uid(); // 3
Providing a code-snippet which may give you some hint:
$(".add_field_button").click(function ()
{
if (counter > 10)
{
alert("Only 10 textboxes allow");
return false;
}
var txtBoxDiv = $("<div id='TextBoxDiv"+counter+"' style='float:left;width:10%; position:relative; margin-left:5px;' align='center'></div>");
//creating the risk weight
var txtBox1 = $('<input />',
{
'id' : 'fst_textbox_' + counter,
'name' : 'textbox'+counter,
'type' : 'text',
'class' : 'input_field',
'onClick' : 'txtBoxFun(this,'+counter+')'
});
var txtBox2 = $('<input />',
{
'id' : 'sec_textbox_' + counter,
'name' : 'textbox'+counter,
'type' : 'text',
'class' : 'input_field',
'onClick' : 'txtBoxFun(this,'+counter+')'
});
var txtBox3 = $('<input />',
{
'id' : 'sum_textbox_' + counter,
'name' : 'textbox'+counter,
'type' : 'text',
'class' : 'input_field',
});
$(txtBoxDiv).append(txtBox1).append(txtBox2);
$(txtBoxDiv).append(txtBox3);
});
function txtBoxFun(obj, count)
{
var idGet = $(obj).attr('id');
var idArr = new Array();
idArr = idGet.split("_");
if(idArr[0] == "fst")
{
var sumTxt = parseInt(parseInt($(obj).val()) + parseInt($("#sec_textbox_"+count).val()));
}
else if(idArr[0] == "sec")
{
var sumTxt = parseInt(parseInt($(obj).val()) + parseInt($("#fst_textbox_"+count).val()));
}
$("#sum_textbox_"+count).val(sumTxt);
}
I'm having trouble filtering resulting div's with jQuery via two different inputs. Users can decide to filter by office, specialty or both office and specialty. The filtering is set from data attributes on the div that correspond to the select inputs values.
<div>
<label for="officeSearch">Search by office:</label>
<select name="Office Search" id="officeSearch">
<option value="all"></option>
<option value="communication">Communication</option>
<option value="internal medicine">Internal Medicine</option>
</select>
</div>
<div>
<label for="specialtySearch">Search by specialty:</label>
<select name="Specialty Search" id="specialtySearch">
<option value="all"></option>
<option value="Bone Cancer">Bone Cancer</option>
<option value="Breast Cancer">Breast Cancer</option>
<option value="Oral Cancer">Oral Cancer</option>
</select>
</div>
<div class="module-sm profile" data-office="communication" data-specialty="Oral Cancer">
<p>Person A</p>
</div>
<div class="module-sm profile" data-office="communication" data-specialty="Breast Cancer">
<p>Person B</p>
</div>
<div class="module-sm profile" data-office="internal medicine" data-specialty="Bone Cancer">
<p>Person C</p>
</div>
Here's the jQuery I'm using that fires on change of the selects:
$(document).ready(function() {
$("#officeSearch").on('change', function(){
var selectedOffice = $('#officeSearch').val();
var selectedSpecialty = $('#specialtySearch').val();
var person = $('#filterList .profile').not('.out');
var allPersons = $('#filterList .profile');
var allPersonsOffice = $('#filterList .profile').data('office');
var allPersonsOut = $('#filterList .profile.out');
var office = $('.profile[data-office="' + selectedOffice +'"]');
alert(''+ selectedOffice + ' ' + selectedSpecialty +'');
if (selectedOffice == 'all' && selectedSpecialty == 'all'){
$(allPersons).removeClass('out').fadeIn(500);
}
else {
$(person).not(office).addClass('out').fadeOut(500);
office.removeClass('out').fadeIn(500);
}
});
$("#specialtySearch").on('change', function(){
var selectedOffice = $('#officeSearch').val();
var selectedSpecialty = $('#specialtySearch').val();
var person = $('#filterList .profile').not('.out');
var allPersons = $('#filterList .profile');
var allPersonsOffice = $('#filterList .profile').data('office');
var allPersonsOut = $('#filterList .profile.out');
var specialty = $('.profile[data-specialty="' + selectedSpecialty +'"]');
alert(''+ selectedOffice + ' ' + selectedSpecialty +'');
if (selectedOffice == 'all' && selectedSpecialty == 'all'){
$(allPersons).removeClass('out').fadeIn(500);
}
else {
$(person).not(specialty).addClass('out').fadeOut(500);
specialty.removeClass('out').fadeIn(500);
}
});
});
If it helps, I've made a codepen to demonstrate what I'm trying to do and where I'm at so far.
I've done some searching and have been scratching my head on how to get this working for weeks. Any help making this code more concise or examples to how others have solved this problem are greatly appreciated!
Call a single update from either selection changing.
Create a filter based on the selections (appended).
Hide the ones not in the matches
show the matches.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/2u7NY/
$(document).ready(function () {
var onChange = function () {
var selectedOffice = $('#officeSearch').val();
var selectedSpecialty = $('#specialtySearch').val();
var filter = "#filterList .profile";
var allPersons = $(filter);
if (selectedOffice != "all")
{
filter += '[data-office="' + selectedOffice + '"]'
}
if (selectedSpecialty != "all")
{
filter += '[data-specialty="' + selectedSpecialty + '"]'
}
var $matching = allPersons.filter(filter);
$(allPersons).not($matching).removeClass('out').fadeOut(500);
$matching.removeClass('out').fadeIn(500);
}
$("#officeSearch, #specialtySearch").on('change', onChange );
});
Update: http://jsfiddle.net/TrueBlueAussie/2u7NY/2/
The filter can be made slightly more efficient as "#filterList .profile" is not needed to filter allPersons based on attributes.
I also removed the function variable and placed the function inline on the change event.
$(document).ready(function () {
$("#officeSearch, #specialtySearch").on('change',
function () {
var selectedOffice = $('#officeSearch').val();
var selectedSpecialty = $('#specialtySearch').val();
var allPersons = $("#filterList .profile");
var filter = "";
if (selectedOffice != "all") {
filter = '[data-office="' + selectedOffice + '"]'
}
if (selectedSpecialty != "all") {
filter += '[data-specialty="' + selectedSpecialty + '"]'
}
var $matching = allPersons.filter(filter);
$(allPersons).not($matching).removeClass('out').fadeOut(500);
$matching.removeClass('out').fadeIn(500);
});
});
OK. Try something like this....
var match = function(office, specialty, profile) {
var show = ((office == 'all' || office == $(profile).data('office')) &&
(specialty == 'all' || specialty == $(profile).data('specialty')));
if (show && !$(profile).is(':visible')) {
$(profile).fadeIn();
}
if (!show && $(profile).is(':visible')) {
$(profile).fadeOut();
}
}
var filter = function() {
var selectedOffice = $('#officeSearch').val();
var selectedSpecialty = $('#specialtySearch').val();
$.each($('#filterList .profile'), function(i, profile) {
match(selectedOffice, selectedSpecialty, profile);
});
};
$("#officeSearch").on('change', function(){
filter();
});
$("#specialtySearch").on('change', function(){
filter();
});
working fiddle here.... http://jsfiddle.net/6Q8FF/