Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

My objective has been to build a custom dropdown like the one on Amazon's search scope selector. I do this by positioning a styleable element on top of a standard select list. I then use jQuery to keep the styleable element in sync with the select list. My code works fine, but I would love to learn how to do it cleaner. Currently I do the syncing twice - on page load and on change. Is it possible to refactor my code using on()? (or similar).

prev() is the styleable element.

// Sync is performed on page load
var $select = $('select');
$select.each(function(index, value) {
  var optionText = $(this).find('option:selected').text();
  $(this).prev().text(optionText);
});

// Sync is performed on change event
$('select').change(function() {
  var optionText = $(this).find('option:selected').text();
  $(this).prev().text(optionText);
});
share|improve this question
add comment

2 Answers

up vote 0 down vote accepted

Instead of rewriting the code you can just trigger the change event after you bind it which will cause it to sync on page load

$('select').change(function() {
  var optionText = $(this).find('option:selected').text();
  $(this).prev().text(optionText);
}).trigger('change'); // <-- trigger change
share|improve this answer
    
Thats excatly what Im looking for! –  tolborg Jan 28 '13 at 22:43
add comment

It's probably a bit too heavyweight for your task, but have you considered using knockoutJS for it? It's a quite powerful MVVM javascript framework that uses the notion of Observables to keep UI in sync with underlying data model.

share|improve this answer
    
Thats too much. Thanks though. –  tolborg Jan 28 '13 at 13:40
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.