jQuery empty select but not the first option

I’m loading two dropdowns using jQuery AJAX in WordPress. I’m getting AJAX data as a string, and I’m simply appending those <option>s to my <select> field. It’s working fine. But every time it’s not clearing the previous append. So it’s actually adding repeating options.

So I made a change, I added empty() to the <select> field:

Read More
jQuery.ajax({
    type: 'POST',
    url: ajaxurl,
    data: {"action": "load_product",
            "company_id": company_id
          },
    success: function (data) {
        jQuery('#company-products').empty().append( data );
    }
});

But I have an empty value option in the select field by default, it’s simply removing that one too.

<select name="product" id="company-products" class="form-control" required>
    <option value=""><?php _e( 'Select a product', 'textdomain' ); ?></option>
</select>

How can I append the additional options, but not empty even with the empty (value="") one.
Please note, I know I can pass the empty field from jQuery, but for translation purpose I can’t pass that from there. So I want a solid solution using jQuery, while the first option stays.

I even tried changing it to:

jQuery('#company-products').not(':first-child').empty();
jQuery('#company-products').append( data );

It’s not working, even not appending anything. 🙁

Related posts

Leave a Reply

3 comments

  1. Try using nextAll() – to remove all elements after the empty <option>

    var emptyOp = $('#company-products :first-child');
    
    emptyOp.nextAll().remove();
    emptyOp.after(data);
    

    Sample Demo

    There are many other selectors you can use,

    $('#company-products :gt(0)').remove();
    $('#company-products').append(data);
    

    OR

    $('#company-products :not(:first-child)').remove();
    $('#company-products').append(data);
    
  2. What if you just try to write

    <?php _e( 'Select a product', 'textdomain' ); ?>
    

    JS variable and pass you option as you write, from jQuery?

    var selectOption = '<?php _e( 'Select a product', 'textdomain' ); ?>';