Is it possible to place chceckboxes inside LazyTreeGrid ?
Maybe there is some plugin that would automatically update the selected object and fire onSelectionChanged event ?
Thanks for help.
The treegrid has a bug in terms of checkbox.
{ field: "isSelected",name: "Selected", width: "6em", editable:"true",alwaysEditing:"true",cellType:"dojox.grid.cells.Bool"},
Will show the checkbox. But it will not provide you the value when you check/uncheck the value.
To fix it, you need to do this:
{ field: "recvid",name: "Selected", width: "6em",formatter:formatCheckBox},
function formatCheckBox(value,rowIndex)
{
var icon;
//var item = e.grid.getItem(rowIndex);
//var itemName = item.itemName.toString();
var id = value + "|" + 'Selected';
//console.log(rowIndex + " "+value);
if (rowIndex!=-1)
{
icon = "<input style=\"vertical-align: middle;\" id='" + id + "' name='grid_item_checkbox' type='checkbox' /> ";
}
return icon;
}
Dijit Tree with Multi State Checkboxes (appeared as first result when Googling)
Related
I need to create an enhanced transferbox, using HTML, JavaScript and JQuery.
I have a set of options a user can select from and associate with an attribute. The selection and deselection must be accomplished with two SELECT HTML elements (i.e., a transferbox). For example, these options can be a list of skill names.
When the 'add' button is clicked, the option(s) selected in the first SELECT element, along with an attribute (e.g. number of years from a text box) must be transferred from the source SELECT element to selected/destination SELECT element. The attribute must be displayed along with the item text in this second SELECT element (for example, the item displays the skill and the number of years).
When the 'remove' button is clicked, the selected option(s) in the second SELECT element must be moved back to the first SELECT element (in the original format .. without the attribute).
JSON should be the data format for initial selection setup and saving latest selections.
I want an initial set of selections and attributes to be set via JSON in an a hidden input field. I want the final set of selections to be saved to JSON in the same hidden input field.
Example HTML:
<input type="hidden" id="SelectionsId" value='[{ "id": "2", "attribute":"15"},{ "id": "4", "attribute":"3" }]' />
<!--<input type="hidden" id="SelectionsId" value='[]' />-->
<div>
<select class="MultiSelect" multiple="multiple" id="SelectFromId">
<option value="1">.NET</option>
<option value="2">C#</option>
<option value="3">SQL Server</option>
<option value="4">jQuery</option>
<option value="5">Oracle</option>
<option value="6">WPF</option>
</select>
<div style="float:left; margin-top:3%; padding:8px;">
<div>
<span>Years:</span>
<input id="YearsId" type="number" value="1" style="width:36px;" />
<button title="Add selected" id="includeBtnId">⇾</button>
</div>
<div style="text-align:center;margin-top:16%;">
<button title="Remove selected" id="removeBtnId">⇽</button>
</div>
</div>
<select class="MultiSelect" multiple="multiple" id="SelectToId"></select>
</div>
<div style="clear:both;"></div>
<div style="margin-top:40px;margin-left:200px;">
<button onclick="SaveFinalSelections();">Save</button>
</div>
Example CSS:
<style>
.MultiSelect {
width: 200px;
height: 200px;
float: left;
}
</style>
Visual of requirement:
Here's a solution to the challenge. The variables being setup at the start make this solution easy to configure and maintain.
When the page gets displayed, the SetupInitialSelections method looks at the JSON data in the hidden input field and populates the selected items.
When the 'Save' button clicked, the current selections are converted to JSON and placed back in the hidden input field.
Invisible character \u200C is introduced to delimit the item text and the attribute during display. This comes in to use if the item has to be removed and the original item text has to be determined so it can be placed back in the source SELECT element.
The selectNewItem variable can be set to true if you would like the newly added item to be selected soon after adding it to the SELECT element via the 'add' or 'remove' operations.
This solution supports multiple item selections. So multiple items can be added at once ... and similarly multiple items can be removed at once.
<script src="jquery-1.12.4.js"></script>
<script>
var savedSelectionsId = 'SelectionsId';
var fromElementId = 'SelectFromId';
var toElementId = 'SelectToId';
var includeButtonId = 'includeBtnId';
var removeButtonId = 'removeBtnId';
var extraElementId = 'YearsId';
var extraPrefix = " (";
var extraSuffix = " years)";
var noItemsToIncludeMessage = 'Select item(s) to include.';
var noItemsToRemoveMessage = 'Select item(s) to remove.';
var selectNewItem = false;
var hiddenSeparator = '\u200C'; // invisible seperator character
$(document).ready(function () {
SetupInitialSelections();
//when button clicked, include selected item(s)
$("#" + includeButtonId).click(function (e) {
var selectedOpts = $('#' + fromElementId + ' option:selected');
if (selectedOpts.length == 0) {
alert(noItemsToIncludeMessage);
e.preventDefault();
return;
}
var attribute = $("#" + extraElementId).val();
selectedOpts.each(function () {
var newItem = $('<option>', { value: $(this).val(), text: $(this).text() + hiddenSeparator + extraPrefix + attribute + extraSuffix });
$('#' + toElementId).append(newItem);
if (selectNewItem) {
newItem.prop('selected', true);
}
});
$(selectedOpts).remove();
e.preventDefault();
});
//when button clicked, remove selected item(s)
$("#" + removeButtonId).click(function (e) {
var selectedOpts = $('#' + toElementId + ' option:selected');
if (selectedOpts.length == 0) {
alert(noItemsToRemoveMessage);
e.preventDefault();
return;
}
selectedOpts.each(function () {
var textComponents = $(this).text().split(hiddenSeparator);
var textOnly = textComponents[0];
var newItem = $('<option>', { value: $(this).val(), text: textOnly });
$('#' + fromElementId).append(newItem);
if (selectNewItem) {
newItem.prop('selected', true);
}
});
$(selectedOpts).remove();
e.preventDefault();
});
});
// Setup/load initial selections
function SetupInitialSelections() {
var data = jQuery.parseJSON($("#" + savedSelectionsId).val());
$.each(data, function (id, item) {
var sourceItem = $("#" + fromElementId + " option[value='" + item.id + "']");
var newText = sourceItem.text() + hiddenSeparator + extraPrefix + item.attribute + extraSuffix;
$("#" + toElementId).append($("<option>", { value: sourceItem.val(), text: newText }));
sourceItem.remove();
});
}
// Save final selections
function SaveFinalSelections() {
var selectedItems = $("#" + toElementId + " option");
var values = $.map(selectedItems, function (option) {
var textComponents = option.text.split(hiddenSeparator);
var attribute = textComponents[1].substring(extraPrefix.length);
var attribute = attribute.substring(0, attribute.length - extraSuffix.length);
return '{"id":"' + option.value + '","attribute":"' + attribute + '"}';
});
$("#" + savedSelectionsId).val("[" + values + "]");
}
</script>
I have an input field with Add button below it. Also have another Div class named .new-option-content
What I am trying to do is if anyone type something in the input filed and click the +ADD button this text of the input filed will append with a Check box inside .new-option-content div.
Here is the Fiddle
I tried with this but I guess with this process I can't get the result.
$( ".checklist-new-item-text" )
.keyup(function() {
var value = $( this ).val();
$( ".new-option-content" ).text( value );
})
.keyup();
I am not good with advance jquery. I did tried to find something similar but failed. I am not sure if this can be done with jquery.
Any help or suggestion will be appreciated.
$("#add").click(function(){
var newLabel = $("#optionInput").val();
if (!newLabel) return; //avoid adding empty checkboxes
var newOption = '<div class="checkbox"><label><input type="checkbox">' + newLabel +'</label></div>';
$(".new-option-content").append(newOption);
$("#optionInput").val(''); //clearing value
})
Fiddle: http://jsfiddle.net/has9L9Lh/8/
If you want to use it in multiple places on your page, you can try this modified version:
$(".new-option-add").click(function(){
var labelInput = $(this).parent().parent().find(".checklist-new-item-text")
var newLabel = labelInput.val()
if (!newLabel) return; //avoid adding empty checkboxes
var newOption = '<div class="checkbox"><label><input type="checkbox">' + newLabel +'</label></div>';
// where to append?
var listToAppend = $(this).attr("data")
$("." + listToAppend).append(newOption);
labelInput.val(''); //clearing value
})
We are using data attribute value on the button, to assign class name of the list, which need to be updated.
Fiddle: http://jsfiddle.net/has9L9Lh/18/
Here is how you can do it:
$(function() {
$('.new-option-add').on('click',function() {
var noc = $('.new-option-content'),
val = $('.checklist-new-item-text');
!val.val() || noc.append(
$('<div/>',{class:'checkbox'}).html(
$('<label/>').html( $('<input/>', {type:'checkbox'}) )
.append( ' ' )
.append( val.val() )
)
);
val.val('');
});
});
DEMO
And this should work for multiple sections:
$(function() {
$('.new-option-add').on('click',function() {
var section = $(this).closest('section'),
noc = $('.new-option-content', section),
val = $('.checklist-new-item-text', section);
!val.val() || noc.append(
$('<div/>',{class:'checkbox'}).html(
$('<label/>').html( $('<input/>', {type:'checkbox'}) )
.append( ' ' )
.append( val.val() )
)
);
val.val('');
});
});
DEMO
Many have answered, yet another option is to use .clone(), cause otherwise you can end up in a maintainence nightmare, so something like
$(".new-option-add").click(function() {
var checkbox = $(".checkbox:first").clone(), value;
value = $(".checklist-new-item-text").val();
checkbox.html(checkbox.html().replace('Sample 1', value));
checkbox.appendTo($(".new-option-content"));
})
http://jsfiddle.net/has9L9Lh/19/
you can do this by adding this code
on click event
$('#yourDiv').append(' <label><input id="chkbox" type="checkbox"> "+$('#yourText').val() +" </label>');
I have this fiddle which is having user tab.In user tab ,there are three fields which accepts name,mobile and email.When a user fills all the three and hits add button then a row is inserted.Now i want to make the new added row editable.This means that I want to keep 2 bootstrap buttons edit and delete.So if delete is pressed then the entire row will be deleted and if edit is pressed then the entire will be editable where user can change the mobile number,name and email.Can any body please tell me how to do.
This js code adds new rows
$('#btn1').click(function () {
if ($(".span4").val() != "") {
$("#mytable").append('<tr id="mytr' + val + '"></tr>');
$tr=$("#mytr" + val);
$tr.append('<td class=\"cb\"><input type=\"checkbox\" value=\"yes\" name="mytr' + val + '" unchecked ></td>');
$(".span4").each(function () {
$tr.append("<td >" + $(this).val() + "</td>");
});
var arr={};
name=($tr.find('td:eq(1)').text());
email=($tr.find('td:eq(2)').text());
mobile=($tr.find('td:eq(3)').text());
arr['name']=name;arr['email']=email;arr['mobile']=mobile;
obj[val]=arr;
val++;
} else {
alert("please fill the form completely");
}
This question is so specific to the OP scenario, so i will try to make the answer a bit more general.
I'm no expert here, but it seems you already capture the user's input and cloned it when they click Add to a new td. Therefore from what I understood is that you need to edit/delete the data from the new created td.
We have a table that contains several fields. We want to apply the following action on them
1- Add
2- Edit
3- Delete
Maybe this isn't the best practice, in short, my approach for this was to insert two spans for each data value:
One hidden that contains an input text field (inputSpan).
Another just contains plain text value (dataSpan).
Whenever you want to edit, dataSpan (just a data container) will disappear and inputSpan (text input field) appears instead enabling you to edit the text field. Once you edit and click Save the data in the text field will be cloned to replace the data in dataSpan. So basically dataSpan is just a reflection to inputSpan text field.
Here is an updated demo:
JSFiddle >> FullView Fiddle
I suggest for readability purposes, you break your code down into small function, it will make life easier, just sayin. So here general logic for your idea:
deleteRow = function (trID) {
// delete code goes here, remove the row
$(trID).remove();
}
manageEdit = function (tdNo) {
if ($("#edit-btn" + tdNo).html() === "Edit") {
$("#save-btn" + tdNo).show();//show save button
$("#edit-btn" + tdNo).html("Cancel");//change edit to cancle
editRow(tdNo);//call edit function
} else if ($("#edit-btn" + tdNo).html() === "Cancel") {
$("#save-btn" + tdNo).hide();//hide save button
$("#edit-btn" + tdNo).html("Edit");//change back edit button to edit
cancelEditRow(tdNo);
}
}
editRow = function (tdNo) {
$(".inputSpan" + tdNo).show();//show text input fields
$(".dataSpan" + tdNo).hide();//hide data display
}
cancelEditRow = function (tdNo) {
//looop thru 3 input fields by id last digit
for (var i = 0; i < 3; i++) {
//get input span that contain the text field
var inputSpan = $("#inputSpan" + tdNo + "-" + i);
//get the data span that contain the display data
var dataSpan = $("#dataSpan" + tdNo + "-" + i);
//text field inside inputSpan
var textField = inputSpan.find('input:text');
inputSpan.hide();//hide input span
textField.val(dataSpan.html());//take original data from display span and put it inside text field to cncle changes.
dataSpan.show();//show data span instead of edit field
}
}
saveRow = function (tdNo) {
//same as edit, but we reverse the data selection.
for (var i = 0; i < 3; i++) {
var inputSpan = $("#inputSpan" + tdNo + "-" + i);
var dataSpan = $("#dataSpan" + tdNo + "-" + i);
var textField = inputSpan.find('input:text');
inputSpan.hide();
dataSpan.html(textField.val());//take data from text field and put into dataSpan
dataSpan.show();
}
$("#edit-btn" + tdNo).html("Edit");//change text to edit
$("#save-btn" + tdNo).hide();//hide same button.
}
Here where I add the spans:
var tdCounter = 0;
$(".span4").each(function () {
var tid = val+"-"+tdCounter;
$tr.append("<td id='#mytd"+tid+"'>
<span id='inputSpan"+tid+"' class='inputSpan"+val+"' style='display:none'>
<input type='text' id='#input"+tid+"' value='"+ $(this).val() + "' /></span>
<span id='dataSpan"+tid+"' class='dataSpan"+val+"'>"+$(this).val()+"</td>");
tdCounter++;
});
Here I just append the buttons to call the functions, each button works for it's own row:
$tr.append("<td><botton id='edit-btn" + val + "' class='btn' onclick=manageEdit('" + val + "');>Edit</botton></td>");
$tr.append("<td><botton style='display:none' id='save-btn" + val + "' class='btn' onclick=saveRow('" + val + "');>Save</botton></td>");
$tr.append("<td><botton id='delete-btn" + val + "' class='btn' onclick=deleteRow('" + trID + "');>Delete</botton></td>");
Below is a sample function, it wont do everyhing you need, but it shows the jquery functions and one possibility how to do it. I only enabled editing name field, and deleting.
You would have to add other fields, + copy id data for the input.
js Fiddle
window.deleteRow = function (tar) {
$(tar).parent().remove();
}
window.editRow = function (tar) {
var row = $(tar).parent(),
cells, name;
cells = row.find("td");
name = $(cells.get(1)).text();
$(cells.get(1)).text('');
$(cells.get(1)).append('<input type="text" value="' + name + '">');
}
window.saveData = function() {
var data = {};
data.name = "some name";//get this from your input
data.email= "some email";//get this from your input
data.phone= "some phone";//get this from your input
$.get("http://yourphpsite.com", data, function(data, status) {
//data contains your server response
if (data.somepositiveservermessage) {
$("#user_notification_field").text("data saved");
$("#user_notification_field").show();
});
}
I am appending the checkboxes in a particular class using some function.. I have a function to run everytime the checkbox is selected.. So I need to get the name and id of the Checkboxes..
Heres the part of the code where I am appending the checkbox dynamically.. Here value is the one I want the id and name attribute to be..
$.each(brandNameg, function(key, value) {
$(".fpblocks .fpblocksBrands_inner ul").append("<label class='checkbox'><input type='checkbox' onclick='selectMainBrand(\"" + value + "\");' />" + value + "</label>");
});
set the id using
$.each(brandNameg, function(key, value) {
$(".fpblocks .fpblocksBrands_inner ul").append('<label class="checkbox"><input type="checkbox" id="' + value + '" onclick="selectMainBrand("' + value + '");" />' + value + '</label>');
});
function selectMainBrand(ids) {
$('#Brands').on("change", "input", function () {
console.log("called");
var selected = this.name;
console.log(selected);
});
}
I'm assuming your UL tag has id="brands". If not change the above code as follows
$('.fpblocks').on("change", "input", function () {
$.each(brandNameg, function(key, value) {
$(".fpblocks .fpblocksBrands_inner ul").append("<label class='checkbox'><input type='checkbox' id ='someID' name ='someName' />" + value + "</label>");
});
and on checkbox click..
$(".fpblocks .fpblocksBrands_inner ul :checkbox").live('click', function(){
var id = $(this).attr('id'); //get id of checked checkbox
var name = $(this).attr('name'); //get name of checked checkbox
})
remove onclick='selectMainBrand(value);' from inputs' generation code
After checkboxes are generated, you can select name and
$('#Brands input').on("change", function () {
var name=$(this).attr("name");
var id=$(this).attr("id");
alert(name);
alert(id);
console.log(selected);
});
see the DEMO http://jsfiddle.net/BbtEG/
Your dynamically created html (<input type='checkbox' onclick='selectMainBrand(value);' />) does not have a name, or an id. You cannot pass what doesn't exist. To solve this, generate a name and an id to use.
Also in your selectMainBrand function you don't appear to be using the ids parameter that you're passing in. All that function is doing is binding a handler to the input which, since you're using on to bind it, seems silly.
Why not use on to delegate the handler instead? If you delegate the handler, you can grab the name or id from within the handler thereby obviating the need to pass those in as parameters (working demo).
$.each(brandNameg, function (key, value) {
var label = $('<label />').addClass('checkbox'),
input = $('<input />').attr({
"type": "checkbox",
"name": "mainBrand" + key, //set the name, appending the key to make it unique
"id": "mainBrand" + key //set the id, appending the key to make it unique
});
$(".fpblocks .fpblocksBrands_inner ul").append(label.append(input).append(value));
});
//delegate the change handler
$('.fpblocks .fpblocksBrands_inner').on("change", '#Brands input', function (e) {
var selectedName = this.name,
selectedId = this.id,
isChecked = this.checked;
console.log(JSON.stringify({
"called": true,
"selectedName": selectedName,
"selectedId": selectedId,
"isChecked": isChecked
}));
});
If you truly have your heart set on passing in the parameters, there are ways to do that, such as binding the handler within the loop where you create the inputs (working demo):
$.each(brandNameg, function (key, value) {
var label = $('<label />').addClass('checkbox'),
input = $('<input />').attr({
"type": "checkbox",
"name": "mainBrand" + key, //set the name, appending the key to make it unique
"id": "mainBrand" + key //set the id, appending the key to make it unique
}).click(function (e) {
var self = $(this), // capture the input as a jQuery object (typically very useful)
actualHandler = function (id, name) {
// do stuff
console.log(JSON.stringify({
"called": "actualHandler",
"selectedName": id,
"selectedId": name,
"isChecked": self.prop('checked')
}));
};
actualHandler(this.id, this.name);
// or
actualHandler(self.attr('id'), self.attr('name'));
});
$(".fpblocks .fpblocksBrands_inner ul").append(label.append(input).append(value));
});
or you could set the onchange attribute in the loop where you create the inputs (working demo):
window.inputHandler = function (id, name) { // must be added to the global scope, otherwise it won't be visible.
// do stuff
console.log(JSON.stringify({
"called": "inputHandler",
"selectedName": id,
"selectedId": name
}));
};
$.each(brandNameg, function (key, value) {
var label = $('<label />').addClass('checkbox'),
input = $('<input />').attr({
"type": "checkbox",
"name": "mainBrand" + key, //set the name, appending the key to make it unique
"id": "mainBrand" + key, //set the id, appending the key to make it unique
"onchange": "inputHandler('" + "mainBrand" + key + "', '" + "mainBrand" + key + "')"
});
$(".fpblocks .fpblocksBrands_inner ul").append(label.append(input).append(value));
});
and there are other ways to go about it.
Personally, I would use the delegation.
i am using this code to access all the hidden elements from a form:
function get_hidden_val(ids,form_id)
{
var get_check_val = document.getElementById(ids);
if(get_check_val.checked){
var div = $('<div></div>')
.appendTo('form#bulk_add_cart')
.attr('id',"bulk_"+form_id)
$("form#" +form_id).find('input[type="hidden"]').each(function(){
var value =$(this).val();
var name = $(this).attr("name");
var tags = "<input type='hidden' value='" + value + "' name='"+name+"'>";
$('div#' +form_id).append(tags);
});
}
else
{
$("form#bulk_add_cart").find('div#' +form_id).remove();
}
}
My problem is when I click the first checkbox it give me the result but when i click the second checkbox it doesn't and also the another problem is when i click first checkbox it shows total hidden elements but when i second time checked it, it show 4 less ?
Please suggest a solution.
Thanks
#user704302: Missing >, update var tags to --
var tags = "<input type='hidden' value='" + value + "' id='"+id+"'>";