Filter an Object - javascript

I'm hoping someone will point me in the right direction or give me an example. I'm trying to filter through this multidimensional json object using a form with four filter options (see below).
After the user makes their selections and hits the submit button the results of that product or service's details are displayed on the page (ie...link to that product, content of that product), there can also be more than one product or service to display based on the search filter. Can someone please help me out?
Here is my object:
var data = {
"Product":{"url":["http://www.google.com"],"mode":["gyro"],"modeOptions":["drop-controlled-descent","seated-wireline-steering","slickline-memory","surface-readout-ms","wireline-orientation"],"diameter":{"usa":"1.75","intl":"44.5mm"},"accuracy":{"usa":"0.5 deg","intl":"0.5 deg"},"temp":{"usa":"400F","intl":"204C"},"speed":{"usa":"250 ft\/min","intl":"76.2m\/min"}},
"Service":{"url":["http://www.google.com"],"mode":["gyro"],"modeOptions":["drop-controlled-descent","seated-wireline-steering","slickline-memory","surface-readout-ms","wireline-orientation"],"diameter":{"usa":"(2.2)","intl":"(55.9mm)"},"accuracy":{"usa":"0.15 deg","intl":"0.15 deg"},"temp":{"usa":"(400F)","intl":"(204C)"},"speed":{"usa":"600 ft\/min","intl":"182.9m\/min"}}
};
Her is my html form:
<form name="searchForm" id="searchForm">
<select name="diameter">
<option value="" selected="">Select One</option>
<option value="1.2">1.2</option>
<option value="1.75">1.75</option>
<option value="2.2">2.2</option>
</select>
<select name="accuracy">
<option value="" selected="">Select One</option>
<option value="0.15 deg">0.15</option>
<option value="0.5 deg">0.5</option>
<option value="1 deg">1</option>
<option value="2.5 deg">2.5</option>
</select>
<select name="temp">
<option value="" selected="">Select One</option>
<option value="257F">257F</option>
<option value="300F">300F</option>
<option value="400F">400F</option>
</select>
<select name="modeOptions">
<option value="" selected="">Select One</option>
<option value="surface-readout-ms">Surface Readout/MS</option>
<option value="wireline-orientation">Wireline Orientation</option>
<option value="memory-orientation">Memory Orientation</option>
<option value="slickline-memory">Slickline memory</option>
<option value="drop-controlled-descent">Drop – Controlled Descent</option>
<option value="drop–freefall-descent">Drop – Freefall Descent</option>
<option value="seated-wireline-steering">Seated Wireline Steering</option>
</select>
<input type="submit" value="submit"/>
</form>

Get TaffyDB. It is made for these sorts of things.

Try something like
var $form = $('#searchForm'),
$diameter = $form.find('select[name="diameter"]'),
$accuracy = $form.find('select[name="accuracy"]'),
$temp = $form.find('select[name="temp"]'),
$modeOptions = $form.find('select[name="modeOptions"]');
$('#searchForm').submit(function (e) {
e.preventDefault();
var diameter = $diameter.val(),
accuracy = $accuracy.val(),
temp = $temp.val(),
modeOptions = $modeOptions.val();
var selected = $.map(data, function (obj) {
return (!diameter || diameter == obj.diameter.usa) && (!accuracy || accuracy == obj.accuracy.usa) && (!temp || temp == obj.temp.usa) && (!modeOptions || $.inArray(modeOptions, obj.modeOptions) > -1) ? obj : undefined
});
//print result
console.log('found:', selected);
$('#result').html($.map(selected, function (val) {
return '<p>' + JSON.stringify(val) + '</p>'
}))
})
Demo: Fiddle

Related

Reset select dropdown base on hierarchy

<script>
function refresh()
{
document.forms[0].submit();
}
</script>
<select name = "firstoption" onChange ="refresh()"></select>
<option value = "">default option</option>
<option value = "1">1</option>
if($_POST['firstoption]!= "")
<select name = "secondoption" onChange ="refresh()"></select>
<option value = "">default option</option>
<option value = "2">2</option>
if($_POST['secondoption]!= "" && $_POST['firstoption]!= "")
<select name = "thirdoption" onChange ="refresh()"></select>
<option value = "">default option</option>
<option value = "3">3</option>
if($_POST['thirdoption]!= "" && $_POST['secondoption]!= "" && $_POST['firstoption]!= "")
<select name = "fourthoption" onChange ="refresh()"></select>
<option value = "">default option</option>
<option value = "4">4</option>
Hi,
I have 6 static dropdowns. (something like this for some reason I am currently having laptop problems so I could not copy and paste the code where I wrote down generic values)
DELETED (NO LONGER AN ISSUE FIX ON MY OWN)
Basically, I need 6 dropdown (all values kept after it s refresh) and when a dropdown values changes all of the dropdowns below it get reset.
EDIT:
I am looking for code to reset select option back to the default select option (base on hierarchy). Once an select option above it gets change. so if select "2" gets change select 3,4,5 6 value should change to default option. If select "4" gets change select 5,6 would be change to default option etc.
I do not want ajax or jQuery. I am looking for a solution with php, javascript, or html. I think the way to approach it is by comparing the previous and new index number of the select option being change
Note the code I provide is sudo code I can not copy and paste code due to current laptop state.
So the answer does not need to use my code.
I just want a php/javascript/html code that has multiple select options (4-6 select with 2 option in each) the other drop down will be disable until the select above get a value. SO option 2-6 will be disable until select 1 is pick then option 3-6 will be disable until a value for option 2 is pick).
If he user changes select 1 option will select 2-6 already have a value. Select 2-6 automatically switches to default option value. and option 3-6 is now disable until user select option for select 2
Also stack overflow does not allow bounty to be given until 24 hours so I can not give bounty until tomorrow around this time.
Some suggestions to facilitate the solution:
Give all your drop-down lists the same class attribute.
Use just one change event handler on a container element (or the whole document), and let the handler find out which select value was changed.
Create a function that, given an index, will clear all dropdowns from that index onwards, and will disable all of those, except the first one (at that index).
Call this function in the event handler, and also at page load, so to initialise the enabled/disabled status of those dropdowns.
Below is how that could work. I removed all HTML that is not necessary for this solution, but of course you may need more HTML attributes for other purposes:
const dropDowns = Array.from(document.querySelectorAll(".option"));
function reset(i) {
for (let other of dropDowns.slice(i)) {
other.selectedIndex = 0;
other.disabled = other !== dropDowns[i];
}
}
document.addEventListener("change", function (e) {
let i = dropDowns.indexOf(e.target);
if (i < 0) return;
// only allow input in next one if current value is not default:
reset(i+(dropDowns[i].selectedIndex > 0));
});
reset(0); // on page load, disable all except first one
<select class="option">
<option>default option</option>
<option>1</option>
<option>2</option>
</select>
<select class="option">
<option>default option</option>
<option>A</option>
<option>B</option>
</select>
<select class="option">
<option>default option</option>
<option>x</option>
<option>y</option>
</select>
<select class="option">
<option>default option</option>
<option>alpha</option>
<option>beta</option>
</select>
More on the following:
reset(i+(dropDowns[i].selectedIndex > 0));
dropDowns[i].selectedIndex will be 0 when the first entry (default) is selected, and a strictly positive number when any other entry is selected. So with > 0 this actually gives true for when a non-default entry is selected, false otherwise.
Now we want to make the next dropdown available only when the current one has a non-default entry selected, i.e. when this > 0 expression is true. By involving that expression in a + operation, we convert that boolean value to a number (0 for false, 1 for true). And so, that whole expression is either i+0 or i+1, depending on whether the current dropdown has the default value selected or not.
By providing that index (i or i+1) to the reset function, we make sure that the effect of selecting the default value or not is just like is needed.
There are many ways to accomplish this. The below should work with any number of select boxes. The code is commented to explain the steps.
<form accept="#" method="POST" id="myform">
<div>
<select name="firstoption">
<option value="">default option</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
<div>
<select name="secondoption" disabled>
<option value="">default option</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<div>
<select name="thirdoption" disabled>
<option value="">default option</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
<div>
<select name="fourthoption" disabled>
<option value="">default option</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
<div>
<input type="submit" value="Submit">
</div>
</form>
<script>
//get references to the DOM elements we need
var form = document.getElementById('myform');
var selects = form.querySelectorAll('select');
//register event listeners for each of the select boxes so we know when the value changes
for( let i=0; i<selects.length; i++ ) {
selects[i].addEventListener('change', function(evt) {
//select box "i" has changed
//since the value changed, reset other boxes after to the default value and disable
for( let i2 = (i+1); i2 < selects.length; i2++ ) {
selects[i2].value = "";
selects[i2].disabled = true;
}
//if the value of the changed select box is not the default, enable the next one
if( selects[i].value !== "" && selects[i+1] ) {
selects[i+1].disabled = false;
}
});
}
//catch form submission so we can validate the select boxes
form.addEventListener('submit', function(evt) {
//ensure we have all values before submitting
try {
for( let i=0; i<selects.length; i++ ) {
if( selects[i].value === "" ) {
alert(`Please select an option for box number ${i+1}`);
throw 0;
}
}
}catch(e) {
//error, prevent submission
evt.preventDefault();
return false;
}
//all good, submit
return true;
});
</script>
Load all select with document.querySelectorAll() using an expresion to get elements wich name ends with option, that's what $ do before the equal sign.
Then, in your function, check every select if one is empty, set to default value the next.
// Get all items wich name ends with "option"
let selects = document.querySelectorAll('[name$="option"]');
function refresh() {
// Loop into all selects
selects.forEach((item, index) => {
// Don't do this on last one
if(item.value == '' && index < selects.length - 2)
selects[index + 1].value = ""
});
// Check here the sixthoption value if you need it not empty to submit the form
}
<select name="firstoption" onchange="refresh()">
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="secondoption" onchange="refresh()">
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="thirdoption" onchange="refresh()">
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="fourthoption" onchange="refresh()">
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="fifthoption" onchange="refresh()">
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="sixthoption" onchange="refresh()">
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
Another way using if's:
// Get all items wich name ends with "option"
let selects = document.querySelectorAll('[name$="option"]');
function refresh() {
// 0 = firstoption, 1 = secondoption... 5 = sixthoption
// If value is empty string, set default value for next element too
if(selects[0].value == "") selects[1].value = '';
if(selects[1].value == "") selects[2].value = '';
if(selects[2].value == "") selects[3].value = '';
if(selects[3].value == "") selects[4].value = '';
if(selects[4].value == "") selects[5].value = '';
}
<select name="firstoption" onchange="refresh()">
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="secondoption" onchange="refresh()">
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="thirdoption" onchange="refresh()">
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="fourthoption" onchange="refresh()">
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="fifthoption" onchange="refresh()">
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="sixthoption" onchange="refresh()">
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
I assume that you not necessarily want to post upon each select change. Instead, let's see this approach:
<select class="fancy-select" id="s-1" name = "firstoption">
<option value = "">default option</option>
<option value = "1">1</option>
</select>
<select class="fancy-select" id="s-2" name = "secondoption">
<option value = "">default option</option>
<option value = "2">2</option>
</select>
<select class="fancy-select" id="s-3" name = "thirdoption">
<option value = "">default option</option>
<option value = "3">3</option>
</select>
<select class="fancy-select" id="s-4" name = "fourthoption">
<option value = "">default option</option>
<option value = "4">4</option>
</select>
<script type="text/javascript">
function myHandler() {
if (!this.value) {
var currentID = parseInt(this.id.substring(2));
for (let i = currentID; i < fancySelects.length; i++) fancySelects[i].value = "";
}
}
var fancySelects = document.querySelectorAll(".fancy-select");
for (let item of fancySelects) item.addEventListener("change", myHandler);
</script>
Fiddle: https://jsfiddle.net/0dfxytpc/1/
You see that despite the claims about Vue JS and jQuery making it easier, Javascript in itself is easy. If you know how to program in Javascript. My understanding is that once default is chosen you intend the subsequent items to be defaulted. If that's not the aim, then I misunderstood the goal.
Now, you can notice that this is pretty repetitive, we can surely make it nicer to appear. Let's generate the select tags on the server:
<?php
for ($index = 1; $index <= 4; $index++) {
?>
<select class="fancy-select" id="s-<?php echo $index; ?>">
<option value="">default option</option>
<option value="<?php echo $index; ?>"><?php echo $index; ?></option>
</select>
<?php
}
?>
<script type="text/javascript">
function myHandler() {
if (!this.value) {
var currentID = parseInt(this.id.substring(2));
for (let i = currentID; i < fancySelects.length; i++) fancySelects[i].value = "";
}
}
var fancySelects = document.querySelectorAll(".fancy-select");
for (let item of fancySelects) item.addEventListener("change", myHandler);
</script>
The code is small and easy to understand. Vue JS and jQuery would just overcomplicate this, they would add dependencies that you do not need. There is a trend of programmers who are less capable to work in Javascript and will argue that doing stuff is easier in Vue JS or jQuery. You can actually measure the power of that trend with the number of downvotes I get. I do not speak against the use of jQuery or Vue JS in general, although, I am not their fan in particular, but when you learn Javascript you should avoid getting dependant of a framework right from the start. As you get comfortable working with Javascript you might decide that Vue JS and jQuery is good for you. I would totally respect that decision, but do not make that decision before you learn Javascript properly.
You could try this:
const selects = document.querySelectorAll(".myoption");
const submit = document.getElementById("mysubmit");
selects.forEach((select, id) => select.addEventListener("change",() => {
const last = id === selects.length - 1;
if(! last) {
selects[id + 1].removeAttribute("disabled");
selects[id + 1].value = "";
}
for(let i = id + (select.selectedIndex ? 2 : 1); i < selects.length; ++i) {
selects[i].value = "";
selects[i].setAttribute("disabled", true);
}
submit.setAttribute("disabled", true);
if(last && select.selectedIndex) submit.removeAttribute("disabled");
}));
<select class="myoption">
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select class="myoption" disabled>
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select class="myoption" disabled>
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select class="myoption" disabled>
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select class="myoption" disabled>
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select class="myoption" disabled>
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="submit" id="mysubmit" value="submit" disabled>
Hope this helps.
As already a lot of ways are mentioned, here is what I came up with.
Assign every select a data-name attribute.
Every select would also have a class attribute. This class attribute would possess all previous parents' data-names.
When a particular select value changes, you get the data-name of it and use querySelectorAll to get all those elements who have this data-name in their class and set their values and disability accordingly.
var selects = document.querySelectorAll('select');
selects.forEach(function(select_dropdown){
select_dropdown.addEventListener('change',function(){
var kids = document.querySelectorAll('.' + this.getAttribute('data-name'));
var parent_value = this.value;
kids.forEach(function(child,index){
child.value = "";
if(parent_value == "" || index > 0){
child.setAttribute('disabled','disabled');
}else{
child.removeAttribute('disabled');
}
});
});
});
<select class="" data-name="select_1">
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select data-name="select_2" class="select_1" disabled>
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select data-name="select_3" class="select_1 select_2" disabled>
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select data-name="select_4" class="select_1 select_2 select_3" disabled>
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select data-name="select_5" class="select_1 select_2 select_3 select_4" disabled>
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select data-name="select_6" class="select_1 select_2 select_3 select_4 select_5" disabled>
<option value="">Default</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
You can add data attribute for each dropdown, that way you can track index of that dropdown, so on change all higher than index apply action..
when option is selected, reset rest of the boxes that are in order.
If previus select box not default, enable next box else disable it
var selects = document.getElementsByClassName("select")
for(var i = 0; i < selects.length; i++){
selects[i].addEventListener('change', function(e){
for(var x = 0; x < selects.length; x++){
//On select, reset selectboxes that commes after
if(Number(e.target.dataset.columns) < x){
selects[x][0].selected = true;
}
//If previus select box not default, enable next box
if(x > 0 && selects[x -1][0].selected != true){
selects[x].disabled = false;
}
//else dissable next box..
else if(x > 0 && selects[x -1][0].selected == true){
selects[x].disabled= true;
}
}
})
}
<select data-columns="0" class="select">
<option value = "">default option</option>
<option value = "1">1</option>
<option value = "1">1</option>
</select>
<select data-columns="1" disabled class="select">
<option value = "">default option</option>
<option value = "2">2</option>
<option value = "1">1</option>
</select>
<select data-columns="2" disabled class="select">
<option value = "">default option</option>
<option value = "3">3</option>
<option value = "1">1</option>
</select>
<select data-columns="3" disabled class="select">
<option value = "">default option</option>
<option value = "4">4</option>
<option value = "1">1</option>
</select>

how i can populate my search fields based on the parameters inside the URL

I am working on an asp.net web application and i have the following code to build a search fields section, which build the URL parameters based on the users' input:-
<script type="text/javascript">
$(document).ready(function(){
$('#button').click(function(e) {
var count=1;
var s="";
var inputvalue = $("#journal").val();
var inputvalue2 = $("#keywords").val();
var inputvalue3 = $("#datepub").val();
var inputvalue4 = $("#title").val();
var inputvalue5 = $("#localcurrency").val();
var inputvalue6 = $("#locations").val();
var inputvalue7 = $("#dropdown1").val();
var inputvalue8 = $("#dropdown2").val();
if(inputvalue!=null && inputvalue!="")
{
s = s+ "FilterField"+count+"=Journal&FilterValue"+count+"="+inputvalue+"&";
count++;
}
if(inputvalue2!=null && inputvalue2!="")
{
s = s+ "FilterField"+count+"=KeyWords&FilterValue"+count+"="+inputvalue2+"&";
count++;
}
if(inputvalue3!=null && inputvalue3!="")
{
s = s+ "FilterField"+count+"=datepub&FilterValue"+count+"="+inputvalue3+"&";
count++;
}
if(inputvalue4!=null && inputvalue4!="")
{
s = s+ "FilterField"+count+"=Title&FilterValue"+count+"="+inputvalue4+"&";
count++;
}
if(inputvalue5!=null && inputvalue5!="")
{
s = s+ "FilterField"+count+"=localcurrency&FilterValue"+count+"="+inputvalue5+"&";
count++;
}
if(inputvalue6!=null && inputvalue6!="")
{
s = s+ "FilterField"+count+"=locations&FilterValue"+count+"="+inputvalue6+"&";
count++;
}
if(inputvalue7!=null && inputvalue7!="")
{
s = s+ "FilterField"+count+"=dropdown1&FilterValue"+count+"="+inputvalue7+"&";
count++;
}
if(inputvalue8!=null && inputvalue8!="")
{
s = s+ "FilterField"+count+"=dropdown2&FilterValue"+count+"="+inputvalue8+"&";
count++;
}
window.location.replace("/teamsites/Bib%20Test/Forms/search.aspx?"+s);
});
});
</script>
Journal <input type="text" id="journal">
keywords <input type="text" id="keywords">
<select id="datepub">
<option value=""></option>
<option value="1950">1950</option>
<option value="2010">2010</option>
<option value="2017">2017</option>
<option value="audi">Audi</option>
</select>
title
<select id="title">
<option value=""></option>
<option value="TestDoc">test doc</option>
<option value="t">t</option>
</select>
localcurrency
<select id="localcurrency">
<option value=""></option>
<option value="USD">USD</option>
</select>
locations
<select id="locations">
<option value=""></option>
<option value="US">US</option>
<option value="UK">UK</option>
</select>
dropdown1
<select id="dropdown1">
<option value=""></option>
<option value="a">a</option>
<option value="b">b</option>
</select>
dropdown2
<select id="dropdown2">
<option value=""></option>
<option value="aa">aa</option>
<option value="bb">bb</option>
<option value="cc">cc</option>
<option value="dd">dd</option>
</select>
<button type="button" id="button">search</button>
Where when the user clicks on the search button, the user will be redirected to the /teamsites/Bib%20Test/Forms/search.aspxpage with the filter parameters inside the url, which will show the related records according to the parameters being passed.
now the filtering is working well.. but the problem i am facing is that after i redirect the user to this page /teamsites/Bib%20Test/Forms/search.aspx the filter fields values (such as the local currency, locations, title, etc..) will cleared out.
so can i using JavaScript to assign the filer fields their original values ? i mean can i extract the fields' values from the URL and assign it to them ? so after the user is being redirected to the /teamsites/Bib%20Test/Forms/search.aspx they can still see the filtering fields populated with the filtering values they have entered?
You can accomplish this by doing the following:
Parse the current page's query string to separate out its query parameters
Process those to match up filter field names with their values
Use $('#' + fieldName).val(value) to set the field values in the page
Below, as a demonstration, I'm passing in a hardcoded query string '?FilterField0=locations&FilterValue0=US&FilterField1=dropdown1&FilterValue1=b' into the populateSearchFields() function. In practice, you would use the three functions here, unmodified, but instead of that hardcoded value, pass in window.location.search.
// input: '?a=b&b=c&e=f'
// output: { a: 'b', b: 'c', e: 'f' }
function buildParameterMap(queryString) {
// ignore the ? at the beginning and split the query string into
// pieces separated by &
var pairs = queryString.replace(/^\?/, '').split('&');
var map = {};
pairs.forEach(function(pair) {
// further split each piece to the left and right of the =
// ignore pairs that are empty strings
if (pair) {
var sides = pair.split('=');
map[sides[0]] = decodeURIComponent(sides[1]);
}
});
return map;
}
// input: { FilterField0: 'Name', FilterValue0: 'Fred',
// FilterField1: 'age', FilterValue1: '30' }
// output: { name: 'Fred', age: '30' }
function buildFilterFieldMap(parameterMap) {
var maxFieldCount = 15;
var map = {};
for (var i = 0; i < maxFieldCount; i += 1) {
var filterFieldName = parameterMap['FilterField' + i];
if (filterFieldName) {
map[filterFieldName.toLowerCase()] = parameterMap['FilterValue' + i];
}
}
return map;
}
function populateSearchFields(queryString) {
// build a map from URL query string parameter -> value
var parameterMap = buildParameterMap(queryString);
// build a map from search field name -> value
var filterFieldMap = buildFilterFieldMap(parameterMap);
Object.keys(filterFieldMap).forEach(function(field) {
$('#' + field).val(filterFieldMap[field]);
});
}
populateSearchFields('?FilterField0=locations&FilterValue0=US&FilterField1=dropdown1&FilterValue1=b');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
Journal <input type="text" id="journal"> keywords <input type="text" id="keywords">
<select id="datepub">
<option value=""></option>
<option value="1950">1950</option>
<option value="2010">2010</option>
<option value="2017">2017</option>
<option value="audi">Audi</option>
</select> title
<select id="title">
<option value=""></option>
<option value="TestDoc">test doc</option>
<option value="t">t</option>
</select> localcurrency
<select id="localcurrency">
<option value=""></option>
<option value="USD">USD</option>
</select> locations
<select id="locations">
<option value=""></option>
<option value="US">US</option>
<option value="UK">UK</option>
</select> dropdown1
<select id="dropdown1">
<option value=""></option>
<option value="a">a</option>
<option value="b">b</option>
</select> dropdown2
<select id="dropdown2">
<option value=""></option>
<option value="aa">aa</option>
<option value="bb">bb</option>
<option value="cc">cc</option>
<option value="dd">dd</option>
</select>
<button type="button" id="button">search</button>
You want to send get request from one page to another. Do something like this:
Part I: send search request in the query string.
$(document).ready(function(){
$('#button').click(function(e) {
var count=1; //out of use
var s = []; //""; //empty array, not empty string
var inputvalue = $("#journal").val();
var inputvalue2 = $("#keywords").val();
var inputvalue3 = $("#datepub").val();
var inputvalue4 = $("#title").val();
var inputvalue5 = $("#localcurrency").val();
var inputvalue6 = $("#locations").val();
var inputvalue7 = $("#dropdown1").val();
var inputvalue8 = $("#dropdown2").val();
if(inputvalue) // !=null && inputvalue!="") //it is redundant. null and empty string are **falsey**
{
s.push('journal='+inputvalue);
//or if you wish to keep your existing format (not recommended because it would produce problems on the search page)
//s.push("FilterField"+count+"=Journal&FilterValue"+count+"="+inputvalue);
//count++;
}
if(inputvalue2) //!=null && inputvalue2!="")
{
s.push('keywords='+inputvalue2);
//for existing format see previous comment
//s = s+ "FilterField"+count+"=KeyWords&FilterValue"+count+"="+inputvalue2+"&";
//count++;
}
/*
//same for other vars
if(inputvalue3!=null && inputvalue3!="")
{
s = s+ "FilterField"+count+"=datepub&FilterValue"+count+"="+inputvalue3+"&";
count++;
}
if(inputvalue4!=null && inputvalue4!="")
{
s = s+ "FilterField"+count+"=Title&FilterValue"+count+"="+inputvalue4+"&";
count++;
}
if(inputvalue5!=null && inputvalue5!="")
{
s = s+ "FilterField"+count+"=localcurrency&FilterValue"+count+"="+inputvalue5+"&";
count++;
}
if(inputvalue6!=null && inputvalue6!="")
{
s = s+ "FilterField"+count+"=locations&FilterValue"+count+"="+inputvalue6+"&";
count++;
}
if(inputvalue7!=null && inputvalue7!="")
{
s = s+ "FilterField"+count+"=dropdown1&FilterValue"+count+"="+inputvalue7+"&";
count++;
}
if(inputvalue8!=null && inputvalue8!="")
{
s = s+ "FilterField"+count+"=dropdown2&FilterValue"+count+"="+inputvalue8+"&";
count++;
}
*/
window.location.replace("/teamsites/Bib%20Test/Forms/search.aspx?"+s.join('&')); //Use the array here
});
});
Part II: Restore values in the search fields.
$(document).ready(function(){
var query = window.location.search.slice(1); //get ?.... less **?**
var terms = query.split('&'); //get pairs like key=value
for(var i = 0, term; term = terms[i]; ++i){ //loop the search terms
var detail = term.split('='); //journal=some
$('#'+detail[0]).val(detail[1]); //set the value provided fields have the same **id**s
}
});
Update based on comments
It is all about ASP.NET. .aspx page prepends server control IDs with parent IDs like parId$controlId. To avoid it and make the client script work set ClientIDMode="Static" attribute to the controls in search.aspx.
<asp:TextBox ID="keywords" runat="server" ClientIDMode="Static"></asp:TextBox>
Update 2
The OP is about ASP.NET. Generally speaking the result can be achieved without any client-side code.
Part I
<form method="GET" action="/search.aspx">
<input type="text" name="keywords" />
<select name="localcurrency">
<option value="USD">US Dollar</option>
<option value="EUR">Euro</option>
</select>
<!--other fields -->
<input type="submit" value="Search" />
</form>
Part II
<%-- search.aspx --%>
<%# Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["keywords"] != null)
this.keywords.Text = Request.QueryString["keywords"];
if (!string.IsNullOrEmpty(Request.QueryString["localcurrency"]))
localcurrency.SelectedValue = Request.QueryString["localcurrency"];
//other request query strings
// DoSearch();
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="keywords" runat="server"></asp:TextBox>
<asp:DropDownList runat="server" ID="localcurrency">
<asp:ListItem Value="USD">US Dollar</asp:ListItem>
<asp:ListItem Value="EUR">Euro</asp:ListItem>
</asp:DropDownList>
</div>
</form>
</body>
</html>
Use this if you are not concerned about Internet Explorer or Edge.
When your page has loaded, you can read the search params with the help of URL API. Below is the code to get you started.
Note that this solution depends on being the form param's ID to be equal to the lower cased search param's name.
$(document).ready(() => {
// Change the value to window.location.href for working with browser's URL instead
const href = "http://yourhost.com?FilterField0=locations&FilterValue0=US&FilterField1=dropdown1&FilterValue1=b";
// Initializes the URL object with current location
const url = new URL(href);
// This array will contain all the FilterFields
const keys = [];
for (let entry of url.searchParams) {
if (entry[0].startsWith("FilterField")) {
keys.push(entry[0]);
}
}
keys.forEach(field => {
// Extract the index of FilterField
const idx = field[field.length - 1];
// Get the value of FilterField (this gives us the ID of the form field)
const formField = url.searchParams.get(field).toLowerCase();
// Set the value of form field using .val()
$("#" + formField).val(url.searchParams.get('FilterValue' + idx));
});
// Rest of the code here
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Journal <input type="text" id="journal"> keywords <input type="text" id="keywords">
<select id="datepub">
<option value=""></option>
<option value="1950">1950</option>
<option value="2010">2010</option>
<option value="2017">2017</option>
<option value="audi">Audi</option>
</select> title
<select id="title">
<option value=""></option>
<option value="TestDoc">test doc</option>
<option value="t">t</option>
</select> localcurrency
<select id="localcurrency">
<option value=""></option>
<option value="USD">USD</option>
</select> locations
<select id="locations">
<option value=""></option>
<option value="US">US</option>
<option value="UK">UK</option>
</select> dropdown1
<select id="dropdown1">
<option value=""></option>
<option value="a">a</option>
<option value="b">b</option>
</select> dropdown2
<select id="dropdown2">
<option value=""></option>
<option value="aa">aa</option>
<option value="bb">bb</option>
<option value="cc">cc</option>
<option value="dd">dd</option>
</select>
<button type="button" id="button">search</button>

Populate dropdown from array on the basis of multiple dropdown values

Please guide me how can I make this code better.
var employees_json = [
{"id":"1","departments_id":"1","designations_id":"1","employee_types_id":"1","name":"name1"},
{"id":"2","departments_id":"2","designations_id":"2","employee_types_id":"1","name":"name2"},
{"id":"3","departments_id":"3","designations_id":"3","employee_types_id":"2","name":"name3"},
{"id":"4","departments_id":"4","designations_id":"4","employee_types_id":"3","name":"name4"},
{"id":"5","departments_id":"5","designations_id":"5","employee_types_id":"3","name":"name5"}
];
$("._employee_selection").change(function() {
update_employees();
});
function update_employees() {
var departments_id = $('#departments_id').val();
var designations_id = $('#designations_id').val();
var employee_types_id = $('#employee_types_id').val();
options = '<option value="">Select an option</option>';
$.each(employees_json, function(index, val) {
var selection = 0;
if (departments_id == '' || val.departments_id == departments_id) {
selection += 1;
}
if (designations_id == '' || val.designations_id == designations_id) {
selection += 1;
}
if (employee_types_id == '' || val.employee_types_id == employee_types_id) {
selection += 1;
}
if (selection == 3) {
options += `<option value="${val.id}">${val.name}</option>`;
}
});
$("#employees_id").html(options);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<select id="departments_id" class="_employee_selection">
<option value="" selected="selected">Select an option</option>
<option value="1">Administration</option>
<option value="2">Data Entry</option>
<option value="3">Development</option>
<option value="4">Management</option>
<option value="5">Marketing</option>
</select>
<select id="designations_id" class="_employee_selection">
<option value="" selected="selected">Select an option</option>
<option value="1">Administration</option>
<option value="2">Data Entry</option>
<option value="3">Development</option>
<option value="4">Management</option>
<option value="5">Marketing</option>
</select>
<select id="employee_types_id" class="_employee_selection">
<option value="" selected="selected">Select an option</option>
<option value="1">Permanent</option>
<option value="2">contract</option>
<option value="3">Probation</option>
</select>
<select id="employees_id">
</select>
What is a better way to populate a dropdown on the basis of multiple dropdown selections?
This is basically a search filter and I'm not doing an Ajax to fetch data from filtered dropdowns.
I have a json array of employees with their department, designation and type in each element of array.
From the dropdown above selected in any combination, I'm trying to populate the employee list.
The following code is working for me, But I'm hoping for an easy and better way of doing it, which I'm not sure how can be done more efficiently.

Using Javascript to check form elements and enabling/disabling the search button

I need your help,
Using javascript, how could I add some sort of data form validation that would be two-fold:
1st Event, [OnKeyUp] attached to all of the input boxes
2nd Event, [OnChange] attached to all of the select boxes
Typical User Scenarios
If there is any data present in any of the input boxes and no selected option values then { enable the search button } else { keep the search button disabled }
If there are any selected option values who’s option value is not null and no data present in all of then { enable the search button } else { keep the search button disabled }
<!DOCTYPE html>
<html>
<head></head>
<body>
<form id="myform">
Cars
<select id="car">
<option value=""></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br><br>
Fruits
<select id="fruits">
<option value=""></option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="pear">pear</option>
<option value="strawberry">strawberry</option>
<option value="mango">mango</option>
<option value="orange">orange</option>
</select>
<br><br>
Vegetable
<input type="input" id="veggie">
<br><br>
Number
<input type="input" id="number">
<br><br>
<input type="button" value="search" id="search" disabled>
</form>
</body>
</html>
var car=$('#car'); var fruits=$('#fruits');
var veggie=$('#veggie'); var number = $('#number');
$('select').change(function(){
validate();
});
$('input').keyup(function(){
validate();
});
function validate(){
if(($(veggie).val()!='' || $(number).val()!='') &&
$(car).val()=='' && $(fruits).val()==''){
$('#search').prop('disabled',false);
}else if($(veggie).val()=='' && $(number).val()=='' &&
($(car).val()!='' || $(fruits).val()!='')){
$('#search').prop('disabled',false);
}else{
$('#search').prop('disabled',true);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form id="myform">
Cars
<select id="car">
<option value=""></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br><br>
Fruits
<select id="fruits">
<option value=""></option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="pear">pear</option>
<option value="strawberry">strawberry</option>
<option value="mango">mango</option>
<option value="orange">orange</option>
</select>
<br><br>
Vegetable
<input type="input" id="veggie">
<br><br>
Number
<input type="input" id="number">
<br><br>
<input type="button" value="search" id="search" disabled>
</form>
</body>
I'm not 100% sure, but it looks like you want to enable the button if only one of the select elements has a value or one of the input elements has a value, but not if both (or neither) do.
If that's the case then this should work, and it allows you you add as many elements to it as you need by adding IDs to the arrays at the top.
https://jsfiddle.net/j7by6bsz/
var selectInputIds = ['fruits', 'car'];
var textInputIds = ['veggie', 'number'];
function setButtonState() {
var hasVal = function(arr) {
for(var i = 0; i < arr.length; i++) {
if(document.getElementById(arr[i]).value) {
return true;
}
}
return false;
};
var hasSelectValue = function () {
return hasVal(selectInputIds);
}
var hasTextValue = function () {
return hasVal(textInputIds);
}
var theButton = document.getElementById('search');
var s = hasSelectValue();
var t = hasTextValue();
theButton.disabled = ((s && t) || (!t && !s)); // you can do this bit smarter, but this is explicit
}
(function attachStuff (arr, evt) {
function listenIn(arr, evt) {
for(var i = 0; i < arr.length; i++) {
document.getElementById(arr[i]).addEventListener(evt, setButtonState);
}
}
listenIn(selectInputIds, 'change');
listenIn(textInputIds, 'keyup');
}())
Your requirements could use some clarification around what happens if both input types have values though.

Loop through multidimensional array and then display results

I'm trying to build a form with drop downs that will query a json object with jQuery and then display that product with its data on my html page depending on what was chosen in the drop downs.
Here is my json object:
var obj = {
"ProductOne":
{
"url":["http://www.google.com"],
"map":["test-one"],
"options":["test-one","test-three","test-four"],
"dim":{
"bam":"5",
"tin":"4"
},
"acc":{
"bam":"1",
"tin":"2"
}
},
"ProductTwo":
{
"url":["http://www.google-two.com"],
"map":["test-two"],
"options":["test-two","test-three","test-five"],
"dim":{
"bam":"6",
"tin":"9"
},
"acc":{
"bam":"8",
"tin":"6"
}
}
};
Here is my form:
<form name="searchForm" id="searchForm">
<select name="dim">
<option value="" selected="">Select One</option>
<option value="5">5</option>
<option value="4">4</option>
<option value="6">6</option>
<option value="9">9</option>
</select>
<select name="acc">
<option value="" selected="">Select One</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="6">6</option>
<option value="8">8</option>
</select>
<select name="options">
<option value="" selected="">Select One</option>
<option value="test-one">Test One</option>
<option value="test-two">Test Two</option>
<option value="test-three">Test Three</option>
<option value="test-four">Test Four</option>
<option value="test-five">Test Five</option>
</select>
<input id="button" type="button" value="submit"/>
</form>
You can filter with this:
var filteredProducts = {},
dim = $("select[name=dim]").val(),
acc = $("select[name=acc]").val(),
option = $("select[name=options]").val();
function valueInObject(object, value){
for(var key in object){
if(object[key] == value) return true;
}
return false;
}
$.each(obj, function(key, product){
if(
(option == "" || $.inArray(option, product.options)) >= 0 &&
(acc == "" || valueInObject(product.acc, acc)) &&
(dim == "" || valueInObject(product.dim, dim))
){
filteredProducts[key] = product;
}
});
console.log(filteredProducts);
alert(JSON.stringify(filteredProducts));
Then, you have the filtered products in the filteredProducts object, that has same structure as the original obj object.
Then you can traverse it and show it in a table or something.
Assuming you want to show them on a list, let's say you have:
<div id="filteredProducts"></div>
you would do:
$('#filteredProducts').empty(); //Clears previous results
$.each(filteredProducts, function(productKey, product){
$('<div class="title">'+productKey+'<br/>'+
''+ product.url + ''+
'</div>').appendTo('#filteredProducts');
});
It would add each product to the list.
Cheers, from La Paz, Bolivia

Categories

Resources