Loop through multidimensional array and then display results - javascript

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

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>

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.

Filter an Object

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

Add form values without exceeding a total value in javascript

Excually Im not a programmer, but Im trying to learn how to make a questionnaire with html and javascript:
I have four selection boxes in a form. Each one of the selection boxes has the values through 0 to 10. The main rule of this questionnaire is to change the value of all four selection boxes so that it adds up to 10.
I figured out the following solution:
instant updated text box where it calculates the total value selected (with onChange);
validate at submit button if a total value of 10 (and not more or less) is selected.
Alternatively I would even assign a (error) message instantly when the user selects a value that exceeds the total value of 10.
I have some half baked javascripts, but I don't have enough understanding of the subject to excually connect the dots. Hope you can help me.
Tim
My framework:
<html>
<head>
<script type="text/javascript">
function editTotalValue(){
}
function validateTotalValue(){
}
</script>
</head>
<body>
<form name="form1">
<select name="question1" onChange="editTotalValue();">
<option selected value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<select name="question2" onChange="editTotalValue();">
<option selected value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<select name="question3" onChange="editTotalValue();">
<option selected value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<select name="question4" onChange="editTotalValue();">
<option selected value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<!-- Show total value selected in text box -->
<input name="totalValue" type="text" maxlength="2" readonly="true">
<!-- Validate that totalValue(); is indeed 10 and not more or less and pass on the data -->
<input name="submit" type="button" onClick="validateTotalValue();">
</form>
</body>
</html>
Here's something more in-depth that you can play with:
document.getElementById("form1").onsubmit = checkTarget;
function checkTarget(evt)
{
var el;
if(window.event)
{
//checking for IE equivalent
el = window.event.srcElement;
}else if(evt.target)
{
el = evt.target;
}
if(window.event)
{
//checking for IE equivalent
window.event.returnValue = false;
}else if(evt.preventDefault)
{
evt.preventDefault();
}
calculateValues(el);
}
function calculateValues(form)
{
var values = [];
var value = 0;
for(var i=0;i<form.elements.length;i++)
{
var el = form.elements[i];
if(el.tagName === "SELECT")
{
values.push(el.value);
}
}
for(var j=0;j<values.length;j++)
{
value = value + parseInt(values[j], 10);
}
updateValue(value);
checkValue(values, value);
}
function updateValue(value)
{
document.getElementById("result_box").value = value;
}
function checkValue(values, value)
{
var temp = [];
for(var i=0;i<values.length;i++)
{
if(values[i] > 0 && values[i] < 10)
{
temp.push(values[i]);
}
}
if(value === 10 && temp.length === 4)
{
document.getElementById("message_box").value = "You win!";
}else if(value > 10 && temp.length === 4)
{
document.getElementById("message_box").value = "Value is more than 10";
}
}
http://jsfiddle.net/YS6mm/9/
Tested as working in: Firefox 4, IE8, IE8 Compatibility View (Quirks), IE7 Quirks Mode, Chrome 4, Safari 4, and Opera 11.
function editTotalValue() {
var val = 0;
for (var i = 1; i < 5; i++) {
val = val + document.getElementById("question" + i).value;
}
var display = document.getElementbyId("totalValue");
if (val > 10) {
alert("error");
} else {
display.value = val;
}
}

jQuery remove SELECT options based on another SELECT selected (Need support for all browsers)

Say I have this dropdown:
<select id="theOptions1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
I want it so that when the user selects 1, this is the thing that the user can choose for dropdown 2:
<select id="theOptions2">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
Or if the user selects 2:
<select id="theOptions2">
<option value="a">a</option>
<option value="b">b</option>
</select>
Or if the user selects 3:
<select id="theOptions2">
<option value="b">b</option>
<option value="c">c</option>
</select>
I tried the code posted here:
jQuery disable SELECT options based on Radio selected (Need support for all browsers)
But it doesn't work for selects.
Please help!
Thank you!
UPDATE:
I really like the answer Paolo Bergantino had on:
jQuery disable SELECT options based on Radio selected (Need support for all browsers)
Is there anyway to modify this to work with selects instead of radio buttons?
jQuery.fn.filterOn = function(radio, values) {
return this.each(function() {
var select = this;
var options = [];
$(select).find('option').each(function() {
options.push({value: $(this).val(), text: $(this).text()});
});
$(select).data('options', options);
$(radio).click(function() {
var options = $(select).empty().data('options');
var haystack = values[$(this).attr('id')];
$.each(options, function(i) {
var option = options[i];
if($.inArray(option.value, haystack) !== -1) {
$(select).append(
$('<option>').text(option.text).val(option.value)
);
}
});
});
});
};
This works (tested in Safari 4.0.1, FF 3.0.13):
$(document).ready(function() {
//copy the second select, so we can easily reset it
var selectClone = $('#theOptions2').clone();
$('#theOptions1').change(function() {
var val = parseInt($(this).val());
//reset the second select on each change
$('#theOptions2').html(selectClone.html())
switch(val) {
//if 2 is selected remove C
case 2 : $('#theOptions2').find('option:contains(c)').remove();break;
//if 3 is selected remove A
case 3 : $('#theOptions2').find('option:contains(a)').remove();break;
}
});
});
And the beautiful UI:
<select id="theOptions1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br />
<select id="theOptions2">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
You can add classes to your <option>s to store which go with each value of #theOptions1:
<select id="theOptions2">
<option value="a" class="option-1 option-2">a</option>
<option value="b" class="option-1 option-2 option-3">b</option>
<option value="c" class="option-1 option-3">c</option>
</select>
then do this:
$(function() {
var allOptions = $('#theOptions2 option').clone();
$('#theOptions1').change(function() {
var val = $(this).val();
$('#theOptions2').html(allOptions.filter('.option-' + val));
});
});
For the record you can NOT remove options in a select list in Internet Explorer.
try this. this will definitely work
$(document).ready(function () {
var oldValue;
var oldText;
var className = '.ddl';
$(className)
.focus(function () {
oldValue = this.value;
oldText = $(this).find('option:selected').text();
})
.change(function () {
var newSelectedValue = $(this).val();
if (newSelectedValue != "") {
$('.ddl').not(this).find('option[value="' + newSelectedValue + '"]').remove();
}
if ($(className).not(this).find('option[value="' + oldValue + '"]').length == 0) { // NOT EXIST
$(className).not(this).append('<option value=' + oldValue + '>' + oldText + '</option>');
}
$(this).blur();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<form action="/Home/Ex2" method="post">
<select class="ddl" id="A1" name="A1">
<option value="">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
<hr />
<select class="ddl" id="A2" name="A2">
<option value="">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
<hr />
<select class="ddl" id="A3" name="A3">
<option value="">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
<hr />
<select class="ddl" id="A4" name="A4">
<option value="">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
<hr />
<input type="submit" name="submit" value="Save Data" id="btnSubmit" />
</form>
Actually, using the code below will remove a dropdown option just fine in IE, as long as it is not the selected option (it will not work on "a" without deselecting that option first):
var dropDownField = $('#theOptions2');
dropDownField.children('option:contains("b")').remove();
You just run this to remove whatever option you want to remove under a conditional statement with the first group (theOptions1) - that if one of those is selected, you run these lines:
var dropDownField = $('#theOptions2');
if ($('#theOptions1').val() == "2") {
dropDownField.children('option:contains("c")').remove();
}
if ($('#theOptions1').val() == "3") {
$("#theOptions2 :selected").removeAttr("selected");
$('#theOptions2').val('b');
dropDownField.children('option:contains("a")').remove();
}
-Tom

Categories

Resources