3 Select Elements, But Produce 6 Value. Why? - javascript

I have this HTML structure :
<div id="kurir_list">
<div class="row">
<div class="col-sm-6">
<div class="form-group form-group-default form-group-default-select2 required">
<select class="tarif full-width" data-init-plugin="select2">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group form-group-default form-group-default-select2 required">
<select class="tarif full-width" data-init-plugin="select2">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group form-group-default form-group-default-select2 required">
<select class="tarif full-width" data-init-plugin="select2">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
</div>
</div>
</div>
</div>
and I have this jquery :
$(".tarif").change(function() {
$(".tarif").each(function() {
alert ($(this).val());
});
});
why the alert produce 6 times dialog box, instead of 3?
first : empty
second : either 1 or 2 of first select element
third : empty
fourth : either 1 or 2 of second select element
fifth : empty
sixth : either 1 or 2 of third select element
how to get exact value of selected element and ignore empty value? please note that this is not just HTML select, but it use Select2 plugins.
UPDATE : here's my complete javascript code
(function($) {
'use strict';
$(document).ready(function() {
$('#rootwizard').bootstrapWizard({
onTabShow: function(tab, navigation, index) {
var $total = navigation.find('li').length;
var $current = index + 1;
// If it's the last tab then hide the last button and show the finish instead
if ($current >= $total) {
$('#rootwizard').find('.pager .next').hide();
$('#rootwizard').find('.pager .finish').show().removeClass('disabled hidden');
} else if ($current == 2) {
if ($(".tarif").is(":disabled")) {
$('#rootwizard').find('.pager .next').hide();
$('#rootwizard').find('.pager .finish').hide();
}
$(".tarif").change(function() {
if ($(".tarif").is(':disabled')) {
$('#rootwizard').find('.pager .next').hide();
} else {
var emptySelect = false;
$('#kurir_list select').each(function(){
if (!$(this).find('option:selected').val()) {
emptySelect = true;
}
});
if (emptySelect == false ) {
$('#rootwizard').find('.pager .next').show();
} else {
$('#rootwizard').find('.pager .next').hide();
}
}
$(".tarif").each(function() {
alert ($(this).val());
});
var selected_tarif = $(this).val();
var ongkir2 = $("#ongkir2").text();
ongkir2 = ongkir2.replace(/\D/g,"");
var new_ongkir2 = parseInt(ongkir2) + parseInt(selected_tarif);
new_ongkir2 = addCommas(new_ongkir2);
$("#ongkir2").text("Rp "+new_ongkir2);
});
$(".kurir").change(function() {
var selected_courier = $(this).val();
var token = $(this).data('token');
var productid = $(this).data('productid');
var city = $("#city").val();
var area = $("#area").val();
var quantity = $(".orderlist2").find("."+productid).find(".quantity").text();
quantity = quantity.replace(/\D/g,"");
var json_url = "SOME URL HERE";
$.ajax({
url: json_url,
dataType: "JSON",
success: function(json){
var rate_tarif = "";
var selected_tarif = "";
$.each(json, function(i,o){
rate_tarif += "<option value="+o.tarif+">"+o.rate+"</option>";
});
$("#tarif-"+productid).append(rate_tarif).change();
event.preventDefault();
$("#tarif"+productid).prop("disabled", false);
selected_tarif = $("#tarif-"+productid).val();
}
});
});
$("#state").change(function() {
$('#rootwizard').find('.pager .next').hide();
});
} else {
$('#rootwizard').find('.pager .next').show();
$('#rootwizard').find('.pager .finish').hide();
}
},
onNext: function(tab, navigation, index) {
console.log("Showing next tab");
},
onPrevious: function(tab, navigation, index) {
console.log("Showing previous tab");
},
onInit: function() {
$('#rootwizard ul').removeClass('nav-pills');
}
});
});
})(window.jQuery);

Your subsequent comment explains it:
what you have is plain HTML, while in my case is using Select2 plugins
The way select2 works, it hides your select elements (without removing them) and creates a new structure, copying your classes and such to it. So you end up with .tarif elements that were in your HTML, and also .tarif elements created by select2.
You can limit the ones you respond to by narrowing your selector:
$("select.tarif").change(function() {
$("select.tarif").each(function() {
alert ($(this).val());
});
});
You can see what select2 does on their examples page.
Here's the "before" of the first example:
<select class="js-states form-control">
<!--...options and such...-->
</select>
Here's the "after":
<select class="js-example-basic-single js-states form-control select2-hidden-accessible" tabindex="-1" aria-hidden="true">
<!--...options and such...-->
</select>
<span class="select2 select2-container select2-container--default" dir="ltr" style="width: 100%;"><span class="selection"><span class="select2-selection select2-selection--single" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-labelledby="select2-438s-container"><span class="select2-selection__rendered" id="select2-438s-container" title="Alaska">Alaska</span><span class="select2-selection__arrow" role="presentation"><b role="presentation"></b></span></span></span><span class="dropdown-wrapper" aria-hidden="true"></span></span>
Note how the original select is hidden, and the js-states and form-control classes were copied from the select to the select2-generated span.

Related

Selecting a specific element from multiple forms

I'm trying to select a specific element from multiple forms but it's not working properly:
So my javascript code is:
function makeActive(target)
{
$("div.interactive").removeClass("interactive");
$("#form" + target).addClass("interactive");
}
$(document).ready(function () {
$('.interactive option[name=bu]').on('change', function () {
$('.interactive option[name=discipline]').empty();
$('.interactive option[name=project]').empty();
$('.interactive option[name=role]').empty();
$.ajax({
type: 'GET',
url: '#Url.Action("GetList", "Central")',
dataType: 'Json',
data: { InitiateId: $('.interactive option[name=bu]').val(), InitiateType: "BU" },
success: function (data) {
console.log("That was calling")
$('.interactive option[name=discipline]').append('<option value="">Select</option>');
$.each(data, function (index, value) {
$('.interactive option[name=discipline]').append('<option value="' + value.Id + '">' + value.Name + '</option>');
});
$('.interactive option[name=project]').append('<option value="">Select Discipline firt</option>');
$('.interactive option[name=role]').append('<option value="">Select Project first</option>');
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
And cshtml struct page is:
<div id="faq" role="tablist" aria-multiselectable="true">
#foreach (var actor in Model)
{
string areacontrol = "answer" + actor.Id;
count +=1;
bool open = false;
if (ViewBag.actor != null)
{
if (actor.Id == ViewBag.actor.Id)
{
open = true;
}
}
else
{
if (count == 1)
{
open = true;
}
}
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="questionOne">
<h5 class="panel-title">
<a data-toggle="collapse" data-parent="#faq" href="##areacontrol" aria-expanded="false" aria-controls="answerOne"
onclick=" makeActive(#actor.Id)">
#actor.Name (#actor.Email)
</a>
</h5>
</div>
<div id="#areacontrol" class="panel-collapse collapse #(open?" in":"")" role="tabpanel" aria-labelledby="questionOne">
<div class="panel-body">
#using (Html.BeginForm("Assign", "Central", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
string form = "form" + actor.Id;
<div class="row form-group #(open?" interactive":"")" id="#form">
<div class="col-md-3 col-md-offset-0">
<label for="bu">Business Unit</label>
<select name="bu" class="form-control">
<option value="">--Select--</option>
#foreach (var item in flowcontext.ContiBusinessUnits.ToList())
{
if (ViewBag.bu != null && actor.Id == ViewBag.actor.Id)
{
bool selected = false;
if (ViewBag.bu.Name == item.Name)
{
selected = true;
}
if (selected)
{
<option value="#item.Id" selected>#item.Name</option>
}
else
{
<option value="#item.Id">#item.Name</option>
}
}
else
{
<option value="#item.Id">#item.Name</option>
}
}
</select>
</div>
<div class="col-md-3">
<label for="discipline">Discipline</label>
<select name="discipline" class="form-control">
#if (ViewBag.discipline != null && actor.Id == ViewBag.actor.Id)
{
<option value="#ViewBag.discipline.ID">#ViewBag.discipline.Name</option>
}
else
{
<option value="">Select Business Unit first</option>
}
</select>
</div>
<div class="col-md-3">
<label for="project">Project</label>
<select name="project" class="form-control">
#if (ViewBag.project != null && actor.Id == ViewBag.actor.Id)
{
<option value="#ViewBag.project.ID">#ViewBag.project.Name</option>
}
else
{
<option value="">Select Discipline first</option>
}
ViewBag.role_id = contiRole;
</select>
</div>
<div class="col-md-3">
<label for="destination">Role</label>
<select name="role" class="form-control">
#if (ViewBag.role != null && actor.Id == ViewBag.actor.Id)
{
<option value="#ViewBag.role.ID">#ViewBag.role.Name</option>
}
else
{
<option value="">Select Project first</option>
}
</select>
</div>
<div class="col-md-3" style="display:none">
<label for="destination">User Id</label>
<select name="userid" class="form-control">
<option value="#actor.Id" selected>#actor.Name</option>
</select>
</div>
</div>
<div class="row form-group">
<div class="col-md-3 col-md-offset-8">
<input type="submit" class="btn btn-primary btn-block" value="Add">
</div>
</div>
}
</div>
</div>
</div>
}
</div>
<!--end language: lang-html -->
In that inside a foreach loop, I load/ generate a form.
First: The bootstrap collapse will be open for the first user(actor);
Inside, I have a form with is necessary to be similar and be a cascade drop select!
When I make a change[ $('.interactive option[name=bu]').on('change', function (){}]that calls for me a controller method which returns me a list and with that list a generate the second field and again for other 2 field!
That helps me to make a cascade select for a form and that works well but only for the first one!
I think either I'm not making the selections properly or using ajax, "$ (document) .ready" does not get the data properly.
How I can select properly or tell others methods!
How can improve that and make it work for all form elements?
Hi in this example we get the selected value from a dropdown list in different forms using a commun class the elements share and then we save that value inside an array which contains the name of the dropdown list, the selected value and the selected value text.
let options = document.querySelectorAll('.cmbMsg');
//get all select boxes with the same class
var values = [];
options.forEach(function(option) {
values.push({"item":option.getAttribute("name"),"value":option[option.selectedIndex].value,"text":option[option.selectedIndex].text});
});
console.log(values);
.cmbMsg {
font-size:14px;
}
<form action="" id="form1">
<select name="select1" id="select1" class="cmbMsg">
<option value="1" selected>Hello </option>
<option value="2">My friend</option>
</select>
</form>
<br>
<form action="" id="form2">
<select name="select2" id="select2" class="cmbMsg">
<option value="1">Hola</option>
<option value="2" selected>Mundo</option>
</select>
</form>
<br>
<form action="" id="form3">
<select name="select3" id="select3" class="cmbMsg">
<option value="1">Viva</option>
<option value="2" selected>la France</option>
</select>
</form>
Hope it helps
I found the solution!
The problem was that I did not recognize my selections after we came up with a change using ajax and I just load all my field immediately after the page load and group them for each form!
$(form + 'select[name=bu]').on('change', function (){};
And I just call a function for getting all actorid and pushing on a list and "leasing" for all field;

How to make input tabs using two inputs?

When we select Anesthesiology in first input, the second input should only show Anesthesiology doctors, when we select Cardiology it should only show Cardiology doctors and so on. Should I use Javascript or jQuery for this? Please help me to find out solution for this. Thank you.
HTML
<div class="col-md-4 col-sm-12">
<select id="dept" name="departments">
<option selected>Anesthesiology</option>
<option>Cardiology</option>
<option>Dermatology</option>
</select>
</div>
<div class="col-md-4 col-sm-12">
<select id="doctors" class="form-control">
<option>Anesthesiology doctor 1</option>
<option>Anesthesiology doctor 2</option>
<option>Cardiology doctor 1</option>
<option>Cardiology doctor 2</option>
<option>Dermatology doctor 1</option>
<option>Dermatology doctor 2</option>
</select>
</div>
Try use the following example,
This will hide all options and only show those that contains the value from dept dropdown
var v = $(this).val()
$("#doctors option").hide()
$("#doctors option:contains(" + v + ")").show()
This will then automatic set the first visible element to be selected, so it updates the dropdown of doctors
$('#doctors option').each(function () {
if ($(this).css('display') != 'none') {
$(this).prop("selected", true);
return false;
}
});
$('#dept').change(function() {
var v = $(this).val()
$("#doctors option").hide()
$("#doctors option:contains(" + v + ")").show()
$('#doctors option').each(function () {
if ($(this).css('display') != 'none') {
$(this).prop("selected", true);
return false;
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-4 col-sm-12">
<select id="dept" name="departments">
<option selected>Anesthesiology</option>
<option>Cardiology</option>
<option>Dermatology</option>
</select>
</div>
<div class="col-md-4 col-sm-12">
<select id="doctors" class="form-control">
<option>Anesthesiology doctor 1</option>
<option>Anesthesiology doctor 2</option>
<option>Cardiology doctor 1</option>
<option>Cardiology doctor 2</option>
<option>Dermatology doctor 1</option>
<option>Dermatology doctor 2</option>
</select>
</div>
This will update second dropdown when first will change.
(function () {
var $dept = $('#dept');
var $doctors = $('#doctors');
$dept.on('change', onDocSelected)
function onDocSelected() {
var selected = $dept.val();
$doctors.find('option').each(function (i, opt) {
toggle(selected, opt)
});
}
function toggle(selected, opt) {
var isApplicable = opt.text.indexOf(selected) !== -1;
return isApplicable ? $(opt).show() : $(opt).hide();
}
}($))
Apply a class to the options of the second select list - and on change of the first select - hide all optionsand then show only those with the corresponding class.
$(document).ready(function(){
$('#dept').change(function(){
var specialty = $(this).val();
$('#doctors').val(0);
$('#doctors option').hide();
$('.'+ specialty).show();
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-4 col-sm-12">
<label> Select a specialty</label>
<select id="dept" name="departments">
<option></option>
<option>Anesthesiology</option>
<option>Cardiology</option>
<option>Dermatology</option>
</select>
</div>
<div class="col-md-4 col-sm-12">
<label> Select a Doctor</label>
<select id="doctors" class="form-control">
<option></option>
<option class="Anesthesiology">Anesthesiology doctor 1</option>
<option class="Anesthesiology">Anesthesiology doctor 2</option>
<option class="Cardiology">Cardiology doctor 1</option>
<option class="Cardiology">Cardiology doctor 2</option>
<option class="Dermatology">Dermatology doctor 1</option>
<option class="Dermatology">Dermatology doctor 2</option>
</select>
</div>
check this
<div class="col-md-4 col-sm-12">
<select id="dept" name="departments">
<option></option>
<option>Anesthesiology</option>
<option>Cardiology</option>
<option>Dermatology</option>
</select>
</div>
<div class="col-md-4 col-sm-12">
<select id="doctors" class="form-control">
</select>
</div>
script for above selection
$(document).ready(function(){
var docotors = ['Anesthesiology doctor 1','Anesthesiology doctor 2','Cardiology doctor 1','Cardiology doctor 2','Dermatology doctor 1'];
$("#dept").on("change",function(){
var selectdDept = $(this).val();
$("#docotrs").empty();
docotors.forEach(function (i) {
if(i.indexOf(selectdDept) >= 0){
$("#doctors").append('<option>'+i+'</option>');
}
});
});
});
If you have doctors name list than create an JSON object by the below method and access it by the selected department value
$(document).ready(function(){
var docotors = {'Anesthesiology':['Anesthesiology doctor 1','Anesthesiology doctor 2'],'Cardiology':['Cardiology doctor 1','Cardiology doctor 2'],'Dermatology':['Dermatology doctor 1']};
$("#dept").on("change",function(){
var selectdDept = $(this).val();
$("#doctors").empty();
if(selectdDept){
var selectedDeptDocotors = docotors[""+selectdDept+""];
selectedDeptDocotors.forEach(function(i){
$("#doctors").append('<option>'+i+'</option>');
});
}
});
});
If you want to do with pure javascript, you may try this
<div class="col-md-4 col-sm-12">
<select id="dept" name="departments" onchange="showOptions(this)">
<option>Select option</option>
<option>Anesthesiology</option>
<option>Cardiology</option>
<option>Dermatology</option>
</select>
</div>
<div class="col-md-4 col-sm-12">
<select id="doctors" class="form-control">
</select>
</div>
SCRIPTS:
var Anesthesiology = [
{ text: "Anesthesiology doctor 1" },
{ text: "Anesthesiology doctor 2" }];
var Cardiology = [
{ text: "Cardiology doctor 1" },
{ text: "Cardiology doctor 2" }];
var Dermatology = [
{ text: "Dermatology doctor 1" },
{ text: "Dermatology doctor 2" }];
function showOptions(e) {
var userSelection = e.options[e.selectedIndex].text;
switch (userSelection) {
case 'Anesthesiology':
options(Anesthesiology);
break;
case 'Cardiology':
options(Cardiology);
break;
case 'Dermatology':
options(Dermatology);
break;
default:
document.getElementById('doctors').innerHTML = "";
break;
}
}
function options(arr) {
var selectList = document.getElementById('doctors');
var len = selectList.options.length;
for (var i = 0; i < arr.length; i++) {
for (j = 0; j < len; j++) {
selectList.options[j] = null;
}
var option = document.createElement("option");
option.text = arr[i].text;
selectList.appendChild(option);
}
}

How can I filter out a div from two select options?

Here is my Fiddle to the example
$('select#classes').on('change', function() {
var classSearch = $(this).val();
$('.col-sm-6:not(:contains(' + classSearch + '))').hide();
$('select#subjects').on('change', function() {
var subjectsSearch = $(this).val();
$('.col-sm-6:contains(' + classSearch + '))').show();
$('.col-sm-6:not(:contains(' + subjectsSearch + '))').hide();
});
});
I strongly suggest the use of values html attribute instead of the text itself for options, otherwise the value of the select will be the selected text (not very useful).
And a little explanation of how you structured your page could have been great, so we wouldn't have to go through the whole code and try to understand what it does and how it is built: what should we display ? when ?
About your problem (with a general structure):
HTML:
<label for="select_class">Class:
<select id="select_category" class="selectSome">
<option value="null">Please select...</option>
<option value="c1">Class 1</option>
<option value="c2">Class 2</option>
<option value="c3">Class 3</option>
</select>
</label><br/>
<label for="select_subject">Subject:
<select id="select_subject" class="selectSome">
<option value="null">Please select...</option>
<option value="s1">Subject 1</option>
<option value="s2">Subject 2</option>
<option value="s3">Subject 3</option>
</select>
</label>
<hr/>
<div class="row" id="row_s1_c1">Subject 1 for Class 1</div>
<div class="row" id="row_s2_c1">Subject 2 for Class 1</div>
<div class="row" id="row_s1_c2">Subject 1 for Class 2</div>
<div class="row" id="row_s2_c2">Subject 2 for Class 2</div>
<div class="row" id="row_s3_c2">Subject 3 for Class 2</div>
<div class="row" id="row_s3_c3">Subject 3 for Class 3</div>
CSS:
.row {
display: none;
}
JS:
$().ready(function() {
$('.selectSome').on('change', function() {
showHide();
});
});
function showHide() {
// hide all rows
$('.row').hide();
// show good row only
if ($('#select_category').val() != 'null' && $('#select_subject').val() != 'null') {
$('#row_' + $('#select_subject').val() + '_' + $('#select_category').val()).show();
}
}
http://jsfiddle.net/g5cryt31/
You can do it using parents and not
$('select#classes').on('change', function() {
var classSearch = $(this).val();
$('.col-sm-6 *').not('.' + classSearch).hide();
$('select#subjects').on('change', function() {
var subjectsSearch = $(this).val();
$('.'+classSearch).parents('.col-sm-6').show();
$('.col-sm-6 *').not('.' + subjectsSearch).hide();
});
});

How to make cloned select behave independantly of original?

I have some logic written for a form where the available items in the second dropdown change based on the first selection.
The drop downs are cloned to allow the user to work with multiples if needed.
The cloned drop downs change if anything is changed in the original drop down. The second field in the cloned options do not respond to change events in the first.
I would like for each cloned set of fields to behave independantly of the other sets of fields. Here is a fiddle: http://jsfiddle.net/HchH8/
Why is this happening? I tried using clone(true, true) for deep copy and it didn't work. I have searched on SO for similar problems and I just can't wrap my head around the answers I'm finding. I am new to this. Can anyone help me please?
jQuery
prods = {
Cookware: ["- Select -", "Round French Oven", "Oval French Oven", "Braiser", "Skillet", "Fry Pan", "Grill Pan", "Saute Pan", "Saucepan", "Saucier", "Griddle", "Roaster", "Stockpot", "Speciality Cookware", "Other"],
Bakeware: ["- Select -", "Covered Casserole", "Baking Dish", "Stoneware Gratin", "Speciality Bakeware", "Individual Bakeware", "Metal Bakeware", "Other"],
KitchenTools: ["- Select -", "Utensils", "Kitchen Accessories", "Cutlery", "Wine Tools", "Textiles", "Other"],
DineEntertain: ["- Select -", "Dinnerware", "Serveware", "Tabletop Accessories", "Glassware", "Kettles", "Tea Collection", "Café Collection", "Other"]
};
var category = $('select[name^="Product_category"]');
var productType = $('select[name^="Product_type"]');
$('.prod-info').live("change", function () {
var catSelected = $(this).val();
$(this).parent("li").next("li.subCats").fadeIn('fast'); /*Fades in next option once selection has been made*/
if($(this).is(category)) {
$('select[name^="Product_type"]').empty();
$('.product-size, .product-color').prop('selectedIndex',0);
$.each(prods[catSelected], function (key, value) {
$('select[name^="Product_type"]')
.append($("<option></option>")
.attr("value", value)
.attr("name", value)
.text(value));
});
}
if($(this).is(productType)) {
$('.product-size, .product-color').prop('selectedIndex',0);
}
});
var otherSelect = $('select');
var select = this.value;
otherSelect.change(function () {
if ($(this).val() == 'Other') {
$(this).next('.other').show();
}
else $(this).next('.other').hide();
});
for (var i = 2; i < 6; i++) { // add counts in a for loop
$('select[name="numProd"]').append('<option value=' + i + '>' + i + '</option>');
}
$.fn.duplicate = function(count, cloneEvents) {
var tmp = [];
for (var i = 0; i < count; i++) {
$.merge(tmp, this.clone(cloneEvents, true, true).get());
}
return this.pushStack(tmp);
};
//SELECT CHANGE FUNCTION (on change get value and clone)
$('select[name="numProd"]').change(function(){ // on change...
var numOfClones = $(this).val() -1; // get value...
var cntr = 2;
$('#addProds').empty(); // empty holder if there are some old clones
$('.prodDetails').duplicate(numOfClones).appendTo('#addProds').each(function() {
$(this).find("select").each(function() {
if (this.name) {
this.name += cntr;
}
if (this.id) {
this.id += cntr;
}
});
++cntr;
});
// duplicate; fill holder with new clones; the class 'new' is just for styling
});
HTML
<form id="warranty">
<div id="prodDetailsContainer">
<label for="numProd">How many products would you like to register (up to 5) <em>*</em></label>
<select name="numProd">
<option>1</option>
</select>
<ul class="prodDetails" id="prod">
<li>
<label for="Product_category">Product Category <em>*</em></label>
<select name="Product_category" class="category prod-info" style="width: 160px;">
<option value="">- Select Category-</option>
<option value="Cookware">Cookware</option>
<option value="Bakeware">Bakeware</option>
<option value="KitchenTools">Kitchen Tools</option>
<option value="DineEntertain">Dine & Entertain</option>
</select>
</li>
<li style="display: none;" class="subCats">
<label for="Product_type">Product Type <em>*</em></label>
<select name="Product_type" class="product-type prod-info"></select>
<div class="other" style="display: none;">
<label for="Other_Product_Type">Specify Other:: </label>
<input class="text-field" name="Other_Product_Type" />
</div>
</li>
<li style="display: none;" class="subCats">
<label for="Product_size">Product Size <em>*</em></label>
<select name="Product_size" class="product-size prod-info" style="width: auto; outline: none; width:120px;">
<option value="">- Select Size -</option>
<option value="1_QT">1 qt.</option>
<option value="2_QT">2 qt.</option>
<option value="3-half_QT">3 ½ qt.</option>
<option value="4-half_QT">4 ½ qt.</option>
<option value="5_QT">5 qt.</option>
<option value="Other">Other</option>
<option value="NA">Not Applicable</option>
</select>
<div class="other" style="display: none;">
<label for="Other_Product_Size">Specify Other:: </label>
<input class="text-field" name="Other_Product_Size" />
</div>
</li>
<li style="display: none;" class="subCats">
<label for="Product_color">Product Color <em>*</em></label>
<select name="Product_color" class="product-color prod-info">
<option value="">- Select Color -</option>
<option value="Amethyst">Amethyst</option>
<option value="Aubergine">Aubergine</option>
<option value="Black Onyx">Black Onyx</option>
<option value="Caribbean">Caribbean</option>
</select>
</li>
</ul>
<div id="addProds"></div>
</div>
</form>
I figured it out- the solution was to move the variables inside the .on function, and also make the selectors more specific so that only the next fields were affected by a change in the previous (instead of all of them).
$('select').live('change', function() {
var category = $('select[name^="Product_category"]');
var productType = $('select[name^="Product_type"]');
var catSelected = $(this).val();
var nextProdType = $(this).parent("li").next("li.subCats").children('select[name^="Product_type"]');
var nextSizeColor = $(this).parent("li").next("li.subCats").children('.product-size, .product-color');
$(this).parent("li").next("li.subCats").fadeIn('fast'); /*Fades in next option once selection has been made*/
if($(this).is(category)) {
nextProdType.empty();
nextSizeColor.prop('selectedIndex',0);
$.each(prods[catSelected], function (key, value) {
nextProdType
.append($("<option></option>")
.attr("value", value)
.attr("name", value)
.text(value));
});
}
if($(this).is(productType)) {
nextSizeColor.prop('selectedIndex',0);
}
});
Here is a working fiddle in case this will be helpful to others in the future:
http://jsfiddle.net/xJyL7/1/

Div's visibility with javascript - problem

I am trying to use div's to display content on my page. This is controlled with an onchange element in a select menu. It works perfectly but the problem is I want one div to close when another one is opened. The div's open fine but it does not close the others. An example code is below. What am I doing wrong?
JavaScript:
if(document.getElementById('catgry').value == '01'){
document.getElementById('post04').style.visibility = "visible";
document.getElementById('post04').style.display = "";
document.getElementById('post07').style.visibility = "hidden";
document.getElementById('post07').style.display = "none";
}else if(document.getElementById('catgry').value == '02'){
document.getElementById('post02').style.visibility = "visible";
document.getElementById('post02').style.display = "";
document.getElementById('post04').style.visibility = "hidden";
document.getElementById('post04').style.display = "none";
document.getElementById('post07').style.visibility = "hidden";
document.getElementById('post07').style.display = "none";
}
HTML:
<div id="post04" style="visibility:hidden; display:none;">
<table class="posttb"><tr>
<td width="30%">Author</td>
<td><input type="text" name="author" size="30" class="postfd"></td>
</tr>
</table>
</div>
Hard to say without seeing your markup, but it could be as simple as this:
Example: http://jsfiddle.net/jtfke/
var posts = document.getElementById('posts').children;
document.getElementById('catgry').onchange = function() {
for( var i = 0, len = posts.length; i < len; i++ ) {
posts[ i ].style.display = (i == this.selectedIndex) ? 'block' : '';
}
};
example html
<select id='catgry'>
<option value='post01'>post 1</option>
<option value='post02'>post 2</option>
<option value='post03'>post 3</option>
<option value='post04'>post 4</option>
</select>
<div id='posts'>
<div>post 1 content</div>
<div>post 2 content</div>
<div>post 3 content</div>
<div>post 4 content</div>
</div>
Consider using jQuery and the jQuery accordion
http://jqueryui.com/demos/accordion/
You can do it with pure Javascript and some looping.
<form method="post" action="#">
<select id="selectMenu">
<option id="option1" value="option 1">option 1</option>
<option id="option2" value="option 2">option 2</option>
<option id="option3" value="option 3">option 3</option>
</select>
</form>
<div id="div1" class="postDiv">Div 1</div>
<div id="div2" class="postDiv">Div 2</div>
<div id="div3" class="postDiv">Div 3</div>
<script type="text/javascript">
init();
function init()
{
addListeners();
}
function addListeners()
{
document.getElementById("selectMenu").onchange = selectChange;
}
function selectChange(evt)
{
for(var i=0;i<evt.currentTarget.length;i++)
{
if(i == evt.currentTarget.selectedIndex)
{
adjustDivs(i+1, evt.currentTarget.options);
}
}
}
function adjustDivs(optionId, options)
{
document.getElementById("div" + optionId).style.display = "block";
for(var i=0;i<options.length;i++)
{
if(i != (optionId-1))
{
document.getElementById("div" + (i+1)).style.display = "none";
}
}
}
</script>
http://jsfiddle.net/hGxfS/
Install jquery;
Use this code as html markup for select box . remember to specify id=visibiitySelector and providean attribute "_showelement" for each option value, that matches with the id of the div you want to display if option is selected
<select id="visibilitySelector">
<option value="whatever" _showelement="post01">whatever</option>
<option value="whatever" _showelement="post02">whatever</option>
</select>
Copy this function into the javascripts of the page
$(document).ready(function(){
$('#visibilitySelector').change(function(){
var showelement = $('#visibilitySelector option:selected').attr('_showelement');
$('div.showhide').not('#' + showelement ).hide();
$('#' + showelement ).show();
});
});
Code the divs as below, remembering to provide class "showhide"
<div id="post01" class="showhide">
</div>
<div id="post01" class="showhide">
</div>
<div id="post01" class="showhide">
</div>

Categories

Resources