Adding a group of options to a list of options using JQuery

I have the following HTML code (do not mark the end tags with <\option>

) generated by Lotus Domino.

<select name="Fault" class="textbox">
<option>Single Light Out
<option>Light Dim
<option>Light On In Daytime
<option>Erratic Operating Times
<option>Flashing/Flickering
<option>Causing Tv/Radio Interference
<option>Obscured By Hedge/Tree Branches
<option>Bracket Arm Needs Realigning
<option>Shade/Cover Missing
<option>Column In Poor Condition
<option>Several Lights Out (please state how many)
<option>Column Leaning
<option>Door Missing/Wires Exposed
<option>Column Knocked Down/Traffic Accident
<option>Lantern Or Bracket Broken Off/Hanging On Wires
<option>Shade/Cover Hanging Open
<option>Other
</select>

      

Using JQuery I want to convert this HTML after the document is loaded: Adding optgroup after the 11th option and also adding a closing tag </option>

<select name="Fault" class="textbox">
<option>Single Light Out</option>
<option>Light Dim</option>
<option>Light On In Daytime</option>
<option>Erratic Operating Times</option>
<option>Flashing/Flickering</option>
<option>Causing Tv/Radio Interference</option>
<option>Obscured By Hedge/Tree Branches</option>
<option>Bracket Arm Needs Realigning</option>
<option>Shade/Cover Missing</option>
<option>Column In Poor Condition</option>
<option>Several Lights Out (please state how many)</option>
    <optgroup label="Urgent Reasons">
<option>Column Leaning</option>
<option>Door Missing/Wires Exposed</option>
<option>Column Knocked Down/Traffic Accident</option>
<option>Lantern Or Bracket Broken Off/Hanging On Wires</option>
<option>Shade/Cover Hanging Open</option>
<option>Other</option>
    </optgroup>
</select>

      

+3


source to share


2 answers


With :nth-child(n+7)

you select all children over index 7.

$('option:nth-child(n+7)').wrapAll('<optgroup  label="Urgent Reasons">');

      



See JsFiddle

Without closing the <option>

invalid HTML, so I'm not sure how this works with jQuery, since it actually does correct DOM manipulation. I suggest you fix these tags not closing before HTML processing.

+3


source


To fix the parameter tags if you can read the HTML code into a string that will allow you to perform the replacement. Something like (this is a javascript example as we are talking about jQuery)



raw_code.replace(/(<option>.+)/g, "$1</option>\n");

      

+2


source







All Articles