3
\$\begingroup\$

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);
});
\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

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
\$\endgroup\$
0
0
\$\begingroup\$

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.

\$\endgroup\$
0

Your Answer

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

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