Question

I am trying to make a 2nd version of a classic drop down menu for the mobile version, by copying it's elements and placing them in a select box with this code, but I wish I keep the original menu also, not replace it, just copy it in the select box. I will then hide it and make it visible only to mobile devices.

So my question is how can I also keep the original menu and just copy it to the select box? I am sorry but I have to ask like this as I am just starting to learn jquery..

$('table.topMenu tr').each(function(){
var list=$(this),
    select=$(document.createElement('select')).insertBefore($(this).hide()).change(function(){
  window.location.href=$(this).val();
});
$('>td a', this).slice(2).each(function(){
  var option=$(document.createElement('option'))
   .appendTo(select)
   .val(this.href)
   .html($(this).html());

  if($(this).parent().attr('id') === 'tm_active'){
    option.attr('selected','selected');
  }
});

});
Was it helpful?

Solution

Seems like the only thing that's wrong with your code is that you're trying to select some descendant elements in an odd way.

$('table.topMenu tr').each(function(){
var list=$(this),
    select=$(document.createElement('select')).insertBefore($(this).hide()).change(function(){
  window.location.href=$(this).val();
});

// You need to get the child <td>'s of your list, which you can do using .find()
// on the element you want to find child elements in
list.find('td a', this).slice(2).each(function(){
  var option=$(document.createElement('option'))
   .appendTo(select)
   .val(this.href)
   .html($(this).html());

  if($(this).parent().attr('id') === 'tm_active'){
    option.attr('selected','selected');
  }
});

});

Here's a jsfiddle of this code working http://jsfiddle.net/andyface/T2k6w/

Hope this does what you need it to

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top