Select2 load related data into second select2? - javascript

I am working with Cakephp 2.4, Select2 3.4 and Jquery 1.10.
In my app, I have a table with 3 columns - product code, product description and product price.
I have Select2 set up so that the user can select either via product code or via product description. What I want to achieve is:
if the users selects via product code, set the product description and price and if he selects via description, set product code and price.
My data gets returned as follows:
[{"id":1,"text":"10001","description":"Test Product Name","unitPrice":"1.25"}, {"id":2,"text":"10002","description":"product 2","unitPrice":"5.00"}, {"id":3,"text":"10003","description":"Product 3","unitPrice":"2.74"}]
I am able to set the value of the second select2 box using plain jQuery:
$(".productCode").on('change', function (product){
$(".description").select2("data", {id: '1', text: 'Test'});
});
What do I have to use to set the .description select2 value to the "description" value returned?

You forget initialize the select elements. Do it like this:
<!DOCTYPE html>
<html>
<head>
<title>jquery select2 test</title>
<script type="text/javascript" src="jquery-1.9.1.js"></script>
<link href="select2/select2.css" rel="stylesheet"/>
<script src="select2/select2.js"></script>
</head>
<body>
<input type="hidden" class="productCode" />
<select class="description" >
</select>
<script type="text/javascript">
$(document).ready(function() {
var $productCode = $(".productCode"),
$description = $(".description"),
product = [{"id":1,"text":"10001","description":"Test Product Name","unitPrice":"1.25"},{"id":2,"text":"10002","description":"product 2","unitPrice":"5.00"},{"id":3,"text":"10003","description":"Product 3","unitPrice":"2.74"}];
//should initilize two select first
$productCode.select2({
'placeholder' : 'input to search',
"width" : '200px',
"query": function(query){
var data = {results: product};
query.callback(data);
}
});
$description.select2({
'width' : '200px'
});
$productCode.on('change', function (product){
$description.select2("data", {id: '1', text: 'Test'});
});
});
</script>
</body>
</html>

If you use hidden inputs to back your Select2 controls, like this:
<input type="hidden" class="product" id="productCode" data-text="text" data-placeholder="code" />
<input type="hidden" class="product" id="description" data-text="description" data-placeholder="description" />
<input type="hidden" class="product" id="unitPrice" data-text="unitPrice" data-placeholder="unit price" />
And you have data like this:
var PRODUCTS = [
{ id: 1, text: '10001', description: 'Product 1', unitPrice: '1.25' },
{ id: 2, text: '10002', description: 'Product 2', unitPrice: '5.00' },
{ id: 3, text: '10003', description: 'Product 3', unitPrice: '2.74' }
];
You can populate your Select2 controls using the "data" option, like this:
$('.product').each(function() {
var $this = $(this);
$this.select2({
allowClear: true,
data: { results: PRODUCTS, text: $this.attr('data-text') }
});
});
And you can use the Select2 "val" function to get and set the values, like this:
$('.product').change(function() {
var selecteId = $(this).select2('val');
$('.product').select2('val', selecteId);
});
jsfiddle demo

Related

Jquery Autocomplete display names and send Id

How can I change my jQuery autocomplete to use an Id instead of my values?
I would like to display the list of names but send a search using the Id value. Now it is working properly with the names but I think it will be more effective if it tries to find a unique value as an ID.
$.getJSON('Dashboard/CompaniesWithId', function (data) {
$.each(data, function (i, item) {
sellers[i] = item.Name;
sellersID[i] = item.Id;
});
}).error(function () {
console.log("error loading seller to the autocomplete");
});
$("#searchSeller").autocomplete({
messages: {
noResults: 'No sellers with this name',
},
minLength: 2,
delay: 500,
source: sellers,
});
you can add a hidden field and use the on select event to set the value of the hidden field to the selected id
http://api.jqueryui.com/autocomplete/#event-select
you can also use selection data with format [{value: 'value', label: 'label'}] but using this way, the field will show the id instead of the label
var availableTags = [
{id: 1, label: "ActionScript"},
{id: 2, label: "Ruby"},
{id: 3, label: "Scala"},
{id: 4, label: "Scheme"}
];
availableTags2 = [
{value: 1, label: "ActionScript"},
{value: 2, label: "Ruby"},
{value: 3, label: "Scala"},
{value: 4, label: "Scheme"}
];
$( "#a" ).autocomplete({
source: availableTags,
select: function( event, ui ) {
$('#tosend').val(ui.item.id);
}
});
$( "#b" ).autocomplete({
source: availableTags2
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script
src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"
integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU="
crossorigin="anonymous"></script>
id to send<br>
<input type="text" name="tosend" id="tosend"><br><br>
type below<br>
<input id="a"><br>
<br>
<br>
using value instead of id<br>
<input id="b">
I don't know anything about your back-end. But assuming it is accepting IDs for your search parameters, will changing the source value to sellersID resolve your issue? You also have that extra comma after sources. It will cause you problems.
$("#searchSeller").autocomplete({
messages: {
noResults: 'No sellers with this ID.',
},
minLength: 2,
delay: 500,
source: sellersID
});

AngularJS - ng-select not working as expected

I have a filter drop down for some tabular data that reads data from a local storage item, the select tag is shown below, and below that is the code to add items to the select tag and the model for the filter.
The issue is that whilst the data filtered is correct when you refresh the page, the selected item only shows the correct value if the local storage value is true.
No matter what value the local storage item is selected="selected" is always added to the "Excluded from Search" option.
Can't for the life of me work out why, any help advice appreciated.
<select class="form-control form-control-sm" ng-model="filterSearch" ng-change="setFilterS()" id="theFilterS" >
<option ng-selected="{{option.value == filterSearch}}" ng-repeat="option in filterSearchOptions" value="{{option.value}}" >{{option.DisplayName}}</option>
</select>
$scope.filterSearch = localStorage.getItem("FilterSearch");
$scope.filterSearchOptions = [{
value: '',
DisplayName: 'All',
}, {
value: 'false',
DisplayName: 'Included in Search',
}, {
value: 'true',
DisplayName: 'Excluded from Search',
}];
You should try with the ng-options directive which IMO gives a simpler approach then ng-repeat
angular.module('app',[]).controller('testCtrl',function($scope){
$scope.filterSearch = 'true';
$scope.filterSearchOptions = [{
value: '',
DisplayName: 'All',
}, {
value: 'false',
DisplayName: 'Included in Search',
}, {
value: 'true',
DisplayName: 'Excluded from Search',
}];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="testCtrl">
<select
class="form-control form-control-sm"
ng-model="filterSearch"
ng-change="setFilterS()"
id="theFilterS"
ng-options="option.value as option.DisplayName for option in filterSearchOptions">
</select>
{{filterSearch}}
</div>

Adding form data inputs to jqGrid

I am trying to add the data obtained from the form and display it to JQGrid.
I have the following elements in my Form.
Textbox for username
Datepicker for date of birth
Combobox for selecting the country.
Two buttons Add and Clear button.
Whenever i click the Add button ,it has to add a row to the JQGrid.Whenver i click the clear button it has to reset the entire table.
Currently,I am trying to display the data from the form to the row.
Below is my effort till now.
<script>
$(function() {
$( "#pwd" ).datepicker();
var source = [{
text: "Australia",
value: 0
},
{
text: "India",
value: 1
},
{
text: "United States",
value: 2
},
{
text: "United Kingdom",
value: 3
}];
$("#jqxComboBox").jqxComboBox({
source: source,
theme: 'energyblue',
width: '240px',
height: '30px',
displayMember: 'text',
selectedIndex: 0,
valueMember: 'value'
});
$('#add').click(function(){
name=$('#name').val();
date=$('#pwd').val();
country=$('#jqxComboBox').val();
alert(name);
$('#jqGrid').jqGrid('addRowData',name,date,country);
}); });
</script>
<style type="text/css">
</head>
<body>
<div class="container">
<h2>Horizontal form</h2>
<form class="form-horizontal" role="form" id="add_form">
<input type="text" id="name"></input>
<input type="text" id="pwd"></input>
<div id="jqxComboBox"></div>
<input type="submit" value="add">
<input type="submit" value="reset">
</div>
</form><table id="jqGrid">
</table>
</body>
</html>
May be you should init jqGird first and run code like below :
$(function() {
$("#jqGrid").jqGrid({
'datatype' : 'local',
// if there is no data at the beginning, just define an empty array [],
// or you can set init data with data option below
'data' : [ {
'name' : 'testUser',
'date' : '15/4/2016',
'country' : 'somewhere'
} ],
'colNames' : [ 'Name', 'Date', 'Country' ],
'colModel' : [ {'name' : 'name'}, {'name' : 'date'}, {'name' : 'country'} ],
'loadComplete' : function() { // You can add data manually using code below.
// You can define a datarow variable as single object and also an
// array of objects.
// array data example: var datarow = [{"name":"addedName",
// "date":"16/4/2016", "country":"any"},
// {"name":"addedName2", "date":"16/4/2016", "country":"any2"}];
var datarow = {
"name" : "addedName",
"date" : "16/4/2016",
"country" : "any"
};
// second parameter of method below is rowid just for generate id
// attribute of tr element.
// if keep rowid variable as undefined, jqGrid will generate a
// random id instead.
var rowid;
// last paremeter tell jqGrid add new data after last row.
$("#jqGrid").jqGrid("addRowData", rowid, datarow, "last");
}
});
});
<script src="http://www.trirand.com/blog/jqgrid/js/jquery.js"></script>
<script src="http://www.trirand.com/blog/jqgrid/js/jquery.jqGrid.js"></script>
<table id="jqGrid"></table>

Echo value from database to selectize.js with php

I'm trying to echo out value from database with php for selectize.js.
Html code
<select id="type" placeholder="Type" name="type" required>
<!-- This option help to selected value from DB -->
<!--<option value="<?php echo $dataFromDB['type'] ?>" selected></option>-->
</select>
<button id="someType">Add Option</button>
Js code (example from selectizejs (with change))
var $select = $('#type').selectize({
maxItems: 1,
valueField: 'id',
labelField: 'days',
searchField: 'days',
options: [{
id: '1',
days: '5 days'
}, {
id: '2',
days: '2 days'
}, {
id: '3',
days: '1 days'
}],
create: true
});
var control = $select[0].selectize;
$('#someType').on('click', function () {
control.addOption({
id: '4',
days: 'New Days'
});
});
How to automatically add option from database value and set as selected option?
jsfiddle link
Note: I could echo out the value to option if there's a match between database value and options value.
Thanks in advanced.
Like this? http://jsfiddle.net/2zyp8jxn/1/
control.setValue("4");
Create a variable with php:
$php_test = "control.addOption({
id: '".$dataFromDB['type']."',
hari: '".$dataFromDB['type']."'
});
control.setValue('".$dataFromDB['type']."');
";
and add this jquery code
var control = $select[0].selectize;
$(function() {
<?php echo 'var someOptions ='. $php_test ?>
});
I dont know if create a variable someOptions is necessary or not but it works for me.
Thanks

Kendo UI Web Grid - Popup_Editor Template - Dropdown

I am using Kendo UI Web Grid, not one of the Server Wrappers. I am only displaying a few fields in the grid. The rest of the fields are displayed in the create or edit popup. For this popup I am using a template:
<script id="popup_editor" type="text/x-kendo-template">
<div class="k-edit-label">
<label for="Title">Title</label>
</div>
<div class="k-edit-field">
<input type="text" class="k-input k-textbox" name="Title" data-bind="value:Title" required>
</div>
</script>
and then I am calling it from the grid:
editable: {
mode: "popup",
template: $("#popup_editor").html(),
confirmation: "Are you sure?"
}
This works great for input boxes. However I have a foreign key column in my table. I want to display all the options from the foreign key table in a dropdown and select the correct one based on the value in my table. I have searched around quite a bit but haven't been able to find an answer to this.
Any help would be greatly appreciated.
I solved this myself. If anyone else is looking for this here is the solution.
In the Javascript section create a new data source it can be static:
var facultyRankDS = new kendo.data.DataSource({
data: [
{ Id: null, Name: "<Please Select>"},
{ Id: 1, Name: "Instructor" },
{ Id: 2, Name: "Assistant Professor" },
{ Id: 3, Name: "Associate Professor" },
{ Id: 4, Name: "Professor" }
]
});
or it can be dynamic:
var facultyRankDS = new kendo.data.DataSource({
transport: {
read: function(options) {
$.ajax({
url: "api/Member.mvc/GetMemberRanks",
dataType: 'json',
success: function(result) {
options.success(result);
}
});
}
}
});
Then in the popup_editor section add your dropdown:
<div class="k-edit-label">
<label for="FacultyRankId">Rank</label>
</div>
<!-- dropdownlist editor for field: "FacultyRankId" -->
<div class="k-edit-field">
<input name="FacultyRankId"
data-bind="value:FacultyRankId"
data-value-field="Id"
data-text-field="Name"
data-source="facultyRankDS"
data-role="dropdownlist"
data-value-primitive="true" />
</div>

Categories

Resources