Javascript autocomplete with different input field value - javascript

I have the following javascript that autocompletes based on a users display name. Problem is that the autocomplete input field is the display name. Each user actually has a user id, but I want to look up the user in the autocomplete based on the display name but when I submit the form I want to submit the user ID itself.
<script>
$(document).ready(function() {
$("input#autocomplete").autocomplete({
source: [
"John Doe",
"Another User",
]
});
});
</script>
<input id="autocomplete" name="autocomplete"/>
Can anyone suggest how i can do this? Ideally in the source, is there a way to have the user ID as the value too and somehow have the user ID submitted but with display name?

instead of using just an array you could use object inside the array so you can still do your search for matching display name and return the user id
instead of:
source: [
"John Doe",
"Another User",
]
you can do:
var sourceValues = [
{label: "John Doe", value: 1},
{label: "Another User", value: 2},
]
$("#autocomplete").autocomplete({
source: sourceValues.map(lang=>lang.label),
});

Consider the following example.
$(function() {
$("#user_name").autocomplete({
source: [{
label: "John Doe",
value: 1001
}, {
label: "Jonny Appleseed",
value: 1002
},{
label: "Jane Doe",
value: 1003
}],
select: function(e, ui) {
$("#user_name").val(ui.item.label);
$("#user_id").val(ui.item.value);
return false;
}
});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.1/jquery-ui.js"></script>
<div>Name: <input id="user_name" /></div>
<div>ID: <input type="text" id="user_id" /></div>
This is based on this example: https://jqueryui.com/autocomplete/#custom-data
If you define a more complex source, you can make use of it in the select callback. ui.item represents the object selected. It has a label and value that you can put in various fields.

Related

Placing an array of jQuery objects into html form elements

I have this array of jQuery objects
(2) [{…}, {…}]
0:{Name: "name", NRIC/Passport: "nric", Date of Birth: "2018-06-02", Occupation: "occ", Weight: "123", …}
1:{Name: "name2", NRIC/Passport: "nric2", Date of Birth: "2018-06-02", Occupation: "occ2", Weight: "234", …}
length:2
__proto__:Array(0)
I want to place them into html form elements. Currently this is how I do it:
$.each(spouses,function(key,value){
$.each(value,function(int_key,int_value){
$("#spouse_data").append("<div class='col-sm-4'><label>"+int_key+"</label><input type='text' readonly class='form-control' name='spouse' value="+int_value+"></div>");
});
});
However, I won't be able to set a name for each of the form elements so that I can receive the data when I submit the form.
There is another option where instead of using this format of object
"Name of obj":data
I use
name_of_obj:data
The problem with the second one is that I can't insert label names. I was wondering what the best way of doing this is.
Change your objects to an array of objects looking somewhat like this:
[{ value: 'name', label: 'Name', name: 'name' }, { value: 'nric', label: 'NRIC/Passport', name: 'nric_password' }]
Then iterate over it using Array.prototype.forEach:
[{
value: 'name',
label: 'Name',
name: 'name_for_form_submission'
}, {
value: 'nric',
label: 'NRIC/Passport',
name: 'nric_password'
}].forEach((item) => {
console.log(`${item.label}: ${item.value}, form name: ${item.name}`)
})
What about using the following for your form elements:
name="spouse[' + index + ']"
Does it make sense to use an array field type instead of a string?
check this code, you can do it like this
https://codepen.io/creativedev/pen/pKjamd
var obj = {
0: {Name: "name", "NRIC/Passport": "nric", "Date of Birth": "2018-06-02", Occupation: "occ", Weight: "123"},
1: {Name: "name2", "NRIC/Passport": "nric2", "Date of Birth": "2018-06-02", Occupation: "occ2", Weight: "234"}
};
$.each(obj,function(key,value){
$.each(value,function(key1,value1){
$("#data").append("<div class='col-sm-4'><label>"+key1+"</label><input type='text' readonly class='form-control' name='spouse' value="+value1+"></div>");
});
$("#data").append("<br/><br/>");
});

Knockout : Unusual Mapping Pattern

Scenario: I make a request to the server for a part. It gives me this back (it's pseudo, but represents what I'm looking at):
{
PartNumber : "XYZ",
Description: "ABCFOO",
ProductClass: "Widget",
FieldList:[
{Name: "PROGRAM TYPE", Value: "Program3"},
{Name: "SHIP", Value: false},
{Name: "NOTES", Value: "SomeValue1"}
],
MoreStuff : [{
...
}]
}
Note the FieldList list of elements, that's the focus here.
The server also gave me a list of certain fields, their types and default values. It looks like this:
[
{FieldName : "PROGRAM TYPE", FieldType: "List", Defaults: [{Name:"Program 1", Value: "Program1"},{Name:"Program 2", Value: "Program2"},{Name:"Program 3", Value: "Program3"}]},
{FieldName : "SHIP", FieldType : "Boolean", Defaults: []},
{FieldName : "NOTES", FieldType: "TextArea", Defaults: []}
]
That comes in a seperate REST call, and the prior to loading my Part. I use it to create part of the HTML page for the Part. You can see they're similarly related to the FieldList section from when I ask for Part.
From that "list of fields" and defaults -- I generate the appropriate HTML elements on the page. If it's a Boolean field type, I create a checkbox - if it's a list, I create a SELECT (with options given in Defaults), TextArea is a text-area, etc. That all works fine. It ends up looking like:
<input data-bind="textInput: PartNumber"/>
<textarea data-bind="textInput: Description"></textarea>
<!-- generating fieldlist - i create a pseudo attr because the field name can have spaces-->
<select field_label="PROGRAM TYPE"> <!-- how the heck do i bind to this??-->
<option value="Program1">Program 1</option>
<option value="Program2">Program 2</option>
<option value="Program3">Program 3</option>
</select >
<input type="checkbox" field_label="SHIP" value="true"/> <!-- or this, how to bind to it?!-->
<!-- end of field list generation -->
Now I take the object (the part I'm given) and put that into my ViewModel - that is all working just swimmingly. I make it easy and just use ko.mapping.fromJS(rest_data); Works just fine.
Data binding is ducky -- for what I am able to bind it to. My issue comes from -- how the heck do I map my FieldList to the HTML I generated for the fields the server gave me?. My data / my viewmodel object has FieldList in it, with a buncha stuff I want to map to that generated stuff. The only real "key" I have is the self-created field_label I have, because the server's FieldName can have spaces.
So I guess what I'm asking is, I have that array of FieldList from my part. I have the whole Part object in my view model and it's all fine. How do I take that FieldList and map it into my self-generated set of fields from the other object (ie., take the FieldList name and tie it to the element with field_label of the same value?)
Spelled out - it'd be like: How to map FieldList with Name of "PROGRAM TYPE" to HTML element having field_label of "PROGRAM TYPE".
I begin to think something like this might be the direction I should be going:
http://jsfiddle.net/MhdZp/128/
but it goes over my head.
One way to approach this:
function Option(definition) {
this.definition = definition;
this.value = ko.observable();
this.templateName = 'input-template-' + definition.FieldType;
}
function ViewModel() {
var self = this;
// from REST call
var fieldDefinition = [{
FieldName: "PROGRAM TYPE",
FieldType: "List",
Defaults: [
{ Name: "Program 1", Value: "Program1" },
{ Name: "Program 2", Value: "Program2" },
{ Name: "Program 3", Value: "Program3" }
]
}];
self.options = ko.observableArray();
// for the sake of the example
self.options.push(new Option(fieldDefinition[0]));
// methods
self.optionByName = function (name) {
return ko.utils.arrayFirst(self.options(), function (option) {
return option.Name = name;
});
};
// poor man's init, imagine 2nd rest call instead
self.optionByName("PROGRAM TYPE").value("Program3");
}
and
<script type="text/html" id="input-template-List">
<label data-bind="text: definition.FieldName"></label>
<select data-bind="
value: value,
options: definition.Defaults,
optionsText: 'Name',
optionsValue: 'Value',
optionsCaption: 'Please select...'
"></select>
</script>
and
<div data-bind="foreach: options">
<div data-bind="template: templateName"></div>
</div>
Add more templates as needed, this should be very easy to extend.
jsFiddle: http://jsfiddle.net/0nxt2zte/

how to validate div element in angular UI bootstrap?

I make view from array of object into view .But My problem is that I take div element inside the li and ui .Now I want to validate element like "number", "url","email".I need to validate element on blur and keyup.Some elements may be required some not .I need to show this using "*".I know how to validate using form when I take form I used
<span ng-show="myForm.name.$error.required" class="help-inline">
But now i have div element inside li .how I will validate .?
http://plnkr.co/edit/we1QHuDuCOOR4tDAk6yv?p=preview
function Controller($scope) {
$scope.outputs = {};
$scope.inputs = [{
type: "email",
name: "email",
required:true
}, {
type: "text",
name: "name",
}, {
type: "number",
name: "phonenumber",
}, {
type: "checkbox",
name: "whant to check",
},
{
type: "url",
name: "server Url",
}];
}
or is there any way to insert all element in form ?
You can use Angular Form Validation.
When i was searching about this, i found out this tutorial. It has helped me alot.
Try your self.

get selected id of kendo drop down value

how to get id of selected name from dropdown.
whene select Apples then got id 1and select Oranges then 2.
this is simple kendo dropdown example.
<body>
<input id="dropdownlist" />
<script>
$("#dropdownlist").kendoDropDownList({
dataSource: [
{ id: 1, name: "Apples" },
{ id: 2, name: "Oranges" }
],
dataTextField: "name",
dataValueField: "id",
index: 1,
select: onSelect
});
function onSelect(e) {
console.log(e);
};
</script>
</body>
thanks.
In order to retrieve the selected Id you can use the dataItem object and access the id within it with change event:
var dataItem = e.sender.dataItem();
$('#id').text(dataItem.id);
This will get you access to any data within the object too:
$('#name').text(dataItem.name);
Working example
http://jsfiddle.net/ygBq8/1/
Html
<input id="dropdownlist" /><br/>
<span id="id" >Id</span><br/>
<span id="name" >Name</span><br/>
JavaScript
$("#dropdownlist").kendoDropDownList({
dataSource: [
{ id: 1, name: "Apples" },
{ id: 2, name: "Oranges" }
],
dataTextField: "name",
dataValueField: "id",
index: 1,
change: onChange
});
function onChange(e) {
var dataItem = e.sender.dataItem();
$('#id').text(dataItem.id);
$('#name').text(dataItem.name);
};
The Select event is a bit more difficult one to use, as that event fires before the item is selected.
If you use the Change event, you should be able to get the dataItem with
this.dataSource.get(this.value())
See sample http://jsbin.com/OcOzIxI/2/edit
Please use this.dataItem()
function onSelect(e) {
alert(this.dataItem().id);
alert(this.dataItem().Name);
};
To select ID of the selected item use:
$("#dropdownlist").val()
And to select TEXT of the selected item use:
$("#dropdownlist").data("kendoDropDownList").text()

How do I set the value for a select statement?

http://jsfiddle.net/WcJbu/
When I select a person, I want the favoriteThing selector to display their current selection.
<div ng-controller='MyController'>
<select ng-model='data.selectedPerson' ng-options='person.name for person in data.people'></select>
<span ...> likes </span>
<select ... ng-model='data.favoriteThing' ng-options='thing.name for thing in data.things'></select>
</div>
$scope.data.people = [{
name: 'Tom',
id: 1,
favorite_thing_id: 1
}, {
name: 'Jill',
id: 2,
favorite_thing_id: 3
}];
$scope.data.things = [{
name: 'Snails',
id: 1
}, {
name: 'Puppies',
id: 2
}, {
name: 'Flowers',
id: 3
}];
Do I need to set up a service and add watches, or is there a [good] way to use the favorite_thing_id directly in the select?
Change the second select to this:
<select ng-show='data.selectedPerson' ng-model='data.selectedPerson.favorite_thing_id'
ng-options='thing.id as thing.name for thing in data.things'></select>
Adding the thing.id as to the ng-options will allow you to select the data.things entries based on their id's instead of their references. Changing the ng-model to data.selectedPerson.favorite_thing_id will make angular automatically change to the correct option based on selectedPerson.favorite_thing_id.
jsfiddle: http://jsfiddle.net/bmleite/4Qf63/
http://jsfiddle.net/4Qf63/2/ does what I want - but it's pretty unsatisfying.
$scope.$watch(function() {
return $scope.data.selectedPerson;
}, function(newValue) {
if (newValue) {
$scope.data.thing = $filter('filter')($scope.data.things, {id: newValue.favorite_thing_id})[0];
}
})
I'd like to see all of that be possible from within the select statement.
Maybe I'll try to write a directive.
association = {key: matchValue}
So that I can do
<select ... ng-model='data.thing' ng-options='t.name for t in data.things' association='{id: "data.selectedPerson.favorite_thing_id"}'></select>

Categories