jQuery: How to set one <select> element to the value of another (using onchange equivalent)

Say you have an HTML <select> form element and you want to set another <select> element equal to the first one when it changes. Here’s an easy way to do so with jQuery:

$('#id_of_select1').change(function() {
    var select1_value = $(this).val();
    $('#id_of_select2').val(select1_value);
});

—————-
Now playing: Drexciya – Astronomical Guidepost
via FoxyTunes

jQuery: How to get the ID of an element.

Say you want to know the ID of an element using jQuery. You can achieve this easily using jQuery’s attr() method:

var currentId = $('#element').attr('id');

But this is fairly useless, because it requires you to already know the ID of the element that you want. Usually you’ll want to find out the ID if you don’t already know it — given a jQuery ‘this‘ object:

var currentId = $(this).attr('id');

This will only work provided that you have a valid jQuery object $(this) that you are working with, eg:

$(document).ready(function() {
  $('input.text').focus(function() {
    $('input.text').removeClass('onFocus'); /* remove focus state from all input elements */
    $(this).addClass('onFocus'); /* add focus state to currently clicked element */
    var currentId = $(this).attr('id');
  });
};

Using the code above, you will now know the ID of the currently focused input element. This can come in handy later on if you want to perform further actions on the element.

—————-
Now playing: Amon Tobin – Precursor (feat. Quadraceptor)
via FoxyTunes