SitePoint Sponsor

User Tag List

Results 1 to 20 of 20
  1. #1
    SitePoint Zealot
    Join Date
    Nov 2008
    Location
    Italy
    Posts
    151
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    retrieve specific values from option select

    Hi,

    please can you help me please?

    I have two 'option select full' of values!
    I would to know: how can I retrieve some values from the second option select based on the selection of a particular value of the first option select?

    I would to do everithing without submitting the form!

    I hope you understand....

  2. #2
    SitePoint Evangelist bals28mjk's Avatar
    Join Date
    Aug 2007
    Posts
    405
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Think so, like a double drop down menu type deal right?

    One way of coding that would be include separate menus rather than hand picking specific values out of one sub menu. If you have a countries menu, with an onchange event function point to the specific territories you wish to include.

  3. #3
    SitePoint Zealot
    Join Date
    Nov 2008
    Location
    Italy
    Posts
    151
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Arrow

    When the page starts I have these two 'option select' full of values:
    - Selecting 'one' value from the first, I would retrieve or 'filter' some values from the second.
    - If I don't select any value from the first I can choise from the 'full' list of the second 'option select'.

    Now I have done yet these two working option select not in javascript but only in PHP. So I must select one value from the first, and one value from the second, but doing so there will be a case where I select a value from the second that is 'not bind', a value that has absolutely no pertinence with the first value selected in the first 'option select'

    So I would do this with javscript, and 'filter' ONLY right values based on the value chosen from the first 'option select'. It is right to say onchange because I don't want to submit the form during this passes.

    What can I do?

  4. #4
    SitePoint Evangelist bals28mjk's Avatar
    Join Date
    Aug 2007
    Posts
    405
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You need to hide the values of the second option select that don't have pertinence to the first?

    Store each values for the groups in an array and onchange loop through those values and place them in the second option select. The way you place them is either you can remove the nodes individually or the entire select list.

    In my previous post, I was saying it would be easier for you to code separate option select lists.

    Cheers.

  5. #5
    SitePoint Zealot
    Join Date
    Nov 2008
    Location
    Italy
    Posts
    151
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yes. Just like as you said.
    Can you post a little example with very few values to explain it to me better?
    Javascript is not familiar for me.
    Till now I have tried always to avoid javascript but not I think that is the better way to proceed...

  6. #6
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    Here you go, try the following.

    With the techniques used here, it will work without javascript where people can pick and choose from the second select that's broken down into optgroup sections.

    When there is javascript, a selection from the first select field updates the second select with only those related options.

    Code html4strict:
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
    <title>Test</title>
    </head>
    <body>
    <form id="myForm" action="progssForm.php">
    <p>
    	<select name="categories">
    		<option>Please select</option>
    		<option value="Categories 1">Category 1</option>
    		<option value="Categories 2">Category 2</option>
    		<option value="Categories 3">Category 3</option>
    		<option value="Categories 4">Category 4</option>
    		<option value="Categories 5">Category 5</option>
    		<option value="Categories 6">Category 6</option>
    	</select>
    	<select name="groups">
    		<optgroup><option>Please select</option></optgroup>
    		<optgroup label="Categories 1"><option>Option 1</option><option>Option 2</option><option>Option 3</option><option>Option 4</option><option>Option 5</option><option>Option 6</option></optgroup>
    		<optgroup label="Categories 2"><option>Option 7</option><option>Option 8</option><option>Option 9</option><option>Option 10</option><option>Option 11</option><option>Option 12</option></optgroup>
    		<optgroup label="Categories 3"><option>Option 13</option><option>Option 14</option><option>Option 15</option><option>Option 16</option><option>Option 17</option><option>Option 18</option></optgroup>
    		<optgroup label="Categories 4"><option>Option 19</option><option>Option 20</option><option>Option 21</option><option>Option 22</option><option>Option 23</option><option>Option 24</option></optgroup>
    		<optgroup label="Categories 5"><option>Option 25</option><option>Option 26</option><option>Option 27</option><option>Option 28</option><option>Option 29</option><option>Option 30</option></optgroup>
    		<optgroup label="Categories 6"><option>Option 31</option><option>Option 32</option><option>Option 33</option><option>Option 34</option><option>Option 35</option><option>Option 36</option></optgroup>
    	</select>
    </p>
    <p><input name="submit" type="submit"></p>
    </form>
     
    <script src="script.js"> </script>
    </body>
    </html>

    script.js
    Code javascript:
    var form = document.getElementById('myForm');
    var categories = form.elements['categories'];
    var groups = form.elements['groups'];
    var submit = form.elements['submit'];
    initGroups(groups);
    categories.onchange = updateGroups;
    submit.onclick = function () {
    	var groups = this.form.elements['groups'];
        if (groups.selectedIndex === 0) {
    		return false;
    	}
    }
    function initGroups(select) {
        var els = select.childNodes;
        select.groups = [];
        for (i = 0; i < els.length; i += 1) {
            if (els[i].nodeName === 'OPTGROUP') {
                select.groups.push(els[i]);
            }
        }
    }
    function updateGroups() {
        var label = this.value;
        var groups = this.form.elements['groups'];
        updateOptionsFromGroup(groups, label);
    }
    function updateOptionsFromGroup(select, label) {
        var group = getGroup(select, label);
        removeOptions(select);
        addOption(select, label);
        addOptionsFromGroup(select, group);
    }
    function getGroup(select, label) {
        var groups = select.groups;
        var i;
        for (i = 0; i < groups.length; i += 1) {
            if (groups[i].label === label) {
                return groups[i];
            }
        }
    }
    function removeOptions(select) {
        while (select.hasChildNodes()) {
            select.removeChild(select.firstChild);
        }
    }
    function addOption(select, text, value) {
        var option = document.createElement('option');
        option.appendChild(document.createTextNode(text));
        if (value) {
            option.value = value;
        }
        select.appendChild(option);
    }
    function addOptionsFromGroup(select, group) {
        var option;
        var i;
    	if (group.childNodes) {
    	    for (i = 0; i < group.childNodes.length; i += 1) {
    	        option = group.childNodes[i].cloneNode(true);
    	        if (option.nodeName === 'OPTION') {
    	            select.appendChild(option);
    	        }
    	    }
    	}
    }
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  7. #7
    SitePoint Zealot
    Join Date
    Nov 2008
    Location
    Italy
    Posts
    151
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Arrow

    Wow . this script is just like what I need. thanks.

    Now the next step I will do is to insert values in the first 'option select' from an PHP array and build the related 'option select' dynamically. Now I am seeing yet in what way I can do that but I think like this:
    $categories = array('Category_1', 'Category_2', 'Category_3');
    $category_1 = array('Option_1', 'Option,2', 'Option_3');

    all these arrays contain data from db, so each $category array is a sub-select derived from each value of the first array.

    Hope I will be able to do this and apply the necessary modifications for make it right with javascript too.

    Many thanks!

  8. #8
    SitePoint Zealot
    Join Date
    Nov 2008
    Location
    Italy
    Posts
    151
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Why when I have chosen a category from catogories and then again I select the value 'please select' the second option select is empty?

    I have done all about PHP and it goes perfectly, unless this 'little bug'.

  9. #9
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    I presume that you would like the full complete list to reappear in there. I'll see what can be done.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  10. #10
    SitePoint Zealot
    Join Date
    Nov 2008
    Location
    Italy
    Posts
    151
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yes you're right.

    I presume that in the js script the function initGroups(groups) would be executed also when the first element of the first 'option select' has been selected... But i'm insecure.

  11. #11
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    I've updated the updateOptionsFromGroup function and added an addAllGroups function so that if no correct group is found, the who lot are put back into the second select.

    Code javascript:
    function updateOptionsFromGroup(select, label) {
        var group = getGroup(select, label);
        removeOptions(select);
    	if (group) {
    	    addOption(select, label);
    	    addOptionsFromGroup(select, group);
    	} else {
    		addAllGroups(select);
    	}
    }
    function addAllGroups(select) {
        var groups = select.groups;
        var i;
        for (i = 0; i < groups.length; i += 1) {
            select.appendChild(groups[i].cloneNode(true));
        }
    }

    Here's the full script as it now stands.

    Code javascript:
    var form = document.getElementById('myForm');
    var categories = form.elements['categories'];
    var groups = form.elements['groups'];
    var submit = form.elements['submit'];
    initGroups(groups);
    categories.onchange = updateGroups;
    submit.onclick = function () {
        var groups = this.form.elements['groups'];
        if (groups.selectedIndex === 0) {
            return false;
        }
    }
    function initGroups(select) {
        var els = select.childNodes;
        select.groups = [];
        for (i = 0; i < els.length; i += 1) {
            if (els[i].nodeName === 'OPTGROUP') {
                select.groups.push(els[i]);
            }
        }
    }
    function updateGroups() {
        var label = this.value;
        var groups = this.form.elements['groups'];
        updateOptionsFromGroup(groups, label);
    }
    function updateOptionsFromGroup(select, label) {
        var group = getGroup(select, label);
        removeOptions(select);
    	if (group) {
    	    addOption(select, label);
    	    addOptionsFromGroup(select, group);
    	} else {
    		addAllGroups(select);
    	}
    }
    function getGroup(select, label) {
        var groups = select.groups;
        var i;
        for (i = 0; i < groups.length; i += 1) {
            if (groups[i].label === label) {
                return groups[i];
            }
        }
    }
    function removeOptions(select) {
        while (select.hasChildNodes()) {
            select.removeChild(select.firstChild);
        }
    }
    function addOption(select, text, value) {
        var option = document.createElement('option');
        option.appendChild(document.createTextNode(text));
        if (value) {
            option.value = value;
        }
        select.appendChild(option);
    }
    function addOptionsFromGroup(select, group) {
        var option;
        var i;
    	for (i = 0; i < group.childNodes.length; i += 1) {
    		option = group.childNodes[i].cloneNode(true);
    		if (option.nodeName === 'OPTION') {
    			select.appendChild(option);
    		}
    	}
    }
    function addAllGroups(select) {
        var groups = select.groups;
        var i;
        for (i = 0; i < groups.length; i += 1) {
            select.appendChild(groups[i].cloneNode(true));
        }
    }
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  12. #12
    SitePoint Zealot
    Join Date
    Nov 2008
    Location
    Italy
    Posts
    151
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Perfect. Definitely it's OK. It goes marvellously ;
    Many many thanks you have resolved one my great problem!!!!!
    Thanks again!! Cheerz..

  13. #13
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by franciska View Post
    I presume that in the js script the function initGroups(groups) would be executed also when the first element of the first 'option select' has been selected...
    It happens even before that. The initGroups part occurs when the page first loads.

    Edit:

    I'm glad that this solution worked out so well for you.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  14. #14
    SitePoint Zealot
    Join Date
    Nov 2008
    Location
    Italy
    Posts
    151
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi, Please I would to know another thing if possible...
    When I select a value from the 'first list' I obtain in the second list the name of the label (or the value of the first option select) and the related values.
    Well I don't want the label appears in the second 'option select' and in place of it I want a blank space &nbsp; (and related, as now). I have applied definitely to my web application and it goes marvellously!!

  15. #15
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    Look at the following function.

    Code javascript:
    function updateOptionsFromGroup(select, label) {
        var group = getGroup(select, label);
        removeOptions(select);
        if (group) {
            addOption(select, label);
            addOptionsFromGroup(select, group);
        } else {
            addAllGroups(select);
        }
    }

    Specifically, the following line:

    Code javascript:
    addOption(select, label);

    You will just need to change that to the following:

    Code javascript:
    addOption(select, ' ');
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  16. #16
    SitePoint Zealot
    Join Date
    Nov 2008
    Location
    Italy
    Posts
    151
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ok thanks again.
    I have saw another thing.
    When I reload from a $_GET call the form that contains these two option select, the two values are mainteined as I programmed, so the value of the first option select is the same but though the value of the second option is the same, when I drop down the option select I find all values and not the few values related to the first 'option select'...... (obviously I have added method get in the form..... )

  17. #17
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    This is because the web browser is trying to be useful and doing what it can to show the values that were there before.

    Add the following to the script. Between the submit.onclick and initGroups function is a good place to add this:

    Code javascript:
    setTimeout(function () {
    	var form = document.getElementById('myForm');
    	var categories = form.elements['categories'];
    	categories.selectedIndex = 0;
    }, 0);
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  18. #18
    SitePoint Zealot
    Join Date
    Nov 2008
    Location
    Italy
    Posts
    151
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    but doing so you 'reset' the first 'option select' ... Maybe I have been not clear. In this form I have also other fields. I have created a link in another page, that clicking on it the script returns to the page of fields with all same values, same criteria of search. All function perfecly, also the new two 'option select', also the values in the option select are preserved, and I want this because it's ok.
    But when I click the option select for another choise 'related' to the value that is showed in the first option select, I see 'all' values of the second and not a restricted interval.
    It will go perfectly again if I select another time the value already selected in the first 'option value'. I obtain the desired result.

    Hope I have been clear. Excuse my bad english..

    I presume that an event form.onload is able to resolve this problem...... but I don't know js

  19. #19
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    Oh I get it. When you select and option from the second select field and submit the form, when the page is loaded again the first value is remembered but the second value is not.

    This is because the scripted changes that occurred to restructure the second select field, are not remembered from one page load to the next.

    The only way to deal with this is to make things more complex.

    The choice of options from the fields can be saved as a cookie, so that when the page loads up again it can restore the select fields to how they were before. This may not be a good option though because you may not want someone else coming along to the computer on a seperate visit to have those fields default to the selection from the previous visit.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  20. #20
    SitePoint Zealot
    Join Date
    Nov 2008
    Location
    Italy
    Posts
    151
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Arrow

    So This is what I mean. And I repeat "it goes perfectly" . there are both values returned. So, there aren't any problems about selected values etc...

    see and try these files. As you will see. It goes perfectly..... BUT.....

    nodes.php
    Code PHP:
    <?php
     
       $self = $_SERVER['PHP_SELF'];
     
       if (isset($_GET['categories'])) {
          $categ = str_replace(" ", " ", $_GET['categories']);
          echo "returned value : " . $categ . "<br>";
       } else {
          $categ = "";
       }
     
       if (isset($_GET['groups'])) {
          $groups = str_replace(" ", " ", $_GET['groups']);
          echo "returned value : " . $groups . "<br><br>";
       } else {
          $groups = "";
       }
     
     
    ?>
     
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
    <title>Test</title>
    </head>
    <body>
    <form id="myForm" method="get" action="progssForm.php">
    <p>
        <select name="categories">
            <option>Please select</option>
            <?php
             for ($g = 1; $g <= 6; $g++) {
                echo "<option value='Categories $g'";
                if ($categ == "Categories $g") {
                   echo " SELECTED>Category $g</option>";
                } else {
                   echo ">Category $g</option>";
                }
             }
            ?>
        </select>
        <select name="groups">
            <optgroup><option>Please select</option></optgroup>
             <?php
              for ($p = 1; $p <= 6; $p++) {
                echo "<optgroup label='Categories $p'>";
                for ($b = 1; $b <= 6; $b++) {
                   echo "<option";
                   if ($groups == "Option $b") {
                      echo " SELECTED>Option $b</option>";
                   } else {
                      echo ">Option $b</option>";
                   }
                }
                echo "</optgroup>";
              }
             ?>
                 </select>
    </p>
    <p><input name="submit" type="submit"></p>
    </form>
     
    <script src="script_2.js"> </script>
    </body>
    </html>


    progssform.php
    Code PHP:
    <?php
       $self = $_SERVER['PHP_SELF'];
     
       if (isset($_GET['categories'])) {
          $categ = str_replace(" ", " ", $_GET['categories']);
          echo $categ . "<br>";
       }
     
       if (isset($_GET['groups'])) {
          $groups = str_replace(" ", " ", $_GET['groups']);
          echo $groups . "<br><br>";
       }
     
       echo "<a href='nodes.php?categories=$categ&groups=$groups>Return</a>";
     
    ?>

    NOTE that in the first php file in str_replace occurences, between the first couple of double quote put '#32' (NOTE without single quote, and & before #) and in the second file put it in the second couple of them.......... (I have post these notes because every time I put the space code this form transforms them in empty spaces and then not visible).


    Ok let's go..
    After you have submitted the form, when you click the link "return", as you can see I obtain again the same values of start with the two option select selected on these two values. It's all perfect and OK till now.

    Next pass: Now try to click on the "second" option select as you can see, the list that results is "the complete list" and not a sub-list based on the value of the first option select.... Why?

    And I have discovered another thing..... I have ran the script on Explorer 7 and every time I select a value from the first option select, the second option select reduces his width gradually each time! Is a problem related to the script or a bug of IE? However I think the second possibility.....


Bookmarks

Posting Permissions

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