Hi all - new here and I have a question which is JS/AJAX related.
I am knowledgeable in PHP and MYSQL/SQL, but have never taken the time to tackle Javascript and all of its intricacies, so here it goes...

I have recently found a dynamic drop-down menu which is database-populated that suits my needs found here:
http://remysharp.com/2007/09/18/auto-populate-multiple-select-boxes/

Yep, another question on this topic from another n00b :confused:
(I will insert the majority of coding at the end of this thread)

I would like to incorporate an ONCHANGE aspect into the third (last) drop-down menu which will automatically direct users to a specified URL once it is clicked/changed. I have tested the following code in the SELECT section for the third drop-down and it works with the exception of the VALUE attribute that is being inserted by the JS/AJAX coding in the script...

<select id="attributeSelect" name="category" onchange="if (this.selectedIndex > 0) location.href=this[this.selectedIndex].value;">
                <option>[none selected]</option>
            </select>

The ONCHANGE function works great, however the VALUE attribute dropped by JS for this application is the same as the TEXT seen in the drop-down window. Obviously, text will not direct anywhere and here comes the build-up to my problem.

I have programmed an additional column into the MYSQL table which came with this download - this stores the URL I would like to place into the VALUE section of the OPTION tab so when it is selected, the ONCHANGE function will do its magic.
(I COMMENTED OUT the PHP script which grabs the url information, found in the select-chain.php code below.)

I can extract the URL column from my database, no problem, but how do I incorporate it into the JS function (called JSON) to include it as a VALUE in my OPTION tag?
Essentially, I want to do the following for the third drop-down:

<select //with ONCHANGE (onchange works no problem)>
<option value="URL 1">option text1</option>
<option value="URL 2">option text2</option>
<option value="URL 3">option text3</option>
</select>

I believe the answer to the problem lies within the select-chain.js file and I have dorked the code trying to make it work but it is like speaking a foreign language (for me). Somewhere within this code lies the change in the option VALUE attribute which will allow the script to insert URL's into my OPTION tags as opposed to the TEXT grabbed by the $JSON from the database.

Some of you will probably have the solution to this right away and will look at me as a goof ! I appreciate your replies and forgiveness for me not pursuing the JS line of programming :D

Here is the coding for this drop-down menu (I deleted some of the CSS/DIV unnecessaries since that isn't the issue):


select-chain.php

<?php
if (@$_REQUEST['ajax']) {
    // connect to database 

//connection specs hidden
   
    if ($connected) {
        $results = mysql_query('select * from select_chain where category="' . strtolower(mysql_real_escape_string(strip_tags($_REQUEST['category']))) . '"');
        
        $json = array();
        
        while (is_resource($results) && $row = mysql_fetch_object($results)) {
          //$json[] = '{"' . $row->id . '", "' . $row->label . '","' . $row->url . '"}';
            $json[] = '"' . $row->label . '"';
	
        }
       
        echo '[' . implode(',', $json) . ']';
		
		
        die(); // filthy exit, but does fine for our example.
    } else {
        user_error("Failed to select the database");
    }
}
?>


    <script src="jquery.js" type="text/javascript"></script>
    <script src="select-chain.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript">
    <!--
    $(function () {
        var cat = $('#categorySelect');
        var el = $('#elementSelect');
        var attr = $('#attributeSelect');
        
        el.selectChain({
            target: attr,
            url: 'select-chain.php',
            data: { ajax: true, anotherval: "anotherAction" }            
        });        

        // note that we're assigning in reverse order
        // to allow the chaining change trigger to work
        cat.selectChain({
            target: el,
            url: 'select-chain.php',
            data: { ajax: true }
        }).trigger('change');

    });
    //-->
    </script>
<form name="form1" method="post">
     
        <div class="selHolder">
            Element Category
            <select id="categorySelect" name="category">
                <option>Forms</option>
                <option>Scripts</option>
            </select>
        </div>
        <div class="selHolder">
            Element
            <select id="elementSelect" name="category">
                <option>[none selected]</option>
            </select>
        </div>
        <div class="selHolder">
            Attributes
            <select id="attributeSelect" name="category" onchange="if (this.selectedIndex > 0) location.href=this[this.selectedIndex].value;">
                <option>[none selected]</option>
            </select><br>

        </div>
    </div>
  </form>

select-chain.js

(function ($) {
    $.fn.selectChain = function (options) {
        var defaults = {
            key: "id",
            value: "label"
        };
        
        var settings = $.extend({}, defaults, options);
        
        if (!(settings.target instanceof $)) settings.target = $(settings.target);
        
        return this.each(function () {
            var $$ = $(this);
            
            $$.change(function () {
                var data = null;
                if (typeof settings.data == 'string') {
                    data = settings.data + '&' + this.name + '=' + $$.val();
                } else if (typeof settings.data == 'object') {
                    data = settings.data;
                    data[this.name] = $$.val();
                }
                
                settings.target.empty();
                
                $.ajax({
                    url: settings.url,
                    data: data,
                    type: (settings.type || 'get'),
                    dataType: 'json',
                    success: function (j) {
                        var options = [], i = 0, o = null;
                        
                        for (i = 0; i < j.length; i++) {
                            // required to get around IE bug (http://support.microsoft.com/?scid=kb%3Ben-us%3B276228)
                            o = document.createElement("OPTION");
                            o.value = typeof j[i] == 'object' ? j[i][settings.key] : j[i];
                            o.text = typeof j[i] == 'object' ? j[i][settings.value] : j[i];
                            settings.target.get(0).options[i] = o;
                        }

			// hand control back to browser for a moment
			setTimeout(function () {
			    settings.target
                                .find('option:first')
                                .attr('selected', 'selected')
                                .parent('select')
                                .trigger('change');
			}, 0);
                    },
                    error: function (xhr, desc, er) {
                        // add whatever debug you want here.
			alert("an error occurred");
                    }
                });
            });
        });
    };
})(jQuery);

Ooops - I should have included the database information.

Table name = select_chain
Columns: id, category, label, url

ZzyzX, did you ever get it working?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.