0

hi can anyone tell me what should i write so that on every iteration of for loop option's value changes and i get one by one option's value. following is the code:

for (var i=1; i<4; i++)
 {
   $("#mydropdown_for_month option[value=i]").attr('hidden','hidden'); 
 } 

for example dropdown has 10 values but i want to hide those options which have the values dynamically changed by for loop so i write " option=i " but it is not working. I mean i want to write variable i. how can i do that

1
  • 2
    $('#mydropdown_for_month option[value="+i+"]").attr('hidden', 'hidden'); Commented Jul 25, 2011 at 13:04

5 Answers 5

2

You need to call i as a variable:
[EDIT 2] Thanks to ThiefMaster, here is a nicer code :

for (var i=1; i<4; i++) { 
   $("#mydropdown_for_month option[value=" + i + "]").prop('hidden', true);
}

[EDIT] Without hidden attribute (which exists only in HTML5) - thanks to Phil and ThiefMaster:

for (var i=1; i<4; i++) { 
   $("#mydropdown_for_month option[value=" + i + "]").hide();
}
Sign up to request clarification or add additional context in comments.

3 Comments

There is no attribute hidden.
@ThiefMaster: correct, thanks ! i just copy-pasted the code from the OP. i'll correct it
Actually, the HTML5 hidden attribute probably has a property behind it, so you could use .prop('hidden', true) which is nicer than setting an attribute with a nonsense value.
1

You can try, $("#mydropdown_for_month option").eq(i).hide() didn't test it, just a guess :D

1 Comment

this would probably work if the options are in the same order as their values. But indeed, that would be smarter
1

Try

"option=" + i

So that the 'i' is a variable rather than a string

Comments

1

You don't have to use a loop here (actually, loops are quite rare when you're using jQuery in the way it was designed for).

You can use the slice() method to match a subset of the <option> elements and hide them all at the same time:

$("#mydropdown_for_month option").slice(1, 4).hide();

Comments

0
for (var i=1; i<3; i++)
 {    
   $("#mydropdown_for_month").find('option[value="'+i+'"]').hide();

 } 

here is the demo http://jsfiddle.net/DBXGe/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.