populate combobox with java script - javascript

i am write some code for cascading drop down with dojo ajax first drop down is static and second one is fetch the data from servlet .. i am using the dijit.form.ComboBox for make dropdown. Dojo provide the Store property in which he store the data and then put it into combobox. in servlet i through the array list to ajax function .. in ajax function i separate the array with comma and strore in variable and then store in the dojo's store property But i am not able to populate the whole string .. it populate only the last value of the string i am using following code
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" href="dojo/dijit/themes/claro/document.css">
<link rel="stylesheet" href="dojo/dijit/themes/claro/claro.css" />
<script src='dojo/dojo/dojo.js' data-dojo-config=' parseOnLoad: true'></script>
<script>
require(["dojo/parser", "dijit/form/ComboBox","dijit/form/TextBox"]);
function abc(){
var j = document.getElementById('state').value
dojo.xhrPost({
// The URL to request
url: "populate", //servlet name
timeout : 3000 ,
content: {
username: dojo.byId("state").value
},
load: function(result) { // the value in result is like=[Abas Store, Accounts ]
require([
"dojo/ready", "dojo/store/Memory", "dijit/form/ComboBox"
], function(ready, Memory, ComboBox){
var ss=result.split(",");
var i;
for (i=1;i< ss.length ;i++){
var stateStore = new Memory({
data: [ {name:ss[i], id: ss[i]} ]
});
}
ready(function(){
var comboBox = new ComboBox({
id: "stateSelect",
name:"select",
value: "Select",
store: stateStore,
searchAttr: "name"
}, "stateSelect");
});
});
}
});
}
</script>
</head>
<body class="claro">
<select data-dojo-type="dijit.form.ComboBox" id="state" name="state" onchange="abc();">
<option selected >Andaman Nicobar</option>
<option>Andhra Pradesh</option>
<option>Tripura</option>
<option>Uttar Pradesh</option>
<option>Uttaranchal</option>
<option>West Bengal</option>
</select>
<input id="stateSelect" >
</select>
</body>
</html>
please give me solution .. to populate all the value in combobox which is i get from array list

You are building the store in the for loop. Instead, you should build the data array that gets passed into the MemoryStore constructor.
require(["dojo/store/Memory", "dijit/form/ComboBox", "dojo/ready"],
function(Memory, ComboBox, ready){
ready(function) {
dojo.connect(dijit.byId('state'), 'onChange', function() {
var stateSelect = dijit.byId('stateSelect');
if (!stateSelect) {
stateSelect = new ComboBox({
id: "stateSelect",
name: "select",
value: "Select...",
searchAttr: "name"
}, "stateSelect");
}
var ss = 'Abas Store, Accounts';
ss = ss.split(',');
var data = [];
dojo.forEach(ss, function(item, idx) {
data.push({
id: idx,
name: item
});
stateSelect.set('store', new Memory({data: data}));
}); // dojo.connect
}); // ready
}); // require
​
The working example is at http://jsfiddle.net/cswing/DLNNc/

Related

selectize.addItem(value) adds the value of the item and not the items label

I have found plenty of other questions, but all of their answers have been unable to resolve my issue.
I am trying to set the value of a selectize.js input to a specified value.
Here is what I am doing:
$select = $picker.selectize({
valueField: 'id',
labelField: 'displayName',
searchField: 'displayName',
options: [],
create: false,
// ... Omitted
});
if (initialValue.length > 0) {
// Do a search for the user.
jQuery.getJSON("/_api/GetUserById?Id=" + initialValue, function(data) {
var results = data.value;
if (results.length == 1) {
$select[0].selectize.addOption(results[0]);
$select[0].selectize.addItem(results[0].id);
}
}, function(err) {
initialSearchForUserFailed(err);
});
This does successfully change the value of the input, however, the addItem method adds the users Id to the selectize input instead of their display name.
Could be that your searchField value needs to be formatted as an array but I am unable to reproduce the display issue you are seeing. Also, could be an issue with how the data is being returned from your remote source. See the working example below that may help you troubleshoot:
// placeholder for data retrieved from remote source
const options = [
{ value: 1, text: 'Annie' },
{ value: 2, text: 'Bart' },
{ value: 3, text: 'Carol' }
];
// init selectize input
const field = $('#select1').selectize({
options: [],
placeholder: 'Select...',
valueField: 'value',
labelField: 'text',
searchField: ['text'],
create: false
});
// change the index to simulate retrieving a different option
const option = options[0];
// add first option to selectize input and select it
field[0].selectize.addOption(option);
field[0].selectize.addItem(option.value);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Selectize</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/css/selectize.default.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/js/standalone/selectize.js"></script>
</head>
<body>
<form action="" method="POST">
<input id="select1" name="select1" type="text" />
<button type="submit">Submit</button>
</form>
</body>
</html>

Uncaught ReferenceError: characters is not defined

I am creating a simple rest api in javascript, I want upon initialization, the widget must display a list of all characters.
here is folder structure :
├───book
└───book.js
├───store
│ └───store.js
here is my store.js
window.Store = {
create: function() {
var self = {};
var props = {
name: 'string',
species: 'string',
picture: 'string',
description: 'string'
};
var listProps = ['name', 'species'];
var detailProps = ['name', 'species', 'picture', 'description'];
var characters = [
{
id: makeID(),
name: 'Ndiefi',
species: 'Wookie',
picture: 'store/img/ndiefi.png',
description: 'A legendary Wookiee warrior and Han Solo’s co-pilot aboard the Millennium Falcon, Chewbacca was part of a core group of Rebels who restored freedom to the galaxy. Known for his short temper and accuracy with a bowcaster, Chewie also has a big heart -- and is unwavering in his loyalty to his friends. He has stuck with Han through years of turmoil that have changed both the galaxy and their lives.',
_delay: 500
},
];
}
}
here is index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Character Book</title>
<!-- 3rd party vendor libraries -->
<link rel="stylesheet" href="vendor/font-awesome-4.6.3/css/font-awesome.min.css">
<script src="vendor/jquery-3.1.0.min.js"></script>
<script src="vendor/underscore-1.8.3.min.js"></script>
<!-- 1st party internal libraries -->
<script src="store/store.js"></script>
<script src="tests/start-test.js"></script>
<script src="tests/test-book.js"></script>
<!-- The source of the 'Book' widget -->
<link href="book/book.css" rel="stylesheet">
<script src="book/book.js"></script>
<script>
$(function() {
var frame = $('#test-frame');
var run = $('#test-run');
var results = $('#test-results');
var store = Store.create();
run.click(function() {
run.prop('disabled', true).text('Running Tests');
results.removeClass('test-pass test-fail').text('');
testBook(frame).then(
function success() {
run.prop('disabled', false).text('Run Tests');
results.addClass('test-pass').text('All tests passed');
},
function failure(err) {
run.prop('disabled', false).text('Run Tests');
results.addClass('test-fail').text('Test failed, see console');
}
);
});
Book.init(frame, store);
});
</script>
</head>
<body>
<button id="test-run">Run Tests</button>
<span id="test-results"></span>
<div id="test-frame">
</div>
</body>
</html>
here is what I have tried :
books.js
var data = JSON.parse(characters);
data.forEach(characters => {
console.log(characters.name)
});
so when I run the app in my browser I see the following error :
Uncaught ReferenceError: characters is not defined
what is wrong with my code ? any suggestion or help will be helpfull thanks

EasyAutocomplete: change the returned value

I would like to use the EasyAutcomplete plugin to create an autocomplete list for the user and then to send the value associated to the matching string by GET method ... and not the matching string.
Using this code
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<link rel="stylesheet" href="./EasyAutocomplete/easy-autocomplete.min.css">
<link rel="stylesheet" href="./EasyAutocomplete/easy-autocomplete.themes.min.css">
<script src="./EasyAutocomplete/jquery.easy-autocomplete.min.js"></script>
</head>
<body>
<form method="get" action="test.php">
<input id="provider-file" name="get_value"/>
<script>
$(document).ready(function() {
var options = {
url: "./EasyAutocomplete/file.json",
getValue: "name",
list: {
match: {
enabled: true
}
}
};
$("#provider-file").easyAutocomplete(options);
});
</script>
<div>
<input type="submit" value="send"/>
</div>
</form>
</body>
</html>
and the JSON file having the following format
[
{"name":"Bob","id":"1"},
{"name":"David","id":"2"},
{"name":"Steve","id":"3"},
...
]
the user get redirected to 'test.php?get_value=Bob' after submitting Bob, while I would like him to be redirected to 'test.php?get_value=1' (i.e. to send "id" and not "name").
Could anyone help me? I couldn't find any answer in the EasyAutocomplete doc.
You can use the onSelectItemEvent event along with the getSelectedItemData method to populate a hidden input field named get_value with the ID you want to submit and remove the name from the lookup input field so that it won't get submitted.
HTML:
<input id="provider-file">
<input type="hidden" id="id-value" name="get_value">
Setup:
var options = {
url: "./EasyAutocomplete/file.json",
getValue: "name",
list: {
onSelectItemEvent: function() {
var value = $("#provider-file").getSelectedItemData().id; //get the id associated with the selected value
$("#id-value").val(value).trigger("change"); //copy it to the hidden field
}
}
};
Demo (click submit to see that get_value=id is submitted):
$(document).ready(function() {
var options = {
data: [{
"name": "Bob",
"id": "1"
}, {
"name": "David",
"id": "2"
}, {
"name": "Steve",
"id": "3"
}],
getValue: "name",
list: {
onSelectItemEvent: function() {
var value = $("#provider-file").getSelectedItemData().id; //get the id associated with the selected value
$("#id-value").val(value).trigger("change"); //copy it to the hidden field
}
}
};
$("#provider-file").easyAutocomplete(options);
// used to validate what gets submitted
$("#form-test").on('submit', function(e) {
e.preventDefault();
console.log($(this).serialize());
});
});
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/easy-autocomplete/1.3.5/easy-autocomplete.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/easy-autocomplete/1.3.5/easy-autocomplete.themes.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/easy-autocomplete/1.3.5/jquery.easy-autocomplete.min.js"></script>
<form method="get" id="form-test">
<input id="provider-file">
<input type="hidden" id="id-value" name="get_value">
<input type="submit">
</form>

Backbone script to read from external JSON

I want to display data from JSON using a backbone script.
This is the html Page:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="backbone.js"></script>
<script src="jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var Profile = Backbone.Model.extend();
var ProfileList = Backbone.Collection.extend({
model: Profile,
url: 'document.json'
});
var ProfileView = Backbone.View.extend({
el: "#profiles",
template: _.template($('#profileTemplate').html()),
initialize: function(){
this.listenTo(this.collection,"add", this.renderItem);
},
render: function () {
this.collection.each(function(model){
var profileTemplate = this.template(model.toJSON());
this.$el.append(profileTemplate);
}, this);
return this;
},
renderItem: function(profile) {
var profileTemplate = this.template(profile.toJSON());
this.$el.append(profileTemplate);
}
});
var profileList = new ProfileList();
var profilesView = new ProfileView({ collection: profileList });
profilesView.render();
});
</script>
</head>
<body>
<div id="profiles"></div>
<script id="profileTemplate" type="text/template">
<div class="profile">
<div class="info">
<div class="name">
<%= name %>
</div>
<div class="title">
<%= title %>
</div>
<div class="background">
<%= background %>
</div>
</div>
</div>
<br />
</script>
</body>
</html>
This is my json data:
document.json
[
{
"id": "p1",
"name" : "AAAA",
"title" : "BBBB",
"background" : "CCCC"
},
{
"id": "p2",
"name" : "DDDD",
"title" : "EEEE",
"background" : "FFFF"
},
{
"id": "p3",
"name" : "GGGG",
"title" : "HHHH",
"background" : "IIII"
}
]
There's nothing being displayed on the page.
Am I missing something?
I have been trying to get the JSON data printed on the div element in specified HTML. But Nothing being displayed. I tried debugging the code, I could insert alert statement before Backbone.Model.extend inside document.ready in jquery. But when I put alert statement inside it, it isnt coming up. So, the code inside Backbone.Model.extend must be gone wrong somewhere.
Somebody help me?
You need to check the order of loading your scripts, jquery should come first, underscore secondly (since you are using undescore.js templating) then backbone:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js" type="text/javascript"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js" type="text/javascript"></script>
If that doesn't solve your problem then you could either try sending in a static reference to your initial set of data, then call fetch() as needed to grab more, or you can call fetch explicitly as follows:
var profileList = new ProfileList();
var profilesView = new ProfileView({collection: profileList});
profileList.fetch();
profileList.bind('reset', function () {
profilesView.render();
});
Working Demo
You should load scripts in order, jquery, underscore and then Backbone

How should I do a redirect to a path with an object in ember?

I'm trying to put together a data-driven menu system in Ember.js. Here's the javascript, js/nodal.js:
window.Form = Ember.Application.create();
var menuOptions = [
{id: "root",
options: [ "a", "b" ]},
{id: "a",
name: "Option A",
options: [ "c", "d" ]},
{id: "b",
name: "Option B",
options: [ "e", "f" ]},
{id: "c",
name: "Option C"},
{id: "d",
name: "Option D"},
{id: "e",
name: "Option E"},
{id: "f",
name: "Option F"}
]
Form.MenuOption = Ember.Object.extend({});
var builtOptions = menuOptions.map( function(attrs) {
return Form.MenuOption.create( attrs );
});
Form.options = {};
for( i = 0; i < builtOptions.length; i++ ) {
var opt = builtOptions[i];
Form.options[opt.id] = opt;
}
Form.MenuRoute = Ember.Route.extend({
model: function(params){
console.log( params );
if( !params || !params.index_id || params.index_id == "undefined") {
params.index_id = "root";
}
var keys = Form.options[params.index_id].options;
var options = new Array();
keys.map(function(k){ options.push( Form.options[k] ); });
return options;
}
});
Form.IndexRoute = Ember.Route.extend({
redirect: function(){
/* This here is the problem line... */
this.transitionTo( "menu", Form.options.root );
}
});
Form.Router.map(function(){
this.resource( "menu", { path: "/menu/:index_id" } );
});
And here's the HTML, such as it is:
<title>Hello</title>
<meta name="description" content="My First Ember.js App">
<meta name="author" content="Your Name Here">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script data-template-name="application" type="text/x-handlebars">
<h1>Title Goes Here</h1>
{{outlet}}
</script>
<script data-template-name="menu" type="text/x-handlebars">
<ul>
{{#each controller}}
<li>{{#linkTo menu this}}{{name}}{{/linkTo}}</li>
{{/each}}
</ul>
</script>
<script src="js/libs/jquery-1.9.1.js"></script>
<script src="js/libs/handlebars.js"></script>
<script src="js/libs/ember-1.0.0-rc.1.js"></script>
<script src="js/nodal.js"></script>
</body>
</html>
What I want is for the user to be redirected to /menu/root as soon as they open the page. So far I haven't been able to find the right incantation to make this work. When I load the above, I get this exception:
Error: assertion failed: an Ember.CollectionView's content must implement Ember.Array. You passed <(generated menu controller):ember172>
If I load index.html#/menu/root directly, it works - it's only the redirect that's not working. Replacing the this.transitionTo line in the IndexRoute definition with this:
this.transitionTo( "menu", [Form.options.root] );
does redirect, but it redirects to /menu/undefined, not /menu/root. That's ugly, and obviously broken.
What have I missed?
EDIT
As suggested, I tried adding an ArrayController:
Form.MenuController = Ember.ArrayController.extend({});
This gives me a new error:
arrangedContent.addArrayObserver is not a function
The problem is that your URL assumes you are working with one model, but in transitioTo and your model hook your are passing/returning an array. Your MenuRoute is always about one MenuOption, right?
Therefore i would suggest:
Form.MenuRoute = Ember.Route.extend({
model: function(params){
console.log( params );
if( !params || !params.index_id || params.index_id == "undefined") {
params.index_id = "root";
}
var menuOption = Form.options[params.index_id];
return menuOption;
}
});
Your corresponding template should look like this in this case:
<script data-template-name="menu" type="text/x-handlebars">
<ul>
{{#each option in controller.content.options}}
<li>{{#linkTo menu option}}{{option.name}}{{/linkTo}}</li>
{{/each}}
</ul>
</script>
The error message basically says that view expects either array or array controller as the view's content but receives a generated controller instead(controller is generated when no controller is defined for route). The route's model method returns array thus it must be wrapped with appropriate controller - the ArrayController. You should define a custom controller for the menu route which extends ArrayController - this will eliminate the error message.
Edit
And about routing: I think you should have defined each of our menu options as a route nested in the menu resource, like this:
Form.Router.map(function(){
this.resource( "menu", { path: "/menu/:index_id" }, function () {
this.route('root');
this.route('a');
this.route('b');
...
});
});
This will also require defining the Route class for each route..

Categories

Resources