1

For some reason, some of the selections work but most don't. I can't figure out what I am doing wrong, maybe you can help? Here is a live demo on codepen: http://codepen.io/AlexBezuska/pen/dHmge My jQuery:

$('#ddlOffice option').hide();
    $('#ddlBusiness').change(function(){
      var selectedBusiness = $( "#ddlBusiness option:selected").val();
      selectedBusiness = parseFloat(selectedBusiness);
      $('#ddlOffice option').hide();
      $('#ddlOffice option[value="'+selectedBusiness+'"]').show();
      $('#txtBusiness').val($( "#ddlBusiness option:selected").text());
    });

     $('#ddlOffice').change(function(){
      $('#txtOffice').val($( "#ddlOffice option:selected").text());
    });

Bonus points: I would like to do this without jQuery, if anyone has tips on an easy way of doing the showing and hiding in raw javascript or wants to do a fork without jQuery would be awesome,

Thanks!

2
  • What exactly you want to do? I think you want users to use one select box to select number of businesses and then change options of another select box based on that. Am I right? Commented Oct 5, 2013 at 13:55
  • Yes, exactly. Now I would just like to convert it to raw javascript and not depend on jQuery for this since its the only javascript the app uses. Commented Oct 6, 2013 at 14:37

2 Answers 2

1

I figured out a better way:

var options = $("#ddlOffice").html();
$("#ddlBusiness").change(function(e) {
    var selectedValue = $("#ddlBusiness :selected").val();
    $("#ddlOffice").html(options);
    $('#ddlOffice :not([value="'+selectedValue+'"])').remove();
});

Now Working CodePen: http://codepen.io/AlexBezuska/pen/dHmge

Sign up to request clarification or add additional context in comments.

Comments

0

I re-wrote your jQuery code and now it seems to be working for me (fiddle):

$(function() {
    $('#ddlOffice option').hide();
    $('#ddlBusiness').change(function(){
        var selectedBusiness = parseFloat($("#ddlBusiness").val());
        $('#ddlOffice option').hide();
        $('#ddlOffice option[value="' + selectedBusiness + '"]').show();
        $('#txtBusiness').val($("#ddlBusiness option:selected").text());
    });
    $('#ddlOffice').change(function(){
        $('#txtOffice').val($(this).find("option:selected").text());
    });
});

Please consider:

  1. If you are putting your JavaScript before your HTML, remember to use document.ready or $(function(){ }) in jQuery.
  2. You can't have options with same values as you did in #ddlOffice select. I mean what's the purpose of using options that will return same values?!
  3. You haven't closed one of your options in second select.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.