Sherwin Flight
Sherwin Flight

Reputation: 2363

Use jQuery to filter a SELECT list

I am trying to figure out how to filter a SELECT list on the fly.

I have a list like this:

<div class="domainreginput" id="domainexisting_domain">
<select id="incartsld">
<option value="example.com">example.com</option>
<option value="example2.com">example2.com</option>
<option value="example.net">example.net</option>
<option value="example.rocks">example.rocks</option>
</select> <input type="submit" value="Click to Continue >>" />
</div>

The list could include domain names with any extension. But for this particular purpose I only want to show domains with certain TLDs. In this example, let's say .com and .net.

So if I provided a list of allowed TLDs, like this:

var allowedTLD = [".com", ".net"];

How can I use jQuery to remove any domains from the SELECT list that don't have a TLD that matches one in the allowed array?

I'm fairly new to jQuery and have tried searching around for an answer to this, but couldn't find anything quite like this.

If it helps any, this is the actual regex used to match allowed domains:

/\.(com|net|org|biz|info|name|tv|cc|me|pro|mobi|cm|co|ws)$/i

Upvotes: 1

Views: 198

Answers (2)

j08691
j08691

Reputation: 208032

Here's one way:

var allowedTLD = [".com", ".net"];
$('#incartsld option').filter(function () {
    return !($.inArray('.'+$(this).val().split('.').pop(), allowedTLD) > -1)
}).remove()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="domainreginput" id="domainexisting_domain">
    <select id="incartsld">
        <option value="example.com">example.com</option>
        <option value="example2.com">example2.com</option>
        <option value="example.net">example.net</option>
        <option value="example.bix">example.biz</option>
    </select>
    <input type="submit" value="Click to Continue >>" />
</div>

Or alternatively:

var allowedTLD = /\.(com|net|org|biz|info|name|tv|cc|me|pro|mobi|cm|co|ws)$/i;
$('#incartsld option').filter(function() {
  return ($(this).val().match(allowedTLD) == null)
}).remove()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="domainreginput" id="domainexisting_domain">
  <select id="incartsld">
    <option value="example.com">example.com</option>
    <option value="example2.com">example2.com</option>
    <option value="example.net">example.net</option>
    <option value="example.bix">example.biz</option>
  </select>
  <input type="submit" value="Click to Continue >>" />
</div>

Upvotes: 4

Frayt
Frayt

Reputation: 1233

Try this:

$.each($('#incartsld > option'), function(index,o)
{
    if(!$(o).val().match(/\.(com|net|org|biz|info|name|tv|cc|me|pro|mobi|cm|co|ws)$/i))
    {
        $(o).remove();
    }
});

I'm not experienced with regex so you may have to alter the if statement slightly.

Upvotes: 0

Related Questions