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:
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. 🙁
Try using
nextAll()
– to remove all elements after the empty<option>
Sample Demo
There are many other selectors you can use,
OR
Don’t use
empty()
just useremove()
.hope this will works for you
What if you just try to write
JS variable and pass you option as you write, from jQuery?