Create Dynamic checkboxes by iterating JSONArray in DOJO - javascript

I am new to DOJO and I am using DOJO 1.5.0 version.
I want to create dynamic checkboxes by iterating JSONArray in DOJO. This dynamic creation will be done on a particular event like when we selecting some combo-box value.
For example consider below JSONArray:
var tempJSONArray = [{role_id = '1', role_name = 'role1'},{role_id =
'2', role_name = 'role2'},{role_id = '3', role_name = 'role3'}]
I want display checkboxes corresponding to Role Name. Lable for checkbox will be role_name and value will be role_id from JSON object.
Also I want to add 'onChange' event to check-boxes, as on this event I want to do a Ajax call to server with role_ids.
Thank you for reading and also please let me know if further clarification is needed.

You can use the dojo.create() method for creating DOM nodes and the dojo.place() method for placing them inside another element, for example:
var checkbox = dojo.create("input", {
type: "checkbox",
value: "1"
});
You will probably have to wrap it inside a <label> to show the text (which you can also create with dojo.create()). Then you can place them inside a list, for example:
dojo.place(label, "checkboxes");
This will wrap the checkbox (or label) inside an element with ID checkboxes. So, if you create your checkboxes now inside a loop, it should work.

After doing some internet surfing and playing around code I able write below code, which working fine for my scenario. So thought it will be helpful for others.
for ( var i = 0; i < roleJSON.length; i++) {
var role = roleJSON[i];
var tr = dojo.create("tr",{id:"rolebasecheckbox"+i,'class':'rolebasecheckbox'});
alert("tr=" + tr);
var td= dojo.create("td",{innerHTML:'<input id="roleBaseCb_'+i+'" value="'+role.role_id+'" dojoType="dijit.form.CheckBox" onclick="alert('onclick event')" type="checkbox" /> <label for="roleBaseCb_'+i+'">'+role.role_name+'</label>',align:'center'},tr);
alert("td=" + td);
if(i==0){
alert("i is 0");
dojo.place(tr, "roleBaseComboTR", "after");
}else{
dojo.place(tr, "rolebasecheckbox"+(i-1), "after");
}
}

Related

How to use jQuery to select deeply nested elements created dynamically with javascript

So I have an object in my code and I use js to add the properties of the object to an array named rec based on users interaction. then I use a function named unRec to get unique elements of the array. Then I add the values returned by unRec to the HTML. Then I use jquery to wrap each of the values in anchor tags. So the code is basically like this
obj= {
0: "<span>module1</span>",
1: "<span>module1</span>",
2:"<span>module1</span>",
3:"<span>module2</span>",
4:"<span>module2</span>",
5:"<span>module3</span>",
6:"<span>module3</span>",
7:"<span>module3</span>",
8:"<span>module3</span>",
9:"<span>module4</span>"
}
function unRec(arr){
preRec = [];
for (j of arr){
if (preRec.indexOf(j)=== -1) {
preRec.push(j);
}
}
return (preRec);
}
Recom.innerHTML = unRec(rec);
$('#congrat #recom span').wrap('')
Now am unable to select the created anchors. Hence this function doesn't work
$('#congrat #recom .disp').click(function(e) {
var url = $(this).attr('href') + '#' + $(this).text();
$('#module').html('loading...).load(url); e.preventDefault();
});
I have tried to use find to select the anchors but it still doesn't work. This is the test
var t = $('#congrat #recom').find ('a').length;
console.log(t);
The HTML is basically like this:
<div id="congrat">
<span id="recom"></span>
</div>
<div id="module">click on one of the modules above<div>
Please provide a solution to select the created anchors. Thanks in advance

Chosen multiple select becomes huge when many/all options are selected

When using Chosen.js on a multiple select field, if there are over 500 options that the user has selected, the list just becomes ridiculously long.
Is there any way I could limit the number of show elements? For example when chosing over 3 options, the user will have (4) options are selected..., instead of them being listed.
I wonder why there's no such option in their documentation.
Thanks in advance.
You can use something like this:
$('.element').chosen().change(function() {
var totalSelected = $(this).find('option:selected').size();
var placeholder = $(this).find('option:first-child').text();
if(totalSelected > 3) {
$(this).next().find('.chosen-choices').find('li.search-choice').hide(),
$(this).next().find('.chosen-choices').find('.literal-multiple').show();
$(this).next().find('.chosen-choices').find('span.literal-multiple').text(placeholder + " ("+totalSelected+")");
}
});
The class literal-multiple is a custom element to show the totalSelected elements. You need to add it in the prototype of the chosen plugin:
file chosen.jquery.js
Chosen.prototype.set_up_html = function() {
//stuff
if(this.is_multiple) {
var selVal = this.default_text;
this.container.html('<ul class="chosen-choices"><span class="literal-multiple"></span></ul>');
}
};
SOrry I am unable to comment since I don't have enough reputation.
But to add to the previous answer, instead of adding a separate container,
why don't we just append the n users selected as a <li> item.
Something like this -
$('.element').chosen().change(function() {
var totalSelected = $(this).find('option:selected').size();
var placeholder = $(this).find('option:first-child').text();
if(totalSelected > 3) {
$(this).next().find('.chosen-choices').find('li.search-choice').hide(),
$(this).next().find('.chosen-choices')append('<li class="search-choice" <span>'+totalSelected+' users selected. </li>');
}
});
This seems to work for me.

SAPUI5 dynamic binding of table cells

I have the following Problem:
I want to dynamically create table rows and cells with different settings.
The Solution mentioned here: Dynamic binding of table column and rows
was a good starting point for my problem, but I still could not get it to work.
The table should display each object of the model in a new row with the binding for the given attributes of that object.
The checked attribute should be displayed in/as a checkbox that is either checked or unchecked depending on the value (true or false) of checked.
Now, this works perfectly fine if I define the bindings and columns as they are in the SAPUI5 Table Example
The Problem:
Depending on value (true or false) of the objects existsLocal attribute I want the checkbox of that row to be either enabled or disabled. Further that row should get a new class - called existsLocalClass wich sets its background to grey if existsLocal is true.
I was thinking that this can be solved with a factory function that creates my rows and its cells. Unfortunately my factory does not work as intended.
Here is my code:
Model definition:
var model = [
{name: "name1", description: "description1", checked: true, existsLocal: true},
{name: "name2", description: "description2", checked: false, existsLocal: false}
]
var oModel = new sap.ui.model.json.JSONModel();
oModel.setData({modelData: model});
Table plus factory function:
var oTable = new sap.ui.table.Table({
visibleRowCount: 7,
firstVisibleRow: 3,
selectionMode: sap.ui.table.SelectionMode.None
});
var tableRowFactory = function (sId, oContext) {
console.log("row factory");
var exists = oContext.getProperty("existsLocal");
if(exists){
return new sap.ui.table.Row(sId)
.addCell(new sap.ui.commons.TextView()
.bindProperty("text", oContext.sPath + "/name"))
.addCell(new sap.ui.commons.TextView()
.bindProperty("text", oContext.sPath+ "/description"))
.addCell(new sap.ui.commons.CheckBox()
.bindProperty("checked", oContext.sPath+ "/checked").setEnabled(false))
.addStyleClass("existsLocal");
}else{
return new sap.ui.table.Row(sId)
.addCell(new sap.ui.commons.TextView()
.bindProperty("text", oContext.sPath + "/name"))
.addCell(new sap.ui.commons.TextView()
.bindProperty("text", oContext.sPath+ "/description"))
.addCell(new sap.ui.commons.CheckBox()
.bindProperty("checked", oContext.sPath+ "/checked"))
}
};
oTable.setModel(oModel);
oTable.bindRows("/modelData",tableRowFactory); // does not work
oTable.bindAggregation("rows", "/modelData", tableRowFactory); //doesn't work either
The browser does not show any errors and the table stays empty. I think the function does not even get called but I could not manage to fix it.
Maybe my entire approach is wrong - I don't really understand sapui5's binding and context thingy.
I hope that you can help me with this.
Edit:
I found a kinda hacky solution for this:
var model = oTable.getModel();
var rows = oTable.getRows();
var indicesOfRows = [];
$.each(rows, function (index, row){
indicesOfRows.push(oTable.indexOfRow(row));
});
$.each(rows, function(index, row){
var rowIndex = indicesOfRows[index];
var exists = model.getProperty("existsLocal", oTable.getContextByIndex(rowIndex));
var cells = row.getCells();
if(exists){
$.each(cells, function(index, cell){
if(cell instanceof sap.ui.commons.CheckBox){
row.$().toggleClass("existsLocal", true);
cell.setEnabled(false);
}
})
}
})
Instead you could bind to column with template. You have only rows binding and table does not know the columns.
BTW, You can define "enable" property of the checkbox with formatters. You need factory only for addStyleClass when necessary
So something like that: http://jsbin.com/poyetoqa/1/edit
See my edited solution in the original question. If you have a better working solution feel free to answer. Meanwhile I'll mark the question as answered.

Set Dropdownlist selected index with javascript?

I have 2 dropdownlists on a asp page.
If user changes the selected index of the first drop down list, then set DDL2.selectedindex = DDL1.Selectedindex
and do this same logic except switch DDL1 and DDL2 respectively. I have these both getting populated from the same list of objects(just different properties set to each) and i have a order by clause on the query to ensure the data stays in sync. My question is how can i get this logic to work in javascript? My current method is as such..
Accounts.Attributes.Add("onBlur", Customers.SelectedIndex = Accounts.SelectedIndex)
Customers.Attributes.Add("onBlur", Accounts.SelectedIndex = Customers.SelectedIndex)
This code doesn't work but demonstrates what im shooting for. When the ddl getting the first selection loses focus, populate the other ddl(setting the selected index). Any help would be great!
Can someone see what i'm doing wrong here?
$("[id$=ddlStandardAcctNo]").change(function () {
var acc = $("[id$=ddlStandardAcctNo]");
var cust = $("[id$=ddlCustomerName]");
cust.selectedindex = acc.selectedindex;
});
It compiles and just doesn't work... :( These drop downs are inside of a asp gridview.
After looking at that i'm trying to do this..
$("[id$=ddlStandardAcctNo]").blur(function () {
var acc = document.getElementById('<%=ddlStandardAcctNo.ClientID %>');
var cust = document.getElementById('<%=ddlCustomerName.ClientID %>');
cust.selectedindex = acc.selectedindex
});
$("[id$=ddlCustomerName]").blur(function () {
var acc = document.getElementById('<%=ddlStandardAcctNo.ClientID %>');
var cust = document.getElementById('<%=ddlCustomerName.ClientID %>');
acc.selectedindex = cust.selectedindex
});
Problem is i never use document.ready cause the dropdownlist are in a gridview. I'm literally just learning javascript/jquery as i run across issues like this so feel free to crack the knowledge whip lol.
I figured this out finally!!!! the solution for jquery prior is the following
$("[id$=ddlStandardAcctNo]").change(function () {
$("[id$=ddlCustomerName]").attr("selectedIndex", this.selectedIndex);
});
$("[id$=ddlCustomerName]").change(function () {
$("[id$=ddlStandardAcctNo]").attr("selectedIndex", this.selectedIndex);
});

how to populate select menu in ckeditor

I`m trying to add options to my select menu in my custom plugin. I want to get these options from array that I have and with forearch or for to create these options.How can I do that?
Could you show us your code that generates the select box? If I'm guessing right, you might be able to do something like
var things = [];
var your = ["Derpy","Fluttershy","Applejack"];
for(var i = 0; i < your.length; i++) {
// The two values used to separate actual and display values if needed
things[i] = [your[i],your[i]];
}
// snip snip
tab.add({
type: 'select',
label: 'myAwesomePonySelector',
id: 'myAwesomePonySelector',
items : things
// your other definitions, like onShow and commit
});
I hope this helps.

Categories

Resources