Get name and id of autocomplete suggestions into input field - javascript

I have the code below, which I use to type and suggest a few relation names in an input field. The data variable right now returns only names like:
var data = ["name": "Relation 1", "name":"Relation 2"]
I modified it and now it has data like:
var data = [
{"id":1,"name":"Foo"},
{"id":2,"name":"Bar"},
{"id":3,"name":"Foo Bar"}
];
How do I append the id of the selected name in the id input?
$('input.relation').typeahead({
source: function (query, process) {
return $.get('live_search.php?filter=relation', { query: query }, function (data) {
console.log(data);
data = $.parseJSON(data);
return process(data);
});
}
});
<div class="form-group">
<label for="relation"> Relation </label>
<input class="relation form-control" type="text">
<input class="relation-id form-control" type="text" name="id">
</div>

Related

How to make a function update the value of angular inputs

When I select one of the cards on the page below, I wish to have the value of the inputs updated with values from a JSON object
The json:
{
"status": true,
"data": [
{
"id": 1,
"pessoa_id": 75505,
"created_at": "2022-02-01T17: 42: 46.000000Z",
"holder": "LEONARDO LIMA",
"validade": "2026-06-01",
"bandeira": "Mastercard"
}
]
}
The json value is on the variable "responseData"
renderTokenCard() {
this.mundipaggS.checkToken().subscribe((response: any) => {
console.log(JSON.stringify(response));
this.cartS.tokenCard = response;
this.responseData = response;
console.log(JSON.parse(JSON.stringify(response)));
},);
}
the function that is linked to the select action:
SelecionarCartao() {
this.mundipaggS.postToken(this.responseData)
console.log(this.responseData)
}
I wanted to get the responseData value and make a post for the postToken
The HTML
<div class="form-group ">
<label for="ncartao">Número do cartão <span class="text-danger"> *</span></label>
<input name="card-number" maxlength="19" #cardNumber formControlName="digiNumero" id="ncartao" type="text"
class="form-control col-lg-6 ">
</div>
<div class="form-group">
<label for="nomeimpresso">Nome <b>impresso</b> no cartão<span class="text-danger"> *</span></label>
<input #nomeImpresso formControlName="digiNome" name="holder-name" id="nomeimpresso" class="form-control col-lg-6"
type="text">
</div>
"Think in functions". If you has a function like
getGroup(data:any=null)
{
//data will be the properties by defect and, using spread operator,
//replace the properties by the data object
data={
id: 0,
pessoa_id:0,
created_at:"",
holder: "",
validade: "",
bandeira:"",
...data
}
return new FormGroup({
id: new FormControl(data.id),
pessoa_id: new FormControl(data.pessoa_id),
created_at:new FormControl(data.created_at),,
holder: new FormControl(data.holder),,
validade: new FormControl(data.validade),,
bandeira:new FormControl(data.bandeira),}
})
}
Each change in "Meus Cartoes"
change(bandeira:string)
{
const data=this.responseData.data.find(x=>x.bandeira==bandeira)
if (data)
this.form=getGroup(data) //<--a form with all the data
else
this.form=getGroup({bandeira:bandeira}) //<--a form with the "bandeira"
}
NOTE: really the "form" need split the "validate", get the "numero do cartao" and the "nome_impreso"...

Creating custom dynamic JSON string

I am trying to achieve the following dynamic JSON string creation. I can produce the id part but don't how to produce the name part. Ids are from the list and name is from the textbox.
I tried a lot but nothing seems to work. I want to select both strings and text box should result as below.
{
"name": "GROUP-X1",
"objects": [{ // this part is needed as a complete string
"type": "Host",
"id": "0050569A-7800-0ed3-0000-008589948757"
}, {
"type": "Host",
"id": "0050569A-7800-0ed3-0000-008589945523"
}]
}
var output = createJSON1();
function createJSON1() {
var arr = $("#select1 > option").map((index, val) => ({
"type": "Host",
id: val.value
})).get();
return JSON.stringify(arr);
}
console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="text" id="srch-obj" value="GROUP-X1">
<select id="select1" multiple size="2" style="width: 480px">
<option>0050569A-7800-0ed3-0000-008589948757</option>
<option>0050569A-7800-0ed3-0000-008589945523</option>
</select>
Your code already builds the objects array. As such, all you need to do is wrap the output within another object providing the name property which you can retrieve from the value of #srch-obj. Try this:
var output = createJSON1();
function createJSON1() {
let obj = {
name: $('#srch-obj').val(),
objects: $("#select1 > option").map((t, el) => ({
type: "Host",
id: el.value
})).get()
}
return JSON.stringify(obj);
}
console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="text" id="srch-obj" value="GROUP-X1">
<select id="select1" multiple size="2" style="width: 480px">
<option>0050569A-7800-0ed3-0000-008589948757</option>
<option>0050569A-7800-0ed3-0000-008589945523</option>
</select>

Input field auto complete search select name and store the id in input box laravel

Using laravel and jquery for input field autocomplete. I need to select name and store the id of that user in input field.
<input id="show-user" type="text" class="typeahead form-control" name="student_code" value="{{ old('student_code') }}" placeholder="Student Code" required>
Here is javascript code
var path = "{{ url('library/issue-books/autocomplete/') }}";
$('input.typeahead').typeahead({
source: function (query, process) {
return $.get(path, { query: query }, function (data) {
return process(data);
});
}
});
Controller code for ptah
$data = User::where("name","LIKE","%{$request->input('query')}%")->get();
return response()->json($data);
Now my problem is when I select name, need to send student code in request. Student_code integer column.
You can send the input value to your route:
return $.get(path + $('#show-user').val(), {}, function (data) {
return process(data);
});
In this way you should have this route syntax:
/library/issue-books/autocomplete/{$query}
But you can pass just a query string also:
return $.get(path + '?query=' + $('#show-user').val(), {}, function (data) {
return process(data);
});

Typeahead not suggesting for second option

I have two typeahead inputs, first one is running fine and printing Customers names,
second one is having an issue, after looking at the console I can see that the view is being executed and is returning some results, but it is not appearing in the field. any help is appreciated as I am stuck and I have literally checked every question for an answer with no luck.
creates.blade.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.1/bootstrap3-typeahead.min.js"></script>
<div class="form-group">
<strong>Customer Name:</strong>
<input class="form-control" type="text" name="customer_id" id='cust' onkeypress="myFunction()" placeholder="Customer Name">
</div>
<div class="form-group">
<strong>Card Number:</strong>
<input class="form-control" type="text" name="card_id" id='card' onkeypress="myFunction1()" placeholder="Card Number">
</div>
function myFunction()
{
var path = "{{ route('autocomplete') }}";
$('#cust').typeahead({
name: 'cust',
source: function (query, process) {
return $.get(path, { query: query }, function (data) {
return process(data);
});
}
});
}
function myFunction1()
{
var path = "{{ route('autocompletecard') }}";
$('#card').typeahead({
name: 'card',
source: function (query, process) {
return $.get(path, { query: query }, function (data) {
return process(data);
});
}
});
}
Controllers:
public function autocomplete(Request $request)
{
$data = Customer::select("name")
->where("name","LIKE","%{$request->input('query')}%")
->get();
return response()->json($data);
}
public function autocompletecard(Request $request)
{
$data = Card::select("number")
->where("number","LIKE","%{$request->input('query')}%")
->get();
return response()->json($data);
}
routes:
Route::get('autocomplete', 'AssigneeController#autocomplete')->name('autocomplete');
Route::get('autocompletecard', 'AssigneeController#autocompletecard')->name('autocompletecard');
I am getting correct results on the console and but not being prompted to have results displayed on the screen.

Create JSON in specific format

I need send a json via post to api in this format:
"answer" => {
"name"=>"Test",
"email"=>"test#test.com",
"hospital"=>"Hospital Name",
"answered_questions_attributes"=>{
"0"=>{
"value"=>"1",
"question_id"=>"1"
},
"1"=>{
"value"=>"0",
"question_id"=>"2"
},
"2"=>{
"value"=>"1",
"question_id"=>"3"
}
}
}
I get the "answered_questions_attributes" data from inputs, the values are true or false and the name of the input is the question ID, eg:
<div class="resp_val_div">
<input type="hidden" name="1" value="1" />
<input type="hidden" name="2" value="0" />
<input type="hidden" name="3" value="1" />
</div>
I tried the code below, but this only returns a incorrect json:
var resp_val = jQuery(".resp_val_div").find("input");
var dados = {
"name": jQuery("#name").val(),
"email": jQuery("#email").val(),
"hospital": jQuery(".answer_hospital").val(),
'answered_questions_attributes':[]
};
resp_val.each(function(index, el) {
d = {"value":parseInt(el.value), "question_id":el.name};
dados.answered_questions_attributes.push(d);
});
console.log(dados);
"answer"=>{
"name"=>"Test",
"email"=>"test#test.com",
"hospital"=>"Hospital Test",
"answered_questions_attributes"=>[
{
"value"=>1,
"question_id"=>"1"
},
{
"value"=>0,
"question_id"=>"2"
},
{
"value"=>1,
"question_id"=>"3"
}
]
}
How can i create the first json in this case?
Don't use an array and .push() if you want an object. And don't use parseInt() if you want the value property to be a string rather than a number.
var dados = {
"name": jQuery("#name").val(),
"email": jQuery("#email").val(),
"hospital": jQuery(".answer_hospital").val(),
'answered_questions_attributes':{}
};
resp_val.each(function(index, el) {
d = {"value":el.value, "question_id":el.name};
dados.answered_questions_attributes[index] = d;
});

Categories