I have this Show/Hide select box ( JS Fiddle ) that gets a classname from a selected option and hides a corresponding unordered list item. I am at a loss to use replace()
to replace the text Hide
with Show
or vice versa when an option is clicked.(eg Show Month should become Hide Month on click.)
I also want to change all the options back to Hide
when I click the Show All option.
When I used findoption.replace('Hide','Show');
I got this Uncaught TypeError: undefined is not a function
error. Can anyone show me how to do that? Any help would be appreciated.
JS Code:
$(document).ready(function(){
$(".showhidelist").change(function() {
$this = $(this);
var findoption = $this.find('option:selected');
var selected = findoption.data('hide');
var show_hide_li = $("."+selected);
if (show_hide_li.css("display") == "none") {
show_hide_li.show();
/* Want to Replace the text Hide with Show */
}
else if (show_hide_li.is(':visible')){
show_hide_li.hide();
/* Want to Replace the text Show with Hide */
}
else if (selected == "Reset") {
$('li').show();
/* Want to Replace the text Show with Hide if it's true */
}
});
});
HTML
<select class="showhidelist">
<option data-hide="Reset">Show All</option>
<option data-hide="year">Hide Year</option>
<option data-hide="month">Hide Month</option>
<option data-hide="day">Hide Day</option>
</select>
<ul id="list">
<li class="year">2004</li>
<li class="month">Feb</li>
<li class="day">17</li>
<ul>
You are not getting the text()
into the replace, and you could use the function that .text() has to replace the text.
findoption.text(function(_,text){ return text.replace('Hide', 'Show')});
Change the word 'Hide' or 'Show' depend on what you want.
Update:
I read in caspian comment, that you problem now is that you could not re-click an option clicked, try restarting the select to first option like:
$(".showhidelist").prop('selectedIndex',0);
findoption is returns a jquery array, so you would need to access the first element there. I think the following will achieve what you're looking for (as far as the selected element goes).
findoption[0].innerHTML = findoption[0].innerHTML.replace('Show','Hide');
I'm not sure what you're really doing - this gets a little quirky, since you have the show/hide all and you'll have to go through the whole list to update them when you do. Also - you aren't getting a selected event when you re-select what's already selected.
UPDATE: this includes how to update all items in the list using each()
jsfiddle: http://jsfiddle.net/hk4wg/15/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.