Abram
Abram

Reputation: 41874

How would this line be re-written in plain javascript?

I have the following code, and I would like to manipulate it slightly, but feel more familiar doing so in plain javascript:

jQuery ->
  states = $('#person_state_id').html()
  console.log(states)
  $('#person_country_id').change ->
    country = $('#person_country_id :selected').text()
    options = $(states).filter("optgroup[label=#{country}]").html()
    console.log(options)
    if options
      $('#person_state_id').html(options)
    else
      $('#person_state_id').empty()

Thanks!

Upvotes: 0

Views: 93

Answers (3)

OptiPessiProgrammer
OptiPessiProgrammer

Reputation: 2336

Here is a handy JS to Coffee converter that I use often and it works great.

http://js2coffee.org/

Upvotes: 0

VisioN
VisioN

Reputation: 145388

Well, for me the code described with the words "in plain javascript" should look something like that:

var states = document.getElementById('person_state_id').cloneNode(true);
document.getElementById('person_country_id').onchange = function() {
    var country = this.value;
    var childs = states.childNodes;
    for (var i in childs) {
        if (childs[i].label == country) {
            var options = childs[i].innerHTML;
            document.getElementById('person_state_id').innerHTML = options ? options : "";
        }
    }
};​

Check the example here: http://jsfiddle.net/LmWqA/

Upvotes: 4

stewe
stewe

Reputation: 42612

jQuery(function() {
  var states;
  states = $('#person_state_id').html();
  console.log(states);
  return $('#person_country_id').change(function() {
    var country, options;
    country = $('#person_country_id :selected').text();
    options = $(states).filter("optgroup[label=" + country + "]").html();
    console.log(options);
    if (options) {
      return $('#person_state_id').html(options);
    } else {
      return $('#person_state_id').empty();
    }
  });
});

Upvotes: 2

Related Questions