SitePoint Sponsor

User Tag List

Results 1 to 14 of 14
  1. #1
    SitePoint Enthusiast
    Join Date
    Nov 2008
    Posts
    73
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Help with JQuery auto populate script

    Hi, I'm using Remy Sharp's auto populate select box plugin and everything is working fine apart from one small detail. I basically have a form where a user selects an option via a dropdown select box, then (using AJAX and JQuery) the values in a secondary select dropdown box are populated based on the selection made. The user can then select an option from the secondary dropdown box then submit the form. I process the values in PHP and return a set of results and when I display the results I want the dropdown boxes to be populated with the values which the user selected when submitting the form. This is where the problem lies, I can't seem to get the secondary dropdown box to show the posted option as "selected", instead it just defaults to the first item in the list.

    I have the posted id which I want to use as the selected value in the secondary dropdown, but I'm just sure how to interact with the plugin to pass this value from my php code. If anyone can help. that would be great as i'm stumped here.

    Plugin code (tweaked a bit)
    Code JavaScript:
    (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 ([url]http://support.microsoft.com/?scid=kb%3Ben-us%3B276228[/url])
                                o = document.createElement("OPTION");
                                o.value = typeof j[i] == 'object' ? j[i][settings.key] : j[i];
     
    							//wee hack here as i want to concatenate the job number and description
    							o.text = typeof j[i] == 'object' ? j[i]['id'] + ' :: ' + j[i]['description'] : 'There are currently no jobs for this client';
     
    							//original line below
                                //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.
    						console.log(desc);
                        }
                    });
                });
            });
        };
    })(jQuery);

  2. #2
    SitePoint Addict ArunB's Avatar
    Join Date
    Jun 2008
    Location
    Hyderabad
    Posts
    252
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Lightbulb

    In your code, below part selects the first option of the select box.

    Code JavaScript:
    settings.target.find('option:first').attr('selected', 'selected')


    If you have the value/text that is selected previously (Probably you can get it from $_POST), then you can select that option using jQuery.

    Suppose in Select box, previously, user selected option whose value is 8, then use the code below ( ddlSelectBox is the id of the select box ):

    Code JavaScript:
    $( '#ddlSelectBox > OPTION[value=8]' ).attr('selected', true);

    If the option contains text like "ArunB" (in case you don't know the value), then use the code below:

    $( '#ddlSelectBox > OPTION:contains("ArunB")' ).attr('selected', true);

  3. #3
    SitePoint Enthusiast
    Join Date
    Nov 2008
    Posts
    73
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi Arun, sorry I'm only now getting the chance to implement your suggestion which does seem to be exactly what I'm looking for. The only thing is, and I'm further exposing my poor javascript knowledge here, is how I access the $_POST value from the jQuery script in order to use it in the snippet of code you've provided above. I thought this would be straightforward, but searching around on the net i can't find out how to do this. Can anyone help?

  4. #4
    SitePoint Addict ArunB's Avatar
    Join Date
    Jun 2008
    Location
    Hyderabad
    Posts
    252
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Thumbs up

    These select boxes will have either name or id. When you click on the submit button, on the server side, you can get these selected values using $_POST["element id/name"]. These select boxes data will be sent to the server only if they are in the form which you are submitting.

  5. #5
    SitePoint Enthusiast
    Join Date
    Nov 2008
    Posts
    73
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi Arun, yes I have no problem with getting the posted value using PHP and $_POST - I suppose my confusion is how to pass the variable properly from PHP to the jQuery script so that I can use it.

    Edit: this is getting more into PHP now than Javascript - i'll ask over at the php forum.

  6. #6
    SitePoint Addict ArunB's Avatar
    Join Date
    Jun 2008
    Location
    Hyderabad
    Posts
    252
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    <script language="JavaScript">
    $( '#ddlSelectBox > OPTION[value=<?php echo $_POST["element id/name"]; ?>]' ).attr('selected', true);
    </script>

    ddlSelectBox is the id of the select box.

  7. #7
    SitePoint Enthusiast
    Join Date
    Nov 2008
    Posts
    73
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Many thanks Arun I will just add an isset($_POST) test to this and hopefully this should do the trick

  8. #8
    SitePoint Enthusiast
    Join Date
    Nov 2008
    Posts
    73
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ok, for some reason the following line working perfectly when I run it from the console in firebug:
    Code:
    $('#job_id > OPTION[value=5224]' ).attr('selected', true);
    But when i try to wrap it within the rest of my js to be executed on document.ready, the dropdown list selection keeps reverting to the first option. The select-chain.js script is loaded before i execute the above line of code, and I thought that the fact that the line above is wrapped in document.ready should allow the select-chain.js code to load first, then I could simply update the currently selected option in the dropdown. I'm not sure why this is working from the console and not within my code, any ideas?

  9. #9
    SitePoint Addict ArunB's Avatar
    Join Date
    Jun 2008
    Location
    Hyderabad
    Posts
    252
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Put the above line at the end of document.ready function. May be some other statement is setting that selection to the first one.

  10. #10
    SitePoint Enthusiast
    Join Date
    Nov 2008
    Posts
    73
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks again for your help Arun - appreciate it

    The line is at the end of document.ready, so i'm not sure why it isn't working.
    This is the sequence of events:
    Load jquery lib
    Load select-chain.js
    inline script as follows:
    Code:
        $(document).ready(function() {
            var cat = $('#client_id');
            var el = $('#job_id');
    
            cat.selectChain({
                target: el,
                url: '/timesheets/timesheet_manager/index',
    	    key: 'id',
    	    value: 'id',
                data: { ajax: true }
            }).trigger('change');
    
    	$("#start_date").date_input();
    	$("#end_date").date_input();
        
        
         $('#job_id > OPTION[value=5224]' ).attr('selected', true);
        });
    I can't see why the last line isn't taking effect!

  11. #11
    SitePoint Addict ArunB's Avatar
    Join Date
    Jun 2008
    Location
    Hyderabad
    Posts
    252
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    May be something else is changing the selection. Can you host a sample?

  12. #12
    SitePoint Enthusiast
    Join Date
    Nov 2008
    Posts
    73
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ok i've put a demo online here - to recreate the issue, pick client3, then one of the jobs from the next list - you will see that after submitting the form (no need to supply dates) the job reverts to the first in the list

  13. #13
    SitePoint Addict ArunB's Avatar
    Join Date
    Jun 2008
    Location
    Hyderabad
    Posts
    252
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Thumbs up

    In your code, may be the following code part in jquery.select-chain.js is causing the problem.
    Code JavaScript:
    // hand control back to browser for a moment
    setTimeout(function () {
        settings.target
                   .find('option:first')
                   .attr('selected', 'selected')
                   .parent('select')
                   .trigger('change');
        }, 0);
    Try to comment it out. But make sure that it won't break other functionality. As I haven't looked into it in a detailed manner, I don't know the effect of commenting out the above code part.

  14. #14
    SitePoint Enthusiast
    Join Date
    Nov 2008
    Posts
    73
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I had tried commenting out that section before but it didn't seem to change anything at all - i've commented it out again in case it helps you see what's going on here. I'm totally lost on this one!


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
  •