Get id and a field value in EasyAutocomplete plugin - javascript

Using easyAutocomplete plugin, I autocomplete an input field and take the selected value and display them on a dropdown .
What I want to do, is have a hidden field that would have the id of the value.
My JSON File returns something like this :
{ "name": "Emily"
"id" : 1
"jobData": [
{
"id":1
"loc":"AL"
},
{
"id":2
"loc":"BG"
}
]
Once I select Emily from my users, my dropdown gets filled with Locations of her job.
How do I also save the Id of the location in a hidden field so that I can send it to my controller?
This is my JS function:
function AutoCompleteS() {
$("#basics").keyup(function(e) {
this.query = e.target.value;
var options = {
url: function(query) {
return "/getUser/"+ query
},
getValue:"name"
list: {
onClickEvent: function() {
var value = $("#basics").getSelectedItemData();
function toArray(value){
return value.loc;
}
var allLocations=value.jobData.map(toArray);
$.each(allLocations,function(i,p){
$('#select').append($('<option></option>').val(p).html(p));
})
}
}
};
$('#basics').easyAutocomplete(options);
});
}
How do I get and pass the id ?
EDIT:
html code:
<label for="client1" class=" control-label">First Client</label> <input type="text" name="client" value="" class="form-control input-lg " id="basics"/>
<label for="sel1">Select location:</label>
<select class="form-control input-lg" id="select" >
<option></option>
<input type="text" class="hidden" />
</select>

easyAutocomplete issues:
Your code should be more like this (see remote data source example) - i.e. you should only call easyAutocomplete once:
$("#basics").easyAutocomplete({
url: function(query) {
return "/getUser/" + query;
},
getValue: "name",
list: {
// ...
}
});
HTML issues:
Move the input outside the select, and give them both names (so the values can be submitted to server):
<select class="form-control input-lg" id="select" name="location">
<option></option>
</select>
<input type="text" class="hidden" name="job-id" id="job-id">
To set the value of the hidden field when the select value changes, you need a change handler:
function updateSelect(jobData) {
// Reset options:
$("#select")
.empty()
.append(new Option());
// Add locations:
jobData.forEach(function(job) {
$("#select").append(new Option(job.loc));
});
// Handle dropdown change:
$("#select")
.off("change")
.on("change", function() {
// Reset job id (needed when user selects blank option at top of dropdown)
$("#job-id").val("");
var selectedLocation = this.value;
jobData.forEach(function(job) {
if (job.loc === selectedLocation) {
// Copy job id to hidden field:
$("#job-id").val(job.id);
}
});
});
}
Call updateSelect from your easyAutocomplete onClickEvent handler:
onClickEvent: function() {
var value = $("#basics").getSelectedItemData();
updateSelect(value.jobData);
}

Related

Append options to select2

I have the following select:
<select id="street" name="client[street_id]" class="form-control select2" data-placeholder="Select or Insert The Street" style="width: 100%;">
#foreach($streets as $street)
<option value="{{ $street->id }}">{{ $street->name }}</option>
#endforeach
</select>
And the initialisation:
$(".select2").select2({tags: true});
Note that multiple has not been set to true. The problem is when I enter a new option (tag), first time will add the tag but second time will replace the first one in the list. So how can I add options in the select and keep them? (on each add I will make a request to server to save to db).
https://jsfiddle.net/8c7ujd4g/
I found this solution:
$('.select2').on("select2:select", function(e) {
// what you would like to happen
if(e.params.data.isNew){
$(this).find('[data-select2-tag="true"]').replaceWith($('<option selected>', { value : e.params.data.id })
.text(e.params.data.text));
$.ajax({
// ...
});
}
});
$(".select2").select2({tags: true,
createTag: function (params) {
var term = $.trim(params.term);
if (term === '') {
return null;
}
return {
id: term,
text: term,
isNew: true // add additional parameters
}
}
});

Populate dropdown list dynamically in AngularJS

I'm trying to generate dynamic form based on the key of document fields and using ng-if attribute in AngularJS.
Ex:
- If field name is "name|string" then populate textfield
- If field name is "name|select" then populate dropdownlist
- If field name is "name|datepicker" then populate datepicker
Following is the code:
<div class="form-group" ng-repeat="(index, formVal) in providerModelData" ng-if="!$first">
<label>{{mySplit(index,0) | uppercase}}</label>
<div ng-if="!mySplit(index,1)">
<input type="text" class="form-control" ng-model="providerModelData[index]">
</div>
<div ng-if="mySplit(index,1) == 'datepicker'">
<input type="text" class="form-control" ng-model="providerModelData[index]">
</div>
<div ng-if="mySplit(index,1) == 'select'">
<select class="form-control" ng-init="getDropdownData(index,colName)" ng-options="dropdown._id for dropdown in dropdownData[colName]">
<option value="">Select</option>
</select>
</div>
</div>
controller:
$scope.mySplit = function(string, nb) {
var array = string.split('|');
return array[nb];
}
textfields are working fine and populating data but I'm facing issue while populating dropdown fields.
Example: I've two dropdown fields in my mongodb document i.e. city|select and state|select
I'm trying to use ng-options to call function by passing index and colName (document name) to populate dropdownlist but its not working.
Following is the code:
$scope.dropdownData = {};
$scope.getDropdownData = function (query, colName) {
$http.get('/getdropdowndata/', {
params: {
query: query,
colName: colName
}
}).success(function (response) {
$scope.dropdownData[colName] = response;
});
};
Express:
router.route('/').get(function (req, res) {
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
console.log(query.query);
db.collection(query.colName).aggregate([{
"$group":{
"_id":"$"+query.query
}
}],function (err, docs) {
console.log(docs);
res.json(docs);
});
});
Initially I tried calling function in ng-repeat but it was going into infine loop. Then later I tried ng-init options but it only calls or initialize once which is not working in my case. Here I need to call function dynamically and based on that I want to populate dropdown for different fields.
Any help would be appreciated.
Your view is completely messed up as far I see it you are missing
ng-model
for your select input.
Your JSON is improper its missing , before {'id_':'Arizona'}
Try to get response in your controller and push it to array and make use of that array in your View :
$scope.getDropdownData=function(query, colName){
$http.get('/getdropdowndata/', {
params: {
query: query,
colName:colName
}
}).success(function (response) {
var returnArray = [];
alert(JSON.stringify(response));
angular.ForEach(response,function(option){
//parse response and push it to returnArray
returnArray.push(option);
});
return returnArray;
});
}
View :
<div class="form-group">
<select class="form-control" ng-model="selection" ng-options="dropdown._id for dropdown in getDropDownData()">
<option value="">Select</option>
</select>
</div>
Here is the link to Codepen
.
Consider the following solution:
In your controller, set up a variable for the dropdown data:
$scope.dropdownData = {};
Then change your getDropdownData function to:
$scope.getDropdownData=function(query, colName){
$http.get('/getdropdowndata/', {
params: {
query: query,
colName:colName
}
}).success(function (response) {
alert(JSON.stringify(response));
$scope.dropdownData[colName] = response; // This will put data into our html file
});
}
And the HTML for your dropdown case should be:
<div ng-if="mySplit(index,1) == 'select'">
<select class="form-control" ng-init="getDropdownData(index,colName)" ng-options="dropdown._id for dropdown in dropdownData[colName]">
<option value="">Select</option>
</select>
</div>
I used the notorious ngInit to make the call from getting data for the server. Perhaps there's a better way that I didn't consider. But in any case, the idea is to make the call to the server, and save the data in a way that you can fetch it easily from the view.
Edit
I don't know why, but for some reason this solution doesn't work with ng-options. It does, however, work when using it like this:
<select class="form-control" ng-init="getDropdownData(index,colName)">
<option value="">Select</option>
<option ng-repeat="dropdown in dropdownData[colName]" value="dropdown._id">{{dropdown._id}}</option>
</select>
See a simple example here.
Finally I solved it myself. Thanks #Rishab777 and #yarons for guiding me.
Here's the view code:
<div ng-if="mySplit(index, 1) == 'select'">
<select class="form-control">
<option value="">Select</option>
<option ng-model="providerModelData[index]" ng-selected="providerModelData[index]" ng-repeat="dropdown in dropdownData[index]" value="{{dropdown._id}}">{{dropdown._id}}</option>
</select>
</div>
and controller:
$scope.showModal = false;
$scope.toggleModal = function (colId, colName) {
$http.get('/collectiondata/' + colId + '/collectionName/' + colName).success(function (response) {
$scope.colName = colName;
$scope.colId = colId;
for (var key in response) {
if (response.hasOwnProperty(key)) {
if ($scope.mySplit(key, 1) === 'select') {
$scope.getDropdownData(key, colName);
}
}
}
$scope.providerModelData = response;
$scope.showModal = !$scope.showModal;
});
};
$scope.dropdownData = {};
$scope.getDropdownData = function (query, colName) {
$http.get('/getdropdowndata/', {
params: {
query: query,
colName: colName
}
}).success(function (response) {
$scope.dropdownData[query] = response;
});
};
Now the issue is ng-selected="providerModelData[index]" is not working and its showing last item as selected only.

HTML Input field value set by AJAX and catch that event

I have field in my html, and some third-party service will set it's value.
How could I catch that event when the field value is changing?
<input data-val="true" data-val-length="City cannot be longer than 30 characters." data-val-length-max="30" data-val-required="City is required." id="Address_City" maxlength="30" name="Address.City" type="text" value="">
How could I catch the value change of this field,
I've tried .change event also,
$('#Address_City').on('change', function() {
console.log("Changed");
});
Use change event.
$("#myTextBox").on("change", function() {
//alert($(this).val());
});
<select name="user_id" id="user_id" class="form-control" onchange=get_contact(this.value)>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="text" class="form-control" name = "contact_mob" id="contact_mob" placeholder="Contact Number" value="" />
function get_contact(user_id) {
$.ajax({
type: "POST",
url: "search.php",
data: {
"user_id": user_id
},
dataType:'json',
success: function(data) {
// console.log(data.user_mobile);
$("#contact_mob").val(data.user_mobile);
// $("#replaceThis").append(responseData);
}
});
}
Please specify which control your using in your code.
You Can use change or keydown Event.
FOr Client Control
$("#TextBOXID").bind("keydown", function() {
if($("#TextBOXID")[0].value!="" && $("#TextBOXID")[0].value.length>0)
{}
});
For Server Control
$("#<%=TextBOXID.ClientID%>").bind("keydown", function() {
if($("#TextBOXID")[0].value!="" && $("#TextBOXID")[0].value.length>0)
{}
});
We are going to retrieve a value and set that value in an HTML form. First, let's create the form.
Form
<form method="POST" action="">
<select name="user_id" id="user_id" class="form-control">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="text" class="form-control" name = "contact_mob" id="contact_mob" placeholder="Contact Number" value="" />
</form>
Now that we have a form, we will do the technical part using javascript and jQuery
Javascript/jQuery
// Wait for the dom to load before we start doing stuff
$(document).ready(function ($) {
// append value to input on change of the dropdown
$(document).on('change', '#user_id' , function () {
// Get selected value
var user_id = $(this).val();
$.ajax({
type: "POST", // Set ajax call type
url: "search.php", // Set url
data: {"user_id": user_id}, // Set an array of data
dataType:'json', // Set the data type
success: function(data) {
// Log response to console
console.log(data);
// Append data to input
$("#contact_mob").val(data.user_mobile);
}
});
});
});
That's all
I think I found some solution, I'm going to use a timer here, there will be some permanence issues.. but I couldn't find anything be
$('#Address_Address').on('change keyup paste click', function () {
$('.pcaautocomplete .pcaselected').click(function () {
var refreshInterval = setInterval(function () {
if ($('#State').val() != "") {
var statusVal = $('#State').val();
clearInterval(refreshInterval);
}
}, 100);
});
});

How to import dropdown value from table data

I have a java / Spring MVC application that includes forms that interface with tables. On one of the pages, I have designed it so that when a row is clicked on the table, form data is populated using the data that is in that row.
Javascript code:
$('#table tbody').on('click', 'tr', function () {
var idx = table.row(this).index();
var vName = document.getElementById("userName");
vName.value = table.cell(idx, 7).data();
This works well for the text form fields. Where I am running into a problem is in the "userName" field, since that is a list (form:select) field.
I'm not really sure how I would go about the process of having my app be able to locate the list index of a name in the dropdown list based on the text data that it is reading from the table.
Here is the html for the dropdown field:
<spring:bind path="model.userName">
<label for="fullName">Select User:</label>
<form:select cssClass="form-control" path="model.userName" id="userName" name="userName">
<form:option value=""></form:option>
<form:options items="${userList}" itemLabel="fullName" itemValue="ID"/>
</form:select>
</spring:bind>
The dropdown list, ${userList}, is created by building a List in my DAO, along with the following RowMapper method:
private static class UserRowMapper implements RowMapper {
public Object mapRow(ResultSet rs, int i) throws SQLException {
return new Users(rs.getLong("ID"),
rs.getString("LNAME") + ", " + rs.getString("FNAME"));
}
}
When you set a value of a select element, in fact you are setting the option with this value as selected, while here you are using the name so you are dealing with the content of the option and not it's value.
So in your example when you have the selected userName from your table you just need to loop through the select options and set the appropriate option as selected.
This is the code you need:
$('#table tbody').on('click', 'tr', function() {
var idx = table.row(this).index();
var vName = document.getElementById("userName");
for (i in vName.options) {
//I test on the innerText here because FF doesn't support it
var optionText = typeof vName.options[i].innerText !== 'undefined' ? vName.options[i].innerText : vName.options[i].textContent;
if (optionText === table.cell(idx, 7).data()) {
vName.selectedIndex = i;
break;
}
}
});
This is a brief Snippet Example:
$('#name').on('change', function() {
var vName = document.getElementById("userName");
for (i in vName.options) {
var optionText = typeof vName.options[i].innerText !== 'undefined' ? vName.options[i].innerText : vName.options[i].textContent;
if (optionText === $(this).val()) {
vName.selectedIndex = i;
break;
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Enter name:
<input type="text" id="name" />
<select name="userName" id="userName">
<option value="">Muhammad</option>
<option value="">Alain</option>
<option value="">John</option>
<option value="">Ali</option>
<option value="">Maria</option>
<option value="">Lee</option>
<option value="">Alessandro</option>
</select>
Usually the best way to get data from a server to the front end is as a JSON string/object then we can easily manipulate that just like you're doing already.
I think you're pretty much there you're just missing one part.
In this below example i'm listing the same users in a table and menu and on click of the table row the selected user in the drop down is defaulted.
For example with this sample table data.
JS:
var users = [{
ID: 0,
LNAME: "First",
FNAME: "Senior"
}, {
ID: 1,
LNAME: "Second",
FNAME: "Sir"
}, {
ID: 2,
LNAME: "Third",
FNAME: "Chap"
}, {
ID: 3,
LNAME: "Fourth",
FNAME: "Mr"
}];
mag.module('userName', {
view: function(state) {
state.tr = state.option = users.map(function(user) {
return {
_selected: user.ID == state.index ? true : null,
_text: user.FNAME + ' ' + user.LNAME,
_value: user.ID
}
});
state.$tr = {
_onclick: function(e, i) {
state.index = i;
state.span = users[i].FNAME + users[i].LNAME
}
}
}
});
HTML:
<div id="userName">
<table>
<tr></tr>
</table>
<hr/>
<label for="fullName">Select User: <span></span></label>
<select class="form-control" name="userName">
<option></option>
</select>
</div>
Here is the full working example: http://jsbin.com/bokiqebezo/1/edit?html,js,output
Hope this helps!

Geb test: cannot select value of dropdown based on Ajax call

I've ran into a problem in my Geb tests where I'm trying to hit a select dropdown box where the first option is null (user wanted it to display blank as the first option). It is a state field as follows. Note that the original html has an empty array for the from value. The state gets filled based on the selection of "USA" as country based on an Ajax call, I've had to edit it a bit.
How do I set my selector to hit the second or third value? Can I pass values into the selector as an array or something similar? "100225" the value for USA in both the Firebug HTML and my testing db xml, and "102722" is the state value for "Alabama"
***What I'm trying to achieve is this: I want to be able to hit one of the unique state values such as 102722 but Geb only hits the very first value which is always null in the select box, although the '102722' value exists both in the Firebug HTML and in my test xml db so I know its there. As you can see, I've written the Geb selector for State several different ways. This is the error that always comes back:
| java.lang.IllegalArgumentException: couldn't select option with text or value: 102722
NOTE: Also note below that a println of the value in Geb always returns a null value.
Original form item:
<div class="col-sm-3">
<label id="Country-label" class="toplabel" for="Country">Country<span class="required-indicator">*</span></label>
<g:select name="Country" id="Country" from="${dbinfo...Country.list().sort{it.orderNumber}}" class="form-control" required="" optionKey="id" value="${Instance.Country}" aria-labelledby="Country-label"/>
</div>
<div class="col-sm-2">
<label id="State-label" class="toplabel" for=State>State<span id="StateAsterisk" class="required-indicator">*</span></label>
<g:select name="State" id="State" from="${[]}" class="form-control" optionKey="id" value="${...Instance.State}" noSelection="['null':'']" aria-labelledby="State-label"/>
</div>
Rendered HTML from Firebug:
<select id="Country" class="form-control" aria-labelledby="Country-label" required="" name="Country">
<option selected="selected" value="100225">United States</option>
<select aria-labelledby="State-label" class="form-control" id="State" name="State">
<option value="null"></option>
<option value="102722">Alabama</option>
<option value="102723">Alaska</option>
Geb selector excerpt from test:
println $('#Country').value()
waitFor(5){$('#Country').click()}
$('#Country').value(100225) // USA
waitFor(10){$('#Country').find("option").find{ it.value() == 100225 }.click()} // USA
println $('#State').value() // --> RETURNS NULL VALUE
$('#State').find("option").find{ it.value() == 102722}.click() // --> NONE OF THESE WILL HIT
waitFor(5){$('#State').click()} // --> NONE OF THESE WILL HIT
waitFor(5){$('#State').value(102722)} // --> NONE OF THESE WILL HIT
Javascript/Ajax call - that loads states based on country USA:
$(document).ready(function(){
$('#Country').change(function() {
var country = $(this).val();
if(country != null && country != 'null'){
loadStates(country, null, 'submitter', true);
}
});
<g:if test="${...Country}">
$('#Country').val(${...Country});
loadStates(${...Country}, "${...State?:null}", 'submitter', true);
</g:if>
var xhr = null;
function loadStates(country, state, selectId, hideShowAsterisk){
if(xhr != null){
xhr.abort();
xhr = null;
}
xhr = $.ajax({
url: '${request.contextPath}.../aj/loadStatesByCountry',
data: { country: country, selectId:selectId },
async:false,
success: function(data) {
$('#'+selectId+'State').html(data);
$('#'+selectId+'State-label').show();
if(state){
$('#'+selectId+'State').val(state);
}
if(hideShowAsterisk){
if(country == ${grailsApplication....country.usa}){
$('#'+selectId+'StateAsterisk').show();
}else{
$('#'+selectId+'StateAsterisk').hide();
}
}
xhr = null;
},
error:function(jqXHR, textStatus){
if(textStatus != 'abort'){
xhr = null;
alert("There was an error requesting the States for the selected Country");
}
}
});
}
Did you try the following:
waitFor(30){$("form").State = "102722"}

Categories