Dynamic Dropdown - Year, Make, Model - Link final selection to a specific page - javascript

I am attempting to make a year/make/model lookup for an ecommerce website that uses 3dcart as an engine. Unfortunately, 3dcart does not have a module or simple solution, so I have to create this from scratch.
I found a basic solution for the Year, Make, Model lookup on this site, but the URL that is produced is built from the selections. This will not work for my needs. I need to be able to link the final selection to a specific url of my choosing.
For instance, if you were to choose "Lincoln" on the first drop down, then "Continental" on the second, then "1995" on the last, I would need the button to link to a specific url (www.autoparts.com/23cd3d2d2.html) and not one that was built from the selections. I have to do it this way because I am essentially creating a landing page that will have subcategories depending on the selection and those category pages are given an arbitrary URL that I cannot control. Also, there will only be roughly 30 of these category pages, so the same link will be used more than once. So, essentially, once all choices are made, there would be a button that would take you to the URL that I have designated in advance based on those choices.
Here is the current code, which does not yet do what I need:
<script>
var makeObject = {
"Acura": {
"ILX": ["2015", "2014", "2013"],
},
}
window.onload = function() {
var makeSel = document.getElementById("makeSel"),
modelSel = document.getElementById("modelSel"),
yearSel = document.getElementById("yearSel");
for (var make in makeObject) {
makeSel.options[makeSel.options.length] = new Option(make, make);
}
makeSel.onchange = function() {
modelSel.length = 1; // remove all options bar first
yearSel.length = 1; // remove all options bar first
if (this.selectedIndex < 1) return; // done
for (var model in makeObject[this.value]) {
modelSel.options[modelSel.options.length] = new Option(model, model);
}
}
makeSel.onchange(); // reset in case page is reloaded
modelSel.onchange = function() {
yearSel.length = 1; // remove all options bar first
if (this.selectedIndex < 1) return; // done
var years = makeObject[makeSel.value][this.value];
for (var i = 0; i < years.length; i++) {
yearSel.options[yearSel.options.length] = new Option(years[i], years[i]);
}
}
}
function buildUrl() {
var url = "/";
var make = document.querySelector('#makeSel').value;
var model = document.querySelector('#modelSel').value;
var year = document.querySelector('#yearSel').value;
var qs = encodeURIComponent(make + ' ' + model + ' ' + year);
return url;
}
</script>
<div class="dynamic-dropdown">
<center>
<form name="myform" id="myForm">
<h3 id="dropdown-h3">Search</h3>
<ul>
<li>
<select name="optone" id="makeSel" size="1">
<option value="" selected="selected">Select make</option>
</select>
</li>
<li>
<select name="opttwo" id="modelSel" size="1">
<option value="" selected="selected">Select model</option>
</select>
</li>
<li>
<select name="optthree" id="yearSel" size="1">
<option value="" selected="selected">Select year</option>
</select>
</li>
GO
</ul>
</form>
</center>
</div>
<hr/>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>

3Dcart not providing this kind of feature but we can build such using ajax and jQuery.
First, need to arrange category hierarchy according to filter and then using ajax and jQuery, we can build such kind of filters in 3Dcart.

Related

Change hidden input field value according to select options

I am trying to write a script for changing the hidden input value according to selected options.
I have hindi data stored on a variable and I need to pick this hindi data according to english data selected in select feild. The select options are working fine so far, but I am unable to fectch the related hindi data.
var stateObject = {
"Bihar": {
"Begusarai": ["Bachhwara", "Bakhari", "Balia", "Barauni", "Begusarai", "Bhagwanpur", "Birpur", "Cheriya Bariyarpur", "Chhorahi", "Dandari", "Garhpura", "Khudabandpur", "Mansoorchak", "Matihani", "Nawkothi", "Sahebpur Kamal", "Samho Akha Kurha", "Teghra"],
},
}
var stateObjectHindi = {
"बिहार": {
"बेगूसराय": ["बछवारा", "बखरी", "बलिया", "बरौनी", "बेगुसराय", "भगवानपुर", "बीरपुर", "चेरिया बरियारपुर", "छौराही", "डंडारी", "गढ़पुरा", "खोदाबंदपुर", "मंसूरचक", "मटिहानी", "नावकोठी", "साहेबपुर कमाल", "साम्हो अखा कुरहा", "तेघरा"],
},
}
window.onload = function() {
var stateList = document.getElementById("stateList"),
stateListHindi = document.getElementById("stateListHindi"),
districtList = document.getElementById("districtList"),
districtListHindi = document.getElementById("districtListHindi"),
blockList = document.getElementById("blockList"),
blockListHindi = document.getElementById("blockListHindi");
for (var country in stateObject) {
stateList.options[stateList.options.length] = new Option(country, country);
}
stateList.onchange = function() {
districtList.length = 1; // remove all options bar first
blockList.length = 1; // remove all options bar first
if (this.selectedIndex < 1) return; // done
for (var state in stateObject[this.value]) {
districtList.options[districtList.options.length] = new Option(state, state);
}
}
stateList.onchange(); // reset in case page is reloaded
districtList.onchange = function() {
blockList.length = 1; // remove all options bar first
if (this.selectedIndex < 1) return; // done
var district = stateObject[stateList.value][this.value];
for (var i = 0; i < district.length; i++) {
blockList.options[blockList.options.length] = new Option(district[i], district[i]);
stateListHindi.value = this.value;
}
}
}
<select name="state" id="stateList">
<option value="" selected="selected">Select State</option>
</select>
<select name="district" id="districtList">
<option value="" selected="selected">Select District</option>
</select>
<select name="block" id="blockList">
<option value="" selected="selected">Select Block</option>
</select>
<br/> State in Hindi: <input type="hidden" class="stateListHindi" id="stateListHindi" name="stateListHindi" value="" /><br/> District in Hindi: <input type="hidden" class="districtListHindi" id="districtListHindi" name="districtListHindi" value="" /><br/>Block in Hindi: <input type="hidden" class="blockListHindi" id="blockListHindi" name="blockListHindi" value="" /><br/>
JSFiddle Demo
Your data structure is perhaps not too well-suited for what you want here. You need to find the corresponding property in both objects, for the first two levels, by their position - so you will have to extract the keys first, and use indexOf to locate them.
So for the state first of all, that would be
var selectedKeyIndex = Object.keys(stateObject).indexOf(this.value);
stateListHindi.value = Object.keys(stateObjectHindi)[selectedKeyIndex];
Extract the keys from the English object, and find the index of the property matching the current selection in there. Then use that index, to extract the corresponding property name from the Hindi object.
Now, for the district, you'll have to do the same thing, but for one more level:
var selectedKeyIndex = Object.keys(stateObject[stateList.value]).indexOf(this.value);
districtListHindi.value = Object.keys(stateObjectHindi[stateListHindi.value])[selectedKeyIndex];
And then for the Blocks, which are in an array, you can select directly by index,
var selectedKeyIndex = stateObject[stateList.value][districtList.value].indexOf(this.value);
blockListHindi.value = stateObjectHindi[stateListHindi.value][districtListHindi.value][selectedKeyIndex];
All of it put together here: https://jsfiddle.net/6g5ad4cz/.
(I made the hidden fields into normal text fields, so that the result can be visually checked straight away.)

Clear and re populate drop down list javascript

I want to set an alert every time this option (valList4) is clicked as well as automatically filling in the next text box. I want this to work even if after the first choice, another choice will still work.
I have this code:
$("#List4").change(function() {
var valList4 = $("#List4").val();
if (valList4 == "Ferrari")
{
$("#List5")[0].selectedIndex = 1;
fillSelect($("#List4").val(),$("#List5")[0]);
}
else if (valList4 == "Porsche")
{
$("#List5")[0].selectedIndex = 1;
fillSelect($("#List4").val(),$("#List5")[0]);
}
Here is the alert at the end of the code:
alert("Your selection was:- \n" + valList4);
});
The problem is that if I change my selection from one to the other, the list keeps populating and the second box will not change with the first box.
EDIT
Fill Select function
function fillSelect(currCat,currList){
var step = Number(currList.name.replace(/\D/g,""));
for (i=step; i<nLists+1; i++) {
document.forms['tripleplay']['List'+i].length = 1;
document.forms['tripleplay']['List'+i].selectedIndex = 0;
}
HTML Code
<form name="completion" action="">
<select id='List4' name='List4' onchange="fillSelect(this.value,this.form['List5'])">
<option selected>Make a selection</option>
</select>
<select id='List5' name='List5' onchange="getValue2(this.value, this.form['List4'].value,
this.form['List4'].value)">
<option selected >Make a selection</option>
</select></P>
</form>

How do I get javascript to see updated select value?

I have a page with about 100 dropdown menus that I need to pass to another. So, I've put everything in an array that I'm sending via javascript. However, I'm not sure how to get the javascript to see the changed values of the dropdowns before sending. I mocked up some code to give you an idea of the problem. It only sends the value of the dropdown box at the time the page is initialized. Any help would be appreciated.
<select id="mydropdown">
<option value="Milk">Fresh Milk</option>
<option value="Cheese">Old Cheese</option>
<option value="Bread">Hot Bread</option>
</select>
<script>
var data = new Array();
data[0] = document.getElementById("mydropdown").value;
</script>
<form name="data" method="POST" action="passdata1b.php">
<input type="hidden" name="data">
</form>
<script>
function sendData()
{
// Initialize packed or we get the word 'undefined'
var packed = "";
for (i = 0; (i < data.length); i++) {
if (i > 0) {
packed += ",";
}
packed += escape(data[i]);
}
document.data.data.value = packed;
document.data.submit();
}
</script>
<h1>This is what the array contains:</h1>
<ul>
<script>
for (i = 0; (i < data.length); i++) {
document.write("<li>" + data[i] + "</li>\n");
}
</script>
</ul>
Go to passdata1b.php
Sam's answer was good, except..
data[0] = document.getElementById("mydropdown").value;
..that won't work since it's a dropdown menu. Instead get the value of the selected option. Use this instead:
var zeData = document.getElementById("mydropdown");
data[0] = zeData.options[zeData.selectedIndex].value;
Why can't you put this logic:
var data = new Array();
data[0] = document.getElementById("mydropdown").value;
In your sendData() function?
Comment if you need an example, but this should be a pretty easy fix. That way, when you click the link and run sendData(), it will parse the mydropdown value..instead of doing it on page load.

How to update html SELECT options with javascript or jquery, using values from other SELECT's (within eric hynds's multiselect widget)

I'm using Eric Hynds's jQuery multiselect widget to display a list of employees in several different sections on the same screen. I have several different multiselects on the same page, some of which have the same employees.
If a user selects (or unselects) an employee in one multiselect, I need to update the others to reflect the same choices. I have 2 'optgroups' to consider as well, if possible, but those can be ignored for this purpose, unless it's relatively easy to handle.
The options could be refreshed with javascript or jquery, independent of the multiselect widget, and then the .refresh method could be called to update the widget. So, the solution to this may or may not use code from the widget to do the updating of the options.
Here are examples of two SELECTs and their options. Brian Jones appears in both. If Brian Jones is selected in the first example, how can I dynamically select him in the second example (and if possible, move him to the 'Assigned Employees' group)? Same goes for if he is un-selected.
<select id="empSelection_01" name="employee_01" multiple="multiple">
<optgroup label="Unassigned Employees">
<option value="42954">Smith, Joe</option>
<option value="30357">Jones, Brian</option>
</optgroup>
<optgroup label="Assigned Employees">
<option value="42900">Brown, Laura</option>
<option value="30399">Evans, Jessica</option>
</optgroup>
</select>
<select id="empSelection_02" name="employee_02" multiple="multiple">
<optgroup label="Unassigned Employees">
<option value="42954">Doe, Jane</option>
<option value="30357">Jones, Brian</option>
</optgroup>
<optgroup label="Assigned Employees">
<option value="42900">Hix, Carolyn</option>
<option value="30399">Evans, Jessica</option>
</optgroup>
</select>
Try like this fiddle
$('#empSelection_01').multiselect({click:function(e){
var isChecked = $(e.currentTarget).attr("checked")=="checked";
var labelFrom = isChecked ? 'Unassigned Employees' : 'Assigned Employees';
var labelTo = !isChecked ? 'Unassigned Employees' : 'Assigned Employees';
var el = $('#empSelection_02').children('[label="' + labelFrom + '"]').children('[value="' + e.currentTarget.value + '"]');
el.remove();
$('#empSelection_02').children('[label="' + labelTo + '"]').append(el);
if (isChecked) {
el.attr('selected', 'selected');
} else {
el.removeAttr('selected');
}
$('#empSelection_02').multiselect('refresh');
}});
It's example how you can manipulate with this plugin, but it's not enough to solve you problem. You neeed some logic, to take options into consideration, and indicate in which group options must be located, especially if many-to-many connections is possible.
I ended up using this JavaScript, which receives the ID of the SELECT that was just changed, and then uses values within that SELECT to process all other SELECT's on the screen:
function refreshEmps(currID){
var sel = document.getElementById(currID);
var opt = sel.options;
var checkedVals = new Array();
// save checked values ***************************
for (i=0; i<opt.length; i++){
if (opt[i].selected==true) {
checkedVals[checkedVals.length]=opt[i].value;
}
}
//update remaining SELECT's ***************************
var ddCounter = 0; //
while(document.getElementById("employeeDD_" + ddCounter)!=null) {
var sel2 = document.getElementById("employeeDD_" + ddCounter);
if (currID!=sel2.id) {
var opt2 = sel2.options;
for (i=0; i<opt2.length; i++){
for (j=0; j<checkedVals.length; j++) {
if(opt2[i].value==checkedVals[j]) {
opt2[i].disabled=true;
opt2[i].style.color = 'red';
}
}//end for
}
}//end if
ddCounter++;
}//end WHILE
$("select").multiselect('refresh');
}

Show/Hide Div with JavaScript based on Select from Triple Dropdown

Gang -
This is my first time posting. I'm a JavaScript noob - I think I've figured out what direction to take - just not sure how to get there.
I have a triple drop down select menu. I want the third(final) selection to reveal a hidden div. Am I on the right track by thinking I need to use a combination of onchange, getElementById and if statements?
The javascript code for the dropdown is Philip M's Cut & Paste Triple Combo box from JavaScriptKit.com. That work's beautifully. I won't insert my exact code as the category list is significantly longer.
var categories = [];
categories["startList"] = ["Wearing Apparel","Books"]
categories["Wearing Apparel"] = ["Men","Women","Children"];
categories["Books"] = ["Biography","Fiction","Nonfiction"];
categories["Men"] = ["Shirts","Ties","Belts","Hats"];
categories["Women"] = ["Blouses","Skirts","Scarves", "Hats"];
categories["Children"] = ["Shorts", "Socks", "Coats", "Nightwear"];
categories["Biography"] = ["Contemporay","Historical","Other"];
categories["Fiction"] = ["Science Fiction","Romance", "Thrillers", "Crime"];
categories["Nonfiction"] = ["How-To","Travel","Cookbooks", "Old Churches"];
var nLists = 3; // number of select lists in the set
function fillSelect(currCat,currList){
var step = Number(currList.name.replace(/\D/g,""));
for (i=step; i<nLists+1; i++) {
document.forms['tripleplay']['List'+i].length = 1;
document.forms['tripleplay']['List'+i].selectedIndex = 0;
}
var nCat = categories[currCat];
for (each in nCat) {
var nOption = document.createElement('option');
var nData = document.createTextNode(nCat[each]);
nOption.setAttribute('value',nCat[each]);
nOption.appendChild(nData);
currList.appendChild(nOption);
}
}
function getValue(L3, L2, L1) {
alert("Your selection was:- \n" + L1 + "\n" + L2 + "\n" + L3);
}
function init() {
fillSelect('startList',document.forms['tripleplay']['List1'])
}
navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false);
</script>
My HTML is:
<div id="menuSearch">
<form name="tripleplay" action="">
<p><select name='List1' onchange="fillSelect(this.value,this.form['List2'])">
<option selected>-- Topic of Interest --</option>
</select></p>
<p><select name='List2' onchange="fillSelect(this.value,this.form['List3'])">
<option selected>-- Geographic Area --</option>
</select></p>
<select id="info"name='List3' onchange="getValue(this.value, this.form['List2'].value, this.form['List1'].value)">
<option selected >-- Information Type --</option>
</select>
</form>
</div>
the divs to show/hide are:
<div id="modelingCV">list of publications</div>
<div id="groundwaterCV">list of publications</div>
<div id="subsidenceCV">list of publications</div>
<div id="managementCV">list of publications</div>
<div id="qualityCV">list of publications</div>
<div id="wildlifeCV">list of publications</div>
Is replacing the getValue in the onchange in the final form select with getElementByID the best approach? And replace the getValue in the javascript function with some type of if statement to specify the values? I am guessing I need to hide the divs with javascript vs CSS? Am I completely off base all around?
Oy. Definitely bit off more than I can chew on this one. Any guidance would be appreciated. Thanks for reading!

Categories