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 12 of 12
  1. #1
    Senior Coder
    Join Date
    Jun 2008
    Location
    Cornwall
    Posts
    2,098
    Thanks
    297
    Thanked 12 Times in 12 Posts

    autosuggest textbox shows & submits text value, want itto show text & submit id value

    Hi All,

    i will try and explain my problem as best i can

    i have an autosuggest text input which uses ajax to pull data from a database as the user types, then as far as i know it uses json to display the results in a list beneath the input box.

    this it the form code
    Code:
                                                <!-- Begin Text input element -->
                                                <div class="quform-element quform-element-text quform-med">
                                                    <div class="quform-spacer">
                                                        <label for="accommodation_location">Location <span class="quform-required">*</span></label>
                                                        <div class="quform-input">
                                                            <input id="accommodation_location" type="text" name="accommodation_location" />
                                                            <p class="quform-description">Choose the town/village where the property is located. </p>
                                                        </div>
                                                    </div>
                                                </div>
                                                <!-- End Text input element -->
    and the javascript code on that page to tell it to run location_results.php is
    Code:
    <script type="text/javascript">
    $(document).ready(function() {
      $('#accommodation_location').smartSuggest({
        src: 'location_results.php',
    	fillBox: true,
    	fillBoxWith: 'fill_text',
    	executeCode: false
      });
    });
    </script>
    location_results.php file is
    PHP Code:
    <?php
    include("config.php");
    /* Get the query string "q" variable -- this is what the user typed in. */
    $q $_GET['q'];

    $results = array();

    $query mysqli_query($con"SELECT * FROM tbl_places")or die(mysqli_error());
    while(
    $row mysqli_fetch_array($query))
    {
        
    $id $row['placeID'];
        
    $name $row['placeName'];
        
    $desc $row['placeInfo'];
        
    $postcode $row['placeName'];
        if (
    stripos($name$q) !== false)
        {
            
    $results[$name] = array('id' => $id'name' => $name'desc' => $desc);
        }

    }

    /* Get the data into a format that Smart Suggest will read (see documentation). */

    $final = array('header' => array(), 'data' => array());
    $final['header'] = array(
        
    'title' => 'Town / Village Search',
        
    'num' => count($results),
        
    'limit' => 5
    );
    foreach (
    $results as $name => $data)
    {
        
    $final['data'][] = array(
            
    'primary' => $name,
            
    'secondary' => $data['desc'],
            
    'onclick' => 'alert(\'You clicked on the '.$name.' fruit!\');',
            
    'fill_text' => $name
        
    );
    }

    /* Output JSON */
    header('Content-type: application/json');
    echo 
    json_encode(array($final)); # Put it as the first result in an array, since we only have one category here
    die();
    ?>
    the fill_text is the value of the input box once you click on one of the items in the list which is set to the list items name, which is what i want, but when submitting the inputs value into the db i want the id value of that item selected which is defined in the above file here =>$id = $row['placeID'];

    but m not sure how to get it to show the name but set the value to its id.

    this is the javascript file
    Code:
    (function($) {
    	$.fn.smartSuggest	=	function(options) {
    		
    		// Define default options.
    		var defaults = {
    			boxId: '%-suggestions', // % is filled with the field's ID, allowing for multiple Smart Suggests per page
    			classPrefix: 'ss-',
    			timeoutLength: 500,
    			src: '',
    			resultsText: '$ of % results',
    			noResultsText: 'No results.',
    			showEmptyCategories: false,
    			fillBox: false,
    			fillBoxWith: 'primary',
    			executeCode: true,
    			showImages: true,
    			minChars: 2
    		};
    		
    		// Merge defaults with user-defined options.
    		var options = $.extend(defaults, options);
    		
    		// Get correct box ID
    		options.boxId = options.boxId.replace('%', $(this).attr('id'));
    		
    		// Define other variables.
    		var lastQuery = '';
    		var data;
    		
    		// Create the wrapper and the suggestion box.
    		$(this).wrap('<div class="'+options.classPrefix+'wrap"></div>');
    		$(this).attr('autocomplete', 'off');
    		$(this).after('<ul class="'+options.classPrefix+'box" id="'+options.boxId+'" style="display: none;"></ul>');
    		var inputObj = $(this);
    		var boxObj = $('#'+options.boxId);
    		
    		
    		
    		// Refresh the suggestion box for every keyup event.
    		var timeout = null;
    		inputObj.keyup(function(event) {
    			
    			// If any key but the enter key or tab key was pressed, continue.
    			if (event.keyCode != 13 && event.keyCode != 9)
    			{
    			
    				// Get the query (the value of the input field).
    				var q = inputObj.val();
    				
    				// If the query is empty or doesn't meet the minChar requirement, close the box. If not, keep going.
    				if (q == '' || q.length < options.minChars)
    				{
    					boxObj.fadeOut();
    					unsetTimeout(timeout);
    				}
    				else
    				{
    					// Check the timeout.
    					if (timeout != null)
    					{
    						unsetTimeout(timeout);
    					}
    					
    					timeout = setTimeout(function() {
    												
    						// Once the timeout length has passed, continue to refresh the box.
    						// Change the input class to the "thinking" state.
    						inputObj.addClass(options.classPrefix+'input-thinking');
    
    						// Set the "last query" variable.
    						lastQuery = q;
    
    						// Get the JSON data.
    						$.getJSON(options.src+"?q="+q, function(data, textStatus) {
    							// Check to make sure that the JSON call was a success.
    							if (textStatus == 'success')
    							{
    								// Create the suggestion HTML.
    								var output = "";
    								
    								// Determine if there is any data in the categories.
    								var has_data = false;
    								$.each(data, function(i, group) {
    									if (group['data'].length > 0)
    									{
    										has_data = true;
    									}
    								});
    								
    								if (!has_data)
    								{
    									output += '<li class="'+options.classPrefix+'header">'+"\n";
    									output += '<p class="'+options.classPrefix+'header-text">'+options.noResultsText+'</p>'+"\n";
    									output += '<p class="'+options.classPrefix+'header-limit">0 results</p>'+"\n";
    									output += '</li>';
    								}
    								else
    								{
    									$.each(data, function(i, group) {
    										
    										if (options.showEmptyCategories || (!options.showEmptyCategories && group['data'].length != 0))
    										{
    											var limit = group['header']['limit'];
    											var count = 0;
    
    											// Create the group wrapper and header.
    											output += '<li class="'+options.classPrefix+'header">'+"\n";
    											output += '<p class="'+options.classPrefix+'header-text">'+group['header']['title']+'</p>'+"\n";
    											output += '<p class="'+options.classPrefix+'header-limit">'+options.resultsText.replace("%", group['header']['num']).replace("$", (group['header']['limit'] < group['data'].length ? group['header']['limit'] : group['data'].length))+'</p>'+"\n";
    											output += '</li>';
    
    											// Run through each of the group items in this group and add them to the HTML.
    											var fill_code = (options.fillBox) ? 'document.getElementById(\''+inputObj.attr('id')+'\').value = \'%\';' : '';
    											$.each(group['data'], function (j, item) {
    												if (count < limit)
    												{
    													// Build the link opening tab.
    													var link_open = '<a href="';
    													link_open += (item['url'] != undefined) ? item['url'] : 'javascript: void(0);';
    													link_open += '" ';
    													link_open += (item['onclick'] != undefined) ? ' onclick="'+fill_code.replace("%", item[options.fillBoxWith])+(options.executeCode ? item['onclick'] : '')+'" ' : '';
    													link_open += '>';
    
    													// Open the item wrapper DIV and the anchor.
    													output += '<li class="'+options.classPrefix+'result">'+link_open+"\n";
    
    													// Create the various HTML elements, including the image, primary text, and secondary text.
    													output += '<table border="0" cellspacing="0" cellpadding="0" width="100%"><tr>';
    													output += (item['image'] != undefined && options.showImages) ? '<td width="40"><img src="'+item['image']+'" /></td>'+"\n" : '';
    													output += '<td>';
    													output += '<p>';
    													output += (item['primary'] != undefined) ? '<span class="'+options.classPrefix+'result-title">'+item['primary']+"</span><br />\n" : '';
    													output += (item['secondary'] != undefined) ? ''+item['secondary']+''+"\n" : '';
    													output += '</p>'+"\n";
    													output += '</td>';
    													output += '</tr></table>';
    
    													// Close the item wrapper DIV and the anchor.
    													output += '</a></li>'+"\n";
    												}
    
    												count++;
    											});
    										}
    									});
    								}
    
    								// Display the new suggestion box.
    								boxObj.html(output);
    								
    								boxObj.css('position', 'absolute');
    								boxObj.css('top', inputObj.offset().top+inputObj.outerHeight());
    								boxObj.css('left', inputObj.offset().left);
    								
    								boxObj.fadeIn();
    								
    								// Change the input class back to the default state.
    								inputObj.removeClass(options.classPrefix+'input-thinking');
    							}
    						});
    						
    					}, options.timeoutLength);
    				}
    				
    			}
    			
    		});
    		
    		
    		
    		// Whenever the input field is blurred, close the suggestion box.
    		inputObj.blur(function() {
    			boxObj.fadeOut();
    		});
    		
    		// If the lastQuery variable is equal to what's currently in the input field, show the box. This means that the results will still be valid for what's in the input field.
    		inputObj.focus(function(){
    			if (inputObj.val() == lastQuery && inputObj.val() != '')
    			{
    				boxObj.fadeIn();
    			}
    		});
    	};
    	
    	
    	
    	function unsetTimeout(timeout)
    	{
    		clearTimeout(timeout);
    		timeout = null;
    	};
    })(jQuery);
    any help with this would be greatly appreciated,

    thanks
    Luke
    Last edited by LJackson; 08-30-2013 at 02:14 PM.

  • #2
    Senior Coder
    Join Date
    Jan 2011
    Location
    Missouri
    Posts
    4,303
    Thanks
    23
    Thanked 612 Times in 611 Posts
    I have done a autosuggest before and don't remember it being this complex. Would a select a drop-down list work better for you? How many town/villages are we talking here?
    Evolution - The non-random survival of random variants.

    "If you leave hydrogen alone, for long enough, it begins to think about itself."

  • #3
    Senior Coder
    Join Date
    Jun 2008
    Location
    Cornwall
    Posts
    2,098
    Thanks
    297
    Thanked 12 Times in 12 Posts
    there are approx 1600 in the database. Not sure a dropdown would be suitable as each town/village has a description that is shown underneath its title to tell the user a bit more about it, not sure that is possible in dropdown lists?

    thanks
    Luke

  • #4
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,981
    Thanks
    56
    Thanked 557 Times in 554 Posts
    I guess depending on the nature of the JSON results returned that you could use a hidden input and when the name is selected, fill that with the corresponding ID and use that to submit to the DB.

    I have to agree with sunfighter, though - your autosuggest looks overly complicated. It looks (at a glance) like the old jQuery plugin, which was superceded in many ways by the UI version

  • #5
    Senior Coder
    Join Date
    Jun 2008
    Location
    Cornwall
    Posts
    2,098
    Thanks
    297
    Thanked 12 Times in 12 Posts
    hmm thats a good idea xelawho, might give that a try

    the autosuggest feature i bought off codecanyon and can be found at.
    http://codecanyon.net/item/smart-sug...complete/80946

    thanks for your help
    Luke

  • #6
    Senior Coder
    Join Date
    Jun 2008
    Location
    Cornwall
    Posts
    2,098
    Thanks
    297
    Thanked 12 Times in 12 Posts
    that seems to work just added this to my js code

    Code:
    													
    var elem = document.getElementById("locID");
    elem.value = (item['placeID']);
    thanks for you help mate!!
    Luke

  • #7
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    11,068
    Thanks
    0
    Thanked 256 Times in 252 Posts
    In the onclick data, call a js function passing the id. The function then set a hidden field for the id.

    PHP Code:
    $final['data'][] = array( 
            
    'primary' => $name
            
    'secondary' => $data['desc'], 
            
    'onclick' => 'setPlaceId(\''.$id.'\');',
            
    'fill_text' => $name 
        
    ); 
    Code:
    function setPlaceId(id) {
        $('#placeID').val(id); 
    }
    Code:
    <input type="hidden" name="placeID" id="placeID" />
    EDIT: I have basically the same suggestion as xelawho's. I didn't see his post because I didn't refresh this page when I posted my reply.
    Last edited by glenngv; 08-30-2013 at 06:08 PM.
    Glenn
    ____________________________________

    My Blog
    Tower of Hanoi Android app (FREE!)
    Tower of Hanoi Leaderboard
    Samegame Facebook App
    vBulletin Plugins
    ____________________________________

  • #8
    Senior Coder
    Join Date
    Jun 2008
    Location
    Cornwall
    Posts
    2,098
    Thanks
    297
    Thanked 12 Times in 12 Posts
    then again maybe i was being a little too gung-ho it always returns the last records ID in the db no matter what option is chosen

    @glenngv - just tried your suggestion and im getting the same result, it always returns the last id in the db
    any ideas as to why this might be?

    thanks
    Last edited by LJackson; 08-30-2013 at 06:13 PM.

  • #9
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,981
    Thanks
    56
    Thanked 557 Times in 554 Posts
    I think as glennv points out, the important bit is probably *where* you are placing that code - if it's within the onclick event that fills the name input, they should line up

  • #10
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    11,068
    Thanks
    0
    Thanked 256 Times in 252 Posts
    Wrong variable. It should be:

    PHP Code:
    'onclick' => 'setPlaceId(\''.$data['id'].'\');'
    Glenn
    ____________________________________

    My Blog
    Tower of Hanoi Android app (FREE!)
    Tower of Hanoi Leaderboard
    Samegame Facebook App
    vBulletin Plugins
    ____________________________________

  • Users who have thanked glenngv for this post:

    LJackson (08-30-2013)

  • #11
    Senior Coder
    Join Date
    Jun 2008
    Location
    Cornwall
    Posts
    2,098
    Thanks
    297
    Thanked 12 Times in 12 Posts
    @xelawho nope each way both produces the same result id is always 1479 which is the id of the last place in the db.

    thanks
    luke

  • #12
    Senior Coder
    Join Date
    Jun 2008
    Location
    Cornwall
    Posts
    2,098
    Thanks
    297
    Thanked 12 Times in 12 Posts
    thanks @glenngv that solved it!!!

    thanks for all you help and support guys appreciate it!


  •  

    Posting Permissions

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