Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 13 of 13
  1. #1
    Regular Coder
    Join Date
    Sep 2011
    Posts
    184
    Thanks
    140
    Thanked 0 Times in 0 Posts

    Adding and Selecting an Option Value from a Drop Down Box

    Hello,

    I need your help on creating a function that would allow me to select a given option name based on a known variable from a drop down box (using javascript) and if the value doesn’t exist in the drop down box then add it and select it.

    Example:

    Code:
    <html>
    
    <head>
    
    <script type="text/javascript">
    
    function test() {
    
    var option_name_to_look_for = "mangos"
    
    if the option_name_to_look_for is already listed in the drop down box (drop) then select it
    
    if the option_name_to_look_for is not listed in the drop down box (drop), then automatically add it to the drop down list and select it.
    
    }
    
    </script>
    
    </head>
    
    <body>
    
    <select id="drop" style="width: 200px;">
    <option value="0"></option>
    <option value="1">apples</option>
    <option value="2">oranges</option>
    <option value="3">pears</option>
    <option value="4">mangos</option>
    <option value="5">bananas</option>
    <option value="6">kiwis</option>
    
    </select>
    
    </body>
    
    </html>

  • #2
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,980
    Thanks
    56
    Thanked 557 Times in 554 Posts
    wha?

    you select an option from a list of options, if the option isn't there (which it is because you just selected it) add it, if it is there, select it (which you already did)?

    makes no sense whatsoever

  • #3
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,079
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    I think this is what he means:-

    Code:
    <form id = "myform">
    
    <input type = "text" onchange = "addOption(this.value)">
    
    <select id="drop" style="width: 200px;">
    <option value="0">Select .....</option>
    <option value="1">apples</option>
    <option value="2">oranges</option>
    <option value="3">pears</option>
    <option value="4">mangos</option>
    <option value="5">bananas</option>
    <option value="6">kiwis</option>
    </select>
    
    </form>
    
    <script type = "text/javascript">
    
    function addOption(txt) {
    var f = document.getElementById("myform");
    var s = document.getElementById('drop');
    var opt = new Option(txt);
    
    for (var i = 0; i<s.options.length; i++) {
    var xtext = f.drop[i].text; 
    f.drop[i].selected = true
    if (txt == xtext) {
    //alert ("You have already added this value to the select box");
    return false;
    }
    }
    
    s.options[s.options.length] = opt;
    f.drop[i].selected = true
    return true;
    } 
    
    </script>
    If the user enters the name of the fruit in the singular (banana) you may want to add an "s".

    Code:
    var len = txt.length;
    if (txt.charAt(len-1) != "s") {
    txt += "s";
    document.getElementById("inp").value = txt;
    }
    Quizmaster: A monocracy is a form of government in which how many people rule?
    Contestant: Twelve.
    Last edited by Philip M; 12-14-2012 at 05:29 PM. Reason: Change form name to id

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • Users who have thanked Philip M for this post:

    jason_kelly (12-21-2012)

  • #4
    Regular Coder
    Join Date
    Sep 2011
    Posts
    184
    Thanks
    140
    Thanked 0 Times in 0 Posts
    Thanks again for this Phil.

    I was thinking this

    Code:
    //========================================================================
    function get_position(id,option_name) {
    //========================================================================
    // alert (option_name);
    var flag = false;
    for (var i=0;i<=document.getElementById(id).options.length-1;i++)   {
    if (document.getElementById(id).options[i].text == option_name)  {
    //alert (option_name + " is item No. " + i + " in the option list");
    document.getElementById(id).selectedIndex=i; 
    flag = true;
    }
    }
    //if (!flag) { alert (option_name + " was not found") }
    }
    How can I build on the code above and integrate the additiion to the drop down list to add the option dynamically should it not exist. Id like to use the (!flag) and have it add the new value and select it.

    This is well beyond my level of javascript.

    Thanks for everyones help.

    Cheers,

    Jay

  • #5
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,873
    Thanks
    79
    Thanked 4,421 Times in 4,386 Posts
    ??? Philip's code *ALREADY* does the equivalent of what you asked for.

    Didn't you try it?

    He does have one goof:
    Code:
        f.drop[i].text;
    Because he didn't give a name= to his <select>, he can't use f.drop.

    But I don't understand why he didn't give a name to the <select>. Without a name, the field can't be submitted to another page.

    So if he had simply done:
    Code:
    <select name="drop" style="width: 200px;">
    then he could have coded:
    Code:
    function addOption(txt) 
    {
        var f = document.getElementById("myform");
        var sel = f.drop;
        for (var i = 0; i < sel.options.length; i++) 
        {
            if ( txt == sel.options[i].text; 
            {
                //alert ("You have already added this value to the select box");
                sel.selectedIndex = i;
                return; 
           }
       }
       // not found, so add the option:
       // (i from for loop will be one more than highest numbered existing option)
       sel.options[i] = new Option( txt, i );
       sel.selectedIndex = i;
    }
    Last edited by Old Pedant; 12-21-2012 at 09:22 PM.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    jason_kelly (12-22-2012)

  • #6
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,873
    Thanks
    79
    Thanked 4,421 Times in 4,386 Posts
    And what is YOUR code doing, using document.getElementById() to find the <select>? Again, if your <select> has only an ID, you won't be able to pass it to the next page. So why not abandon the id and use a name= instead?

    Unless you have more than one of these <select>s on the page that needs to have this capability, what is the point in passing in the id (or name) to your [strangely named] get_position( ) function? If there's only one such <select>, just do as Philip (and I) did and "find" it inside the function automatically.

    But if you really do have multiple <select>s that need this functionality, then I guess you could do:
    Code:
    function findOrAddOption(sel, txt) 
    {
        for (var i = 0; i < sel.options.length; i++) 
        {
            if ( txt == sel.options[i].text; 
            {
                //alert ("You have already added this value to the select box");
                sel.selectedIndex = i;
                return; 
           }
       }
       // not found, so add the option:
       // (i from for loop will be one more than highest numbered existing option)
       sel.options[i] = new Option( txt, i );
       sel.selectedIndex = i;
    }
    And then you could invoke the function via something like this:
    Code:
    <form>
        ...
        <input type="text" name="whatever" onchange="findOrAddOption(this.form.select33, this.value);" />
        <select name="select33">
           ...
        </select>
        ...
    </form>
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    jason_kelly (12-22-2012)

  • #7
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,079
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    Quote Originally Posted by Old Pedant View Post
    ??? Philip's code *ALREADY* does the equivalent of what you asked for.

    Didn't you try it?

    He does have one goof:
    Code:
        f.drop[i].text;
    Because he didn't give a name= to his <select>, he can't use f.drop.

    But I don't understand why he didn't give a name to the <select>. Without a name, the field can't be submitted to another page.
    I don't see your objection. The code works just fine for me in IE and Chrome. Agree that the select needs a name for submitting to another page.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #8
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,873
    Thanks
    79
    Thanked 4,421 Times in 4,386 Posts
    Weird.

    I could see it working if you just used drop[i].text because the bare id is equivalent to document.getElementById(id), but here you are asking for it to find an element of a <form> and how does an id, instead of a name, qualify as such?

    I believe you, of course, that it works. It just seems to me that this is a violation of the spirit of the DOM.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #9
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,079
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    Quote Originally Posted by Old Pedant View Post
    Weird.

    I could see it working if you just used drop[i].text because the bare id is equivalent to document.getElementById(id), but here you are asking for it to find an element of a <form> and how does an id, instead of a name, qualify as such?

    I believe you, of course, that it works. It just seems to me that this is a violation of the spirit of the DOM.
    You don't have to believe me. You could test it out for yourself.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #10
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,980
    Thanks
    56
    Thanked 557 Times in 554 Posts
    ... but you don't really need to reference the form at all...
    Code:
    <script type = "text/javascript">
    
    function addOption(txt) {
    var s = document.getElementById('drop');
    for (var i = 0; i<s.length; i++) {
    var xtext = s[i].text; 
    s[i].selected = true
    if (txt == xtext) {
    //alert ("You have already added this value to the select box");
    return false;
    }
    }
    var opt = new Option(txt,i);
    s.options[i] = opt;
    s[i].selected = true
    return true;
    } 
    
    </script>
    Last edited by xelawho; 12-23-2012 at 12:07 AM.

  • #11
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,873
    Thanks
    79
    Thanked 4,421 Times in 4,386 Posts
    I dunno. If you can't trust the DOM to stick to the spirit of its origins, maybe it's time to stop using JavaScript.

    And if you believe that I've got a great used bridge in Arizona for sale. Only one prior owner. Some little old lady in the U.K, I hear.

    Seriously, because I virtually never do any JavaScript that isn't connected with <form>s that are then submitted to some server-side code, I also almost never use form fields with ids. No point, since they aren't then sent to the server. So I'm slow to discover that all these violations of the original spirit of the DOM that were originated in MSIE--and for which MacroSlop was enormously vilified!--are now becoming standard in all browsers. I liked it better before everybody decided that the Slop Shop was right. I, personally, still don't think they were.

    [By the by, a moderately high up architect at MS is the source of "Slop Shop." Not my own invention, unfortunately.]
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #12
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,079
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    Quote Originally Posted by xelawho View Post
    ... but you don't really need to reference the form at all...
    Code:
    <script type = "text/javascript">
    //...
    for (var i = 0; i<s.length; i++) {
    //...
    </script>
    for (var i = 0; i<s.options.length; i++) {

    FWIIW I normally assign both name and (the same) id to form elements. That gives flexibility and means that (often) the form itself does not have to be referenced.

    I have to confess that I am sentimentally attached to Microsoft, which (with MSDOS) enabled me to earn a great deal of money thirty years ago. Just as I continue to always use Shell petrol as they were an important customer of mine at that time. Likewise Heineken beer! I do not have issues with the IE browser (although admitting that it is not perfect).
    Last edited by Philip M; 12-23-2012 at 09:25 AM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #13
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,980
    Thanks
    56
    Thanked 557 Times in 554 Posts
    ... but being that a select has a length that is equal to the number of options that it has
    https://developer.mozilla.org/en-US/...LSelectElement
    Code:
    s.options.length
    just makes the code work harder by introducing an extra dot that doesn't need to be there - if I'm not mistaken, that's what you're doing with this line anyway:
    Code:
    f.drop[i].selected = true
    of course, truly optimising it would involve declaring the variable outside of the loop, but I suspect that the nanoseconds saved would be unnoticeable in most code
    Code:
    var len=s.length;
    for (var i=0; i<len; i++) {
    ...


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •