Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass the dynamic value of id to jquery which I get from json?

I got the values from json and pass to the autocomplete search field.

[{"id":1,"name":"JAVA"},{"id":2,"name":"cake PHP"},"id":3,"name":"Android"}]

For example, when I click the JAVA, I want to get the id of JAVA like www.example.com/1

Jquery code:

<script>
$('#search').typeahead({ 
ajax: '/searchendpoint/search', 
onSelect: function() { 
window.location = "/home/view/" + $(this).val().id; }
});
</script> 
like image 565
Ganesh Avatar asked Oct 25 '17 05:10

Ganesh


3 Answers

When you want to use object array as a source you need to provide the logic for:

  1. which object property to use for matching user input
  2. which property to use for displaying text of the matching items
  3. which property to use when user selects an item

More info:

  1. http://api.jqueryui.com/autocomplete/#option-source
  2. http://api.jqueryui.com/autocomplete/#method-_renderItem
  3. http://api.jqueryui.com/autocomplete/#event-select

var tags = [
  {"id":1,"name":"JAVA"},
  {"id":2,"name":"cake PHP"},
  {"id":3,"name":"Android"}
];


$( "#search" ).autocomplete({
  source: function( request, response ) {
          var matcher = new RegExp( $.ui.autocomplete.escapeRegex( request.term ), "i" );
          response( $.grep( tags, function( item ){
              return matcher.test( item.name ); // match user request with item.name
          }) );
      },
  select: function( event, ui ) {
    event.preventDefault();
    $("#search").val( ui.item.name ); // display user selection in textbox

    console.log('selected: ' + JSON.stringify(ui) );
    console.log('execute window.location = "example.com/' + ui.item.id + '"'); // use id of the selected item to generate required URL
    
  }
});

// provide rendering logic for each matched item
$w = $( "#search" ).data("ui-autocomplete");
$w._renderItem = function( ul, item ) {
  //console.log(JSON.stringify(item) );
    return $( "<li>" )
      .attr( "data-value", item.id )
      .append( item.name )
      .appendTo( ul );
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<input id="search">

Edit: Using typeahead.js as per your comment.

var data =
[
  {"id":1,"name":"JAVA"},
  {"id":2,"name":"cake PHP"},
  {"id":3,"name":"Android"}
];


$(function(){
  var substringMatcher = function(strs) {
    return function(q, cb) {
      var matches, substringRegex;
  
      // an array that will be populated with substring matches
      matches = [];
  
      // regex used to determine if a string contains the substring `q`
      substrRegex = new RegExp(q, 'i');
  
      // iterate through the pool of strings and for any string that
      // contains the substring `q`, add it to the `matches` array
      $.each(strs, function(i, str) {
        if (substrRegex.test(str.name)) {
          matches.push(str);
        }
      });
  
      cb(matches);
    };
  };  

  $('.typeahead').bind('typeahead:select', function(ev, suggestion) {
    console.log('Selection: ' + JSON.stringify(suggestion) );
    console.log('execute window.location = "example.com/' + suggestion.id + '"');
  });

  // passing in `null` for the `options` arguments will result in the default
  // options being used
  $('.typeahead').typeahead({
    hint: true,
    minLength: 1
  }, {
    source: substringMatcher(data),
    display: 'name'
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>

    <div id="prefetch">
      <input class="typeahead" type="text" placeholder="">
    </div>

More Info:

  • https://github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md
  • https://twitter.github.io/typeahead.js/examples/#the-basics
like image 164
Vivek Athalye Avatar answered Nov 17 '22 00:11

Vivek Athalye


Try this. Add event select on bind autocomplete.

$(function () {
    var availableTags = [
        {"id":1,"value":"JAVA"},
        {"id":2,"value":"cake PHP"},
        {"id":3,"value":"Android"}
    ];

    $("#search").autocomplete({
        source: availableTags,
        select: function(event, ui) {
            window.location = "www.example.com/" + ui.item.id;
        }
    });
});
like image 29
Kriengkri Pongpanjanthra Avatar answered Nov 17 '22 00:11

Kriengkri Pongpanjanthra


I am not sure that I understand your question, but do you mean something like this?

JSON:

[{"id":1,"name":"JAVA"},{"id":2,"name":"cake PHP"},"id":3,"name":"Android"}]

jQuery:

<script>
var url = "http://example.com/";

$('#search').change(function() {
  window.location = url + $(this).val().id;
});
</script>
like image 1
Edison D'souza Avatar answered Nov 17 '22 01:11

Edison D'souza