À l'aide de typeahead, je renvoie des valeurs qui contiennent deux données. J'ai besoin de diviser ces données en deux champs différents.

$(document).ready(function(){
  $('#mail_field').typeahead({
	source:  function (query, process) {
		return $.post('http://127.0.0.1:8000/api/userdetailstypeahead', { query: query }, function (data) {
			//console.log(data);
			return process(data); //sample result in the #mail_field: John.Doe@jjc.com - Accounting  
                                              //want data to split into two separate fields 
		  });
	  }
  });
  $('#department_field').typeahead({});
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>
if(count($results)){
$sugge = [];
  foreach($results as $user){
    $temp =[];
    $temp["department"] = $user->department[0];
    $temp["mail"] = $user->mail[0];
    $sugge[] = $temp;
  }

  $result["data"] = $sugge;
  $result["success"] = 1; 

  foreach($result["data"] as $user){
    $data[] = "{$user["mail"]} - {$user["department"]}" ; // I need the mail and department in 2 different fields
  }
  return response()->json($data);
}
0
Samuel Omopariola 4 nov. 2019 à 13:24

2 réponses

Déclarez deux variables:

var f1 = {};
var f2 = {};

dans votre réponse:

f1 = data.field1;
f2= data.field2;
1
theduck 6 nov. 2019 à 13:01

C'est la solution au problème ci-dessus qui permet de transmettre les valeurs de la boucle foreach en tant qu'objet de données et, par conséquent, de pouvoir les récupérer user data.mail et data.department dans le script.

foreach($result["data"] as $user){
  //$data[] = "{$user["mail"]}" ;
  if($user['mail'] != null ){
    $data['mail'][] = $user['mail'];
    $data['department'][$user['mail']] = $user['department'];
  }
}

<script>
  $(document).ready(function(){
  $('#mail_field').typeahead({
    source:  function (query, process) {
    return $.post('http://127.0.0.1:8000/api/userdetailstypeahead', { query: query }, 
    function (data) {
        //console.log(data.mail);
        //console.log(data.department);
        window.department = data.department;
        return process(data.mail);
      });
  },
  afterSelect : function(value){
    console.log(window.department[value]);
    //console.log(value);
    //console.log(window.department);
    $('#department_field').val(window.department[value]);
  }
});
});
</script>
0
Samuel Omopariola 5 nov. 2019 à 09:26