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!
Related
I'm trying to select a drop-down value using js. In my case, I need to select "DRAW PORTRAIT" drop-down option after the plugin loads.
I tried two methods but I'm not getting anywhere. This is a part of the frontend found in Bookly WordPress plugin. I added an id id="category" to the dropdown so that I can select a value.
HTML:
<div class="bookly-js-chain-item bookly-table bookly-box" style="display: table;">
<div class="bookly-form-group">
<label>Service Type</label>
<div>
<select id="categorydraw" class="bookly-select-mobile bookly-js-select-category">
<option value="">Select category</option>
<option value="6">DRAW PORTRAIT</option>
<option value="7">DRAW DUMMY FIGURE</option>
<option value="8">DESIGN WAX SCULPTURE</option></select>
</div>
</div>
</div>
Method 01
document.getElementById("categorydraw").value = "DRAW PORTRAIT";
Method 02
var objSelect = document.getElementById("categorydraw");
setSelectedValue(objSelect, "DRAW PORTRAIT");
function setSelectedValue(selectObj, valueToSet) {
for (var i = 0; i < selectObj.options.length; i++) {
if (selectObj.options[i].text== valueToSet) {
selectObj.options[i].selected = true;
return;
}
}
}
Please see the full code where the js doesn't work: https://jsfiddle.net/3z5hcv62/
I would really appreciate if someone can correct my cranky code. Thanks in advance!
One line of jQuery will allow you to select the item necessary:
$('#categorydraw option[value="7"').prop("selected", true);
https://jsfiddle.net/fLc1p5mq/
Edit: In order to activate on a WordPress page load, use:
jQuery( document ).ready(function() {
jQuery('#categorydraw option[value="7"').prop("selected", true);
});
First, i want to make sure. Do you want to select the value of the dropdown or set the value to the dropdown?. Maybe this will help your problem.
HTML
<!-- I set the "categories" id to the dropdown -->
<select class="bookly-select-mobile bookly-js-select-category" id="categories">
<option value="">Select category</option>
<option value="1">Cosmetic Dentistry</option>
<option value="2">Invisalign</option>
<option value="3">Orthodontics</option>
<option value="4">Dentures</option>
</select>
<p>
Selected value: <strong id="selected"></strong>
</p>
JavaScript
var dropdown = document.getElementById('categories');
var datas = [];
var select = 3;
/* Get value with text from dropdown */
for(var i=0;i<dropdown.options.length;i++) {
datas.push({
id: dropdown.options[i].value,
text: dropdown.options[i].text,
});
}
/* For set the value */
dropdown.value = select; // after page loaded,, default value will selected is "Orthodontics"
/* For select current value with the text */
var dataSelected = datas[select];
document.getElementById('selected').innerHTML = "ID: "+dataSelected.id+", TEXT: "+dataSelected.text;
The result will show like this https://jsfiddle.net/65jnzLko/1/
You can improve that code. Like selecting datas by id of the dropdown value.
Or if you just want to set the value for your dropdown, you can do this
// using pure js
document.getElementById('yourdropdown').value = 3 // or other values
// using jquery
$("#yourdropdown").val(5) // 5 can replace with other values
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.
I'm trying to bulid an image path from two select fields. I have to use the "id"s because "value"s are used already. Unfortunatedly only the second select works. Does anyone have a hint? As you might see I'm not a coder. Could anyone be so kind and help to make the code more elegant/slim?
I use onchange to update the "result1" and "result2" allways when the user alters his selection.
Thanks in advance, Georg
Here is my code:
<script>
function showOptions1(s) {
document.getElementById("result1").innerHTML = "<img src='img/preview/" + s[s.selectedIndex].id;
}
</script>
<script>
function showOptions2(s) {
document.getElementById("result2").innerHTML = s[s.selectedIndex].id + ".jpg'>";
}
</script>
<select onchange="showOptions1(this)" id="my_select1">
<option value="werta" id="1">Text Item 1a</option>
<option value="wertb" id="2">Text Item 1b</option>
</select>
<select onchange="showOptions2(this)" id="my_select2">
<option value="wertc" id="3">Text Item 1c</option>
<option value="wertd" id="4">Text Item 1d</option>
</select>
<span id="result1"></span><span id="result2"></span>
I wouldn't use the onchange event because you want the user to select two things before building the path. So, put another button on the screen called "save image" or something like that. The onclick of this button gets the "value" of each select input and concats them together. You can easily get a handle to the select inputs using jquery by name
var select1 = $("#my_select1");
Now your problem is that you don't want the value. That would be easy. Instead you want the select option and then you want to get the id. You can do that as follows
var my1id = $("#my_select1 option:selected" ).id;
Thanks a lot for your support. Cheers Georg
Finaly I use this code (and stick to onchange because I dont want another button because there are allready three of them):
<script>
var selection01, selection02;
showOptions1 = function(s) {
selection01 = "<img src='img/preview/" + s[ s.selectedIndex ].id;
getResult();
};
showOptions2 = function(s) {
selection02 = s[ s.selectedIndex ].id + ".jpg' width='200px;'>";
getResult();
};
function getResult() {
var total = selection01 + selection02;
console.log( total );
document.getElementById("Image").innerHTML = total;
};
</script>
<select id="select1" onchange="showOptions1(this)">
<option value="" id="01" selected>...</option>
<option value="werta" id="10">Text Item 1a</option>
<option value="wertb" id="20">Text Item 1b</option>
</select>
<select id="select2" onchange="showOptions2(this)">
<option value="" id="02" selected>...</option>
<option value="wertc" id="30">Text Item 1c</option>
<option value="wertd" id="40">Text Item 1d</option>
</select>
<hr><span id="Image"></span>
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>
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');
}