Search code examples
javascriptprototype

How can I remove text and create class from its value with Prototype?


I want to remove from the option text the double bracketed items and take the innertext inside the double brackets and create a class in each option with the value. How would you do this in Prototype?

<select id="attribute969">     
<option value="">Choose an Option...</option>
<option value="340">White [[white]]</option>
<option value="341">White [[white]]</option>
<option value="342">Blue PMS 801 [[pms801]]</option>
<option value="343">Blue PMS 801 [[pms801]]</option>
</select>

Example Below:

<select id="attribute969">     
<option value="">Choose an Option...</option>
<option value="340" class="white">White</option>
<option value="341" class="white">White</option>
<option value="342" class="pms801">Blue PMS 801</option>
<option value="343" class="pms801">Blue PMS 801</option>
</select>

Solution

  • //Here is my brief and killer trial, the way to do it with Prototype's Power!
    $A($('attribute969').options).each(function(s,index)
    {
       $(s).toggleClassName($(s).innerHTML.gsub(/.*\[{2}/,'').gsub(/\]{2}.*/,''));
       $(s).innerHTML = $(s).innerHTML.gsub(/\[{2}.*/,'');
    });
    

    Check this code snippet in action live here...