geeky

jQuery selection copy

Here’s a jQuery scenario I encountered today at work. I found the solution interesting.

I have 2 identical selection dropdowns. When I select from the first one I want to copy the selection value into the second. However, I also have a change event attached to the second selection dropdown. In order to make sure I trigger the second dropdown’s change event, instead of doing:

$('#firstSelection').change(function() {
	$('#secondSelection').val($(this).val());
});

I have to do the following:

$('#firstSelection').change(function() {
	var selectedIndex = $(this).attr('selectedIndex');
	$('#secondSelection').attr('selectedIndex', selectedIndex).change();
});

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s