I'm working on an ajax select box that loads file content into the closest div area Demo. I'm using the script below to change the first option text "Select" to "Hide" when the ajax content is loaded.However, I can't get the "Hide" text to change back to "Select" after on clicking it.
Code:
var area = $(".selectboxarea");
$(".searchselectbox").on('change', function (e) {
area.empty();
var selected = $(this).find('option:selected');
var loadfile = selected.data('file');
if (loadfile) {
$(this).next('.selectboxarea').load(loadfile);
$(this).find('option:contains("Select")').text("Hide");
} else {
window.location.href = $(this).val();
}
});
HTML
<select class="searchselectbox">
<option value="#">Select</option>
<option data-file="fans.php">Fans</option>
<option data-file="stars.php">Stars</option>
</select>
<div class="selectboxarea"></div>
Should I use this line in a function?
$(this).find('option:contains("Hide")').text("Select");
You can add a class to the <option>
that needs its text to be changed, like:
<option value="#" class="select">Select</option>
And then the Js would be
var $this = $(this);
var selected = $this.find('option:selected');
var loadfile = selected.data('file');
if (loadfile) {
$this.next('.selectboxarea').load(loadfile);
$this.find('.select').text('Hide');
$this.find('.select').toggleClass('hide');
} else if (selected.hasClass('hide')) {
selected.text('Select');
selected.toggleClass('hide');
} else {
window.location.href = $(this).val();
}
When there's a file data attribute, the text changes and class "hide" is added on the first option
. After that, if the selected option has the class "hide", the text is changed and the class is removed.
Also, I'm using var $this = $(this);
to cache the jQuery variable, since it's a good practice to not hace the script look for them every time they are needed.