Search code examples
javascriptprototypejs

PrototypeJS not removing select element


Given the following HTML, I'm trying to remove all form elements. The problem I'm encountering is that the select element is not being removed, but rather the first option in it is being removed each time the remove code is called. See http://jsfiddle.net/b8FfT/

HTML

<fieldset>
  <div id="order_history_block">
    <div id="history_form" class="order-history-form">
      <div>Add Order Comments</div>
      <span class="field-row">
        <label class="normal" for="history_status">Status</label><br>
        <select name="history[status]" class="select" id="history_status">
          <option value="processing">Ok to Ship</option>
          <option value="pending" selected="selected">Pending</option>
        </select>
      </span>
      <span class="field-row">
          <label class="normal" for="history_comment">Comment</label>
          <textarea name="history[comment]" rows="3" cols="5" style="height:6em; width:99%;" id="history_comment"></textarea>
      </span>
      <div class="f-left">
        <input name="history[is_visible_on_front]" type="checkbox" id="history_visible" value="1"><label class="normal" for="history_visible"> Visible on Frontend</label>
      </div>
      <div class="f-right">
        <button id="id_79ae3bd75916862b0245fbcb3343d24e" title="Submit Comment" type="button" class="scalable save" onclick="doStuff()" style=""><span><span><span>Submit Comment</span></span></span></button>
      </div>
      <div class="clear"></div>
    </div>
    <div class="divider"></div>
    <!-- ... -->
  </div>
</fieldset>

JS

var a = $('order_history_block').parentNode;
$(a).select('input', 'select', 'textarea').invoke('remove');

Solution

  • So the HTMLSelectElement prototype (not the framework) has its own remove() method and when you call remove() on <select>s it does not traverse up the prototype chain to the remove() method of HTMLElement added by PrototypeJS.

    2 options for you

    $('history_status').parentNode.removeChild($('history_status'));
    

    or

    Element.remove($('history_status'));
    

    I've filed a bug report for this as well

    https://github.com/sstephenson/prototype/issues/122

    EDIT

    Use a CSS selector and the select() method like this

    $('order_history_block').up().select('select').each(function(item){
        Element.remove(item);
    });