user1464139
user1464139

Reputation:

How can I remove part of a string with javascript or jQuery?

I have the following:

$('.select-topic').click(function () {
    if ($(this).attr('data-list') == "N") {
        $(this).attr('data-list', 'Y')
        var topicSelectHtml = $('#TopicID').html();
        $(this).html(topicSelectHtml);
        $(this).attr('data-clicked', 'Y')
    } 

When a user clicks on a new topic then it takes the $('#TopicID').html(); and uses this as the html for topicSelectHtml.

This works but what I need to do is to remove a section of the $('#TopicID').html(); that's not required for the new select. Here is my select html:

<select name="TopicID" id="TopicID"><optgroup label="Admin">
<option value="00">All Topics</option>
<option value="050002">Classes</option>
</optgroup>
xxxxxxxxx</select>

How can I remove the <optgroup label="Admin"> ... </optgroup> section? Note there are no line feeds in my html.

Upvotes: 0

Views: 87

Answers (2)

y2ok
y2ok

Reputation: 658

Add id to each optgroup and then use remove() function.

See example here - http://jsfiddle.net/ue2KJ/ .

If you like, you can avoid adding id to element, but if you will have more than one type of same element, then it may cause problems.

To remove first element just use -

$(this).children("optgroup:first").remove();

Upvotes: 0

Esailija
Esailija

Reputation: 140220

var topicSelectHtml = $('#TopicID').clone().find("optgroup:first").remove().end().html();

Upvotes: 1

Related Questions