I have a dropdown list ,every option of the list have a year and a month . I want to sort a select options according to year or month or both that are . so I can display options sorted by year or month or year and month together or show everything . I have the following event :
$('#years,#months').bind('change', function () {
y = $('#years').val();
m = $('#months').val();
$('#files > option').each(function () {
$(this).show();
});
$('#files > option').each(function () {
string = $(this).text();
//first situation
if (y == 'All' && m == 'All')
$(this).show();
// second situation
else if ((y == 'All') && string.indexOf(m) == -1)
$(this).hide();
//third situation
else if ( string.indexOf(y) == -1 && m == 'All')
$(this).hide();
// fourth situation
else if (string.indexOf(y) == -1 || string.indexOf(m) == -1)
$(this).hide();
});
});
with html code :
<select id='years'>
<option value='All'>All</option>
<option value='2013'>2013</option>
<option value='2012'>2012</option>
</select>
<select id='months'>
<option value='All'>All</option>
<option value='Feb'>Feb</option>
<option value='Jan'>Jan</option>
</select>
<br/>
<br/>
<select id='files' siz='10'>
<option value='0'>sdgsdfsadfsd1-2013-Feb-1212</option>
<option value='1'>fsadfadsfadsfadsf2-2012-Feb-123123</option>
<option value='2'>fsadfadsfadsfadsf3-2012-Jan-123123</option>
<option value='3'>fsadfadsfadsfadsf4-2013-Jan-123123</option>
<option value='4'>fsadfadsfadsfadsf5-2012-Feb-123123</option>
<option value='5'>fsadfadsfadsfadsf6-2013-Feb-123123</option>
<option value='6'>fsadfadsfadsfadsf7-2013-Feb-123123</option>
<option value='7'>fsadfadsfadsfadsf8-2013-Jan-123123</option>
<option value='8'>fsadfadsfadsfadsf9-2012-Jan-123123</option>
<option value='9'>fsadfadsfadsfadsf10-2013-Feb-123123</option>
<option value='10'>fsadfadsfadsfadsf11-2012-Feb-123123</option>
</select>
second and third situations are not working !! it deals with the two conditions (true && false) , (false && true ) as they are same values ! I have no idea why ! here's a Demo
Your logic is wrong; the last condition is being evaluated when it shouldn't be. (For instance: if y == 'All'
and also string.indexOf(m) >= 0
). Try this instead:
$('#files > option').each(function () {
var string = $(this).text();
var show;
if (y == 'All') {
show = m == 'All' || string.indexOf(m) >= 0;
} else if (m == 'All') {
show = string.indexOf(y) >= 0;
} else {
show = string.indexOf(y) >= 0 && string.indexOf(m) >= 0;
}
if (show) $(this).show();
else $(this).hide();
});
'All'
. (The case where they were both 'All'
was covered by the first condition, but the case where one is 'All'
and the other was valid satisfied the fourth hiding condition because the options did not contain the word 'All'
. - Ted Hopp 2013-03-05 19:46
on
as of jQuery 1.7+ is preferrend tobind
. Then, explain better what's the matter (and where!). Useconsole.log(expression)
oralert(exp)
to verify condition and debug - steo 2013-03-05 18:31