How to dynamically get satisfy autocomplete value using .attr() or .on('click', from same source?

83 views Asked by At

I have two input fields.

<input type="text" name="image" />
<input type="text" name="file" />

Javascript

 $('input[name=\'image\'], input[name=\'file\']').autocomplete({ 
    minLength: 2,
    source: function( request, response ) {
        var thisType = $(this).attr('name');
        $.getJSON( "files/", {
            term: extractLast( request.term ),
            type: thisType
        }, response );
    },
    create: function () {
        var thisType = $(this).attr('name');
        if (thisType == 'image') {
            $(this).data("autocomplete")._renderItem = function(ul, item) {
                return $("<li></li>")
      .data("item.autocomplete", item)
     .append('<a><img src="files/' + item.label + '.jpg" />' + item.label + '</a>')
                    .appendTo( ul );
            };
        } else {
            $(this).data("autocomplete")._renderItem = function(ul, item) {
                return $("<li></li>")
                    .data("item.autocomplete", item)
                    .append('<a>' + item.label + '</a>')
                    .appendTo( ul );
            };
        }
    },
    });

PHP

 <?php
    if (empty($_GET['term'])) exit;

    $q = strtolower($_GET["term"]);

    $type = strtolower($_GET["type"]);

    if (get_magic_quotes_gpc()) $q = stripslashes($q);

    $files = array();

    if ($type == 'image') {
        foreach(glob('image/*.jpg*', GLOB_BRACE) as $key=>$file) {
            $files[] = substr($file, 0, -4);
        }
    } else {
        foreach(glob('image/*.txt*', GLOB_BRACE) as $key=>$file) {
            $files[] = substr($file, 0, -4);
        }
    }

    $files = array_unique($files);
    $files = array_combine($files, $files);

    $result = array();
    foreach ($files as $key=>$value) {
        if (strpos(strtolower($key), $q) !== false) {
   array_push($result, array("id"=>$value, "label"=>$key, "value" => strip_tags($key)));
        }
        if (count($result) > 11) break;
    }

    echo json_encode($result);

I want when i type on the first input, as results it need to show me image files name with preview and when type on the second input, as results it need to show me only text files name.Is there any way to if click on or when type or using attr dynamically get satisfy value for each input from same source? I am trying to do link this but not working..

0

There are 0 answers