473,695 Members | 2,884 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to find that a particular option is there in a SELECT element

8 New Member
Hi all,
My page has a SELECT(drop-down list) element and i have to add options dynamically to it.Before adding i have to know whether that option is already there in the drop-down list.

i tried this....
if(myDropDown.o ptions[2].text == "NewYork") {
............
this checks the 3rd option of the drop-down list, but i want to check all the option items.
i can go thru' every option using a for loop like this....
for(i=0;i<optio ns.length;i++)
{
if(myDropDown.o ptions[2].text == "NewYork") {
...........
}

Is this the only way to check whether the option is already there or not?
Is there anything i can try like this....
myDropDown.opti ons.text == "NewYork"

Sorry for elaboration.... Thanks for any replies

-Satya
May 9 '07 #1
11 1597
l1k3kah
2 New Member
are the details of your select is in database?
if yes try to may do while statements and nest it with if statement.

if not try doing it manually by having a javascript code like

if (document.formn ame.selectname. options[index].value=="the value needed")
{
}

something like that...

Sorry can't help that much!
God Bless You!
May 9 '07 #2
satyanarayana49
8 New Member
Thanks for ur reply,
but my population is not from the database and my requirement is to check whether that particular option is there on the browser side itself.
May 9 '07 #3
acoder
16,027 Recognized Expert Moderator MVP
Hi all,
My page has a SELECT(drop-down list) element and i have to add options dynamically to it.Before adding i have to know whether that option is already there in the drop-down list.

i tried this....
if(myDropDown.o ptions[2].text == "NewYork") {
............
this checks the 3rd option of the drop-down list, but i want to check all the option items.
i can go thru' every option using a for loop like this....
for(i=0;i<optio ns.length;i++)
{
if(myDropDown.o ptions[2].text == "NewYork") {
...........
}

Is this the only way to check whether the option is already there or not?
Is there anything i can try like this....
myDropDown.opti ons.text == "NewYork"

Sorry for elaboration.... Thanks for any replies

-Satya
Yes, you'll have to loop through, but you can break out of the loop once you find a match.
May 9 '07 #4
pbmods
5,821 Recognized Expert Expert
Is this the only way to check whether the option is already there or not?
To speed things up a little bit, you can break out of the loop once you find the matching value. I.e.:

Expand|Select|Wrap|Line Numbers
  1. var present = true;
  2. for(i=0;(i<options.length) && present;i++)
  3.     present = (myDropDown.options[i].value == "NewYork");
  4.  
  5. if(! present) {
  6.     //  I'm sure you know what goes here.
  7. }
  8.  
Now on the other hand, you could do something like this:

Expand|Select|Wrap|Line Numbers
  1. var myOptions = null;  // Declared globally at start of execution.
  2.  
  3. .
  4. .
  5. .
  6.  
  7. function createOptionOrWhateverYouCalledIt(newValue, newText) {
  8. .
  9. .
  10. .
  11. // Load existing options (if we haven't done so already).
  12. if(! myOptions)
  13.     for(var i = 0; i < myDropDown.options.length; i++)
  14.         myOptions[myDropDown.options[i].value] = true;
  15. }
  16.  
  17. if(! myOptions[newValue]) {
  18.     // Create the new option.
  19.  
  20.     // Cache the new option.
  21.     myOptions[newValue] = true;
  22. }
  23.  
May 10 '07 #5
satyanarayana49
8 New Member
To speed things up a little bit, you can break out of the loop once you find the matching value. I.e.:

Expand|Select|Wrap|Line Numbers
  1. var present = true;
  2. for(i=0;(i<options.length) && present;i++)
  3.     present = (myDropDown.options[i].value == "NewYork");
  4.  
  5. if(! present) {
  6.     //  I'm sure you know what goes here.
  7. }
  8.  
Now on the other hand, you could do something like this:

Expand|Select|Wrap|Line Numbers
  1. var myOptions = null;  // Declared globally at start of execution.
  2.  
  3. .
  4. .
  5. .
  6.  
  7. function createOptionOrWhateverYouCalledIt(newValue, newText) {
  8. .
  9. .
  10. .
  11. // Load existing options (if we haven't done so already).
  12. if(! myOptions)
  13.     for(var i = 0; i < myDropDown.options.length; i++)
  14.         myOptions[myDropDown.options[i].value] = true;
  15. }
  16.  
  17. if(! myOptions[newValue]) {
  18.     // Create the new option.
  19.  
  20.     // Cache the new option.
  21.     myOptions[newValue] = true;
  22. }
  23.  
Thanks pbmods,
I understand the code u have mentioned.....b ut i don't know really whether it is syntactically correct or not.
and if it is the first time looping through is it OK to use "&& present" in the for loop.
can u correct the syntax and post...
-Satya
May 10 '07 #6
pbmods
5,821 Recognized Expert Expert
but i don't know really whether it is syntactically correct or not.
Which part are ya curious about?

and if it is the first time looping through is it OK to use "&& present" in the for loop.
Yup. We declare present = true on the line above it.
May 10 '07 #7
pbmods
5,821 Recognized Expert Expert
can u correct the syntax and post...
Hm. Now that I'm looking at it, I meant to put this instead:

Expand|Select|Wrap|Line Numbers
  1. var present = false;
  2. for(i=0;(i<options.length) && (! present);i++)
  3.     present = (myDropDown.options[i].value == "NewYork");
  4.  
  5. if(! present) {
  6.     //  I'm sure you know what goes here.
  7. }
  8.  
Since we're trying to determine if the value *is* in the list of options.

The other solution I provided (myOptions object), while requiring a slightly larger memory footprint (we're talking on the scale of maybe 100-200 bytes here), provides the fastest execution that I know of.

Though that code needs one change, too:

Expand|Select|Wrap|Line Numbers
  1. if(! myOptions)
  2.     myOptions = {};
  3.     for(var i = 0; i < myDropDown.options.length; i++)
  4.         myOptions[myDropDown.options[i].value] = true;
  5. }
  6.  
  7.  
May 10 '07 #8
satyanarayana49
8 New Member
Hm. Now that I'm looking at it, I meant to put this instead:

Expand|Select|Wrap|Line Numbers
  1. var present = false;
  2. for(i=0;(i<options.length) && (! present);i++)
  3.     present = (myDropDown.options[i].value == "NewYork");
  4.  
  5. if(! present) {
  6.     //  I'm sure you know what goes here.
  7. }
  8.  
Since we're trying to determine if the value *is* in the list of options.

The other solution I provided (myOptions object), while requiring a slightly larger memory footprint (we're talking on the scale of maybe 100-200 bytes here), provides the fastest execution that I know of.

Though that code needs one change, too:

Expand|Select|Wrap|Line Numbers
  1. if(! myOptions)
  2.     myOptions = {};
  3.     for(var i = 0; i < myDropDown.options.length; i++)
  4.         myOptions[myDropDown.options[i].value] = true;
  5. }
  6.  
  7.  
Thanks pbmods,
I am new to Java Script and I couldn't understand the present variable.Can u explain briefly how it works in our code.
i have an XML file and have to retrieve the particular node texts and add them
to the drop-down.In that XML file 3 or 4 nodes may contain the same texts.So I have to check whether the drop-down already contains the similar text before adding the next option(next node's text).If the drop-down already contains the same text it just does not add that to the drop-down(anyway it retrieves the text already from XML file).Here is my XML .......

<Country>USA
<Table>
<State>Alabam a</State>
<City>Birmingha m</City>
<locationId>2 </locationId>
</Table>
<Table>
<State>Alabam a</State>
<City>Huntsvill e</City>
<locationId>3 </locationId>
</Table>
<Table>
<State>Alaska </State>
<City>Anchorage </City>
<locationId>6 </locationId>
</Table>
<Table>
<State>Alaska </State>
<City>Chignik </City>
<locationId>275 </locationId>
</Table>
<Table>
<State>Alaska </State>
<City>Juneau</City>
<locationId>276 </locationId>
</Table>
-
-
-
-
-
-
</Country>

My requirement is to show States in a drop-down.So from the code i used the drop-down displays Alabama 2 times and Alaska 3 times and so on...
Here is how my code looks like....

optionItem0 = new Option( response, response, false, false);
myDropDown.opti ons[myDropDown.opti ons.length] = optionItem0;

Here response object gets the State node's text.The above code is placed in a for loop so that every State node's text is added to the drop-down.

I have to check whether the state is already there in the drop-down or not.For this purpose i have to write a for loop and an if statement inside the above for loop.

U have mentioned to check with a boolean.I don't know how it works.Can u explain it and please make sure that the syntax is correct.

Regards,
Satya
May 11 '07 #9
pbmods
5,821 Recognized Expert Expert
U have mentioned to check with a boolean.I don't know how it works.Can u explain it and please make sure that the syntax is correct.
(made another quick change; what is with me and the typos this week?!)

Expand|Select|Wrap|Line Numbers
  1. var present = false;
  2. for(i=0;(i< myDropDown.options.length) && (! present);i++)
  3.     present = (myDropDown.options[i].value == "NewYork");
  4.  
  5. if(! present) {
  6.     //  I'm sure you know what goes here.
  7. }
In this block, we loop through myDropDown.opti ons using a for loop, but in addition to checking to see if i is less than options.length, we also check to see if present is still false (since once we know that the item is already in the list of options, there's no point in continuing to search).

At the end of the loop's execution, if we never found "NewYork", then present will be false, and we know to add the new option. On the other hand, if present is true, then we know that the option already exists, so we can skip it.

For faster execution, I also provide this idea:

Expand|Select|Wrap|Line Numbers
  1. var myOptions = null;  // Declared globally at start of execution.
  2.  
  3. .
  4. .
  5. .
  6.  
  7. function createOptionOrWhateverYouCalledIt(newValue, newText) {
  8. .
  9. .
  10. .
  11. // Load existing options (if we haven't done so already).
  12. if(! myOptions) {
  13.     myOptions = {};
  14.     for(var i = 0; i < myDropDown.options.length; i++)
  15.         myOptions[myDropDown.options[i].value] = true;
  16. }
  17.  
  18. if(! myOptions[newValue]) {
  19.     // Create the new option.
  20.  
  21.     // Cache the new option.
  22.     myOptions[newValue] = true;
  23. }
  24.  
In this block, we create a global variable myOptions which we will use to cache all of the options in myDropDown so that we don't have to keep looping through it.

The first time we try to create an option (inside the aptly-named function createOptionOrW hateverYouCalle dIt), the function checks to see if myOptions has been defined. Since it was initialized to null, we create a generic object ('{}'), and then run through myDropDown and populate myOptions. E.g., if myDropDown had three options: (NewYork, Anchorage, Dallas), then myOptions would look like this:

Expand|Select|Wrap|Line Numbers
  1. myOptions = {
  2.     'NewYork': true,
  3.     'Anchorage': true,
  4.     'Dallas': true
  5. };
  6.  
Note that myOptions['NewYork'] === true, whereas myOptions['Indianapolis'] == false (undefined). This becomes important in the next step:

Expand|Select|Wrap|Line Numbers
  1.     if(! myOptions[newValue]) {
  2.  
newValue is the value of the new option. if newValue were 'NewYork', then myOptions['NewYork'] would resolve to true, which we negate to get false, so we don't create a new option.

On the other hand, if newValue were 'Ann Arbor', myOptions['Ann Arbor'] would resolve to undefined, which we negate to get true, so we *do* create the new option.

Expand|Select|Wrap|Line Numbers
  1.     // Cache the new option.
  2.     myOptions[newValue] = true;
  3.  
Once we create the new option, we add it to myOptions so we know about it the next time we try to create an option.

Now so far, this isn't that remarkable, since we had to run through the entire list of options. But watch what happens when we execute it a second time:

Expand|Select|Wrap|Line Numbers
  1. if(! myOptions) {
  2.     myOptions = {};
  3.     for(var i = 0; i < myDropDown.options.length; i++)
  4.         myOptions[myDropDown.options[i].value] = true;
  5. }
Note that since myOptions now is defined (and contains all of the values in myDropDown.opti ons), we don't execute this statement at all!

Instead, we go straight to this block:

Expand|Select|Wrap|Line Numbers
  1. if(! myOptions[newValue]) {
  2.     // Create the new option.
  3.  
  4.     // Cache the new option.
  5.     myOptions[newValue] = true;
  6. }
  7.  
And instead of O(n), we now have O(1) execution time!

(or something like that; I was never very good at computer science o_O)
May 11 '07 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

7
4264
by: John C | last post by:
I am working with an HTML-based form that uses a select element that requires about 200 options. Is there a way that I can load, or select one of these options from a file, rather than hardcode them into the select element? Thanks
4
5917
by: Rithish | last post by:
Is there a way to obtain the height of a <SELECT> element dynamically, i.e. through javascript? I want to dynamically display a list box onFocus of a text box element. Also, if the list box would move out of the bottom screen area, I would want to move it up by that fraction so that it displays at the bottom of the screen. To do this, I would need to acquire the height of the SELECT element. I tried quite a few methods. ...
2
8089
by: Monty | last post by:
I use a SELECT dropdown as the nav interface for jumping to a chosen page number. When I setup up the SELECT element on the page, I want to show the user the current page number they are on, so, I put "selected" next to the page number, as shown below: ------------------------------- <form name="pick" method="post" action="showit.php"> <select name="pggo" onChange="this.options.selected;document.pick.submit();">
2
2267
by: Rob Long | last post by:
Hi I have an HTML select element in my page and it's multiple property is disabled (one item at a time mode) but I still want to transfer all the items in the select to the server when the form is submitted. I'm using javascript to change the multiple property of the select element to true and then I'm looping through each option to change its selected property to true.
6
15630
by: artev | last post by:
if I have a select with more options, how I can know if is there an option selected; is necessary a cycle? or is there an inner property?
3
2229
by: alvinwoon | last post by:
Hi guys, I find it frustrating that I need to sniff out IE to make event handler for the form's select element work across different browsers. Here's a summary of what I have right now: var select = /*get the form select element*/ var option = /*get all the option elements*/ if(document.all){
1
2492
by: Axel Gallus | last post by:
I add some option items to a <selectbox by: ----- MySelect.length = null; // clears all options in select element for ( var i in Somename ) { MySelect.options = new Option(Somename,
5
4544
by: Andy Chambers | last post by:
Hi, On both Opera and Firefox, getElementsByTagName doesn't find anything apart from <optionelements inside a select element. Why is this? Here's a page that demonstrates this behaviour. I'd have thought the correct behaviour would be to show "count: 1" but instead, you get "count: 2". Is this because only <option>s <select>s?
1
1414
Prakash Gnana
by: Prakash Gnana | last post by:
How to remove a particular option in select box in HTML when clicked?
0
8553
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9112
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8971
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8815
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5826
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4332
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4569
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2994
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
1970
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.