Con la ayuda de typeahead, estoy devolviendo valores que contienen dos datos. Necesito dividir estos datos en dos campos diferentes.

$(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 a las 13:24

2 respuestas

Declara dos variables:

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

en tu respuesta:

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

Esta es la solución al problema anterior que permite que los valores pasen del bucle foreach como un objeto de datos y, como resultado, puedan recuperarlo data.mail y data.department en el 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 a las 09:26