79b4825afe5c22c7d6226037ac81ee69

Hi Everyone,

I'm changing the time by 1 hour in the second selectbox, based on what's selected in the first selectbox.

The code is working perfectly fine, you can paste it in your texteditor and fire it up in your webbrowser to see how it works.

The code is just a bit cluttered. So any (better) suggestions are welcome...

[html]

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>

<select id="mySelect">
  <option value="8">08:00</option> 
  <option value="9">09:00</option> 
  <option value="10">10:00</option>
</select> 


<select id="mySelect_2">
  <option value="8">08:00</option> 
  <option value="9">09:00</option> 
  <option value="10">10:00</option>
</select> 


<script>

$("#mySelect").change(function(){
    var selected = $(this).attr("selectedIndex");
    var max_select_box = $("#mySelect option").length -1;
  
      if (selected == max_select_box) { 
           $("#mySelect2").attr("selectedIndex", selected);
      } else {
           $("#mySelect2").attr("selectedIndex", selected + 1);
      }
  
      $("#mySelect_2").change(function(){
      var selected = $(this).attr("selectedIndex");
      var currently_selected = $("#mySelect").attr("selectedIndex");

  
      if (selected < currently_selected) { 
           $("#mySelect").attr("selectedIndex", selected);
      }
  });
});

</script>
</body>
</html>

Refactorings

No refactoring yet !

D41d8cd98f00b204e9800998ecf8427e

lomax

April 19, 2010, April 19, 2010 18:59, permalink

No rating. Login to rate!

If you insist on jQuery, i reckon you could clean it up a lot just by setting the 2nd change method at runtime, rather than event time. After that, it's really just about naming and coding style. I might do it this way:

$("#mySelect").change(function(){
    var selected = $(this).attr("selectedIndex");
    var target = Math.min(selected+1,$("#mySelect option").length-1);
    $("#mySelect2").attr("selectedIndex", target);
});

$("#mySelect_2").change(function(){
    var selected = $(this).attr("selectedIndex");
    var currently_selected = $("#mySelect").attr("selectedIndex");
  
    if (selected < currently_selected) { 
       $("#mySelect").attr("selectedIndex", selected);
    }
  }
});
52842ef7314957521eec702c35b43084

yarış oyunları

April 23, 2010, April 23, 2010 12:49, permalink

No rating. Login to rate!

It's really just about naming and coding style.

$("#mySelect").change(function(){
    var selected = $(this).attr("selectedIndex");
    var max_select_box = $("#mySelect option").length -1;
  
      if (selected == max_select_box) { 
           $("#mySelect2").attr("selectedIndex", selected);
      } else {
           $("#mySelect2").attr("selectedIndex", selected + 1);
      }

Your refactoring





Format Copy from initial code

or Cancel