Passing variable name as id - javascript

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.

Related

bootstrap select picker not working with input field

I have a select picker and I need to make that, when select language from this select picker gets a value from select and put into input filed.
The problem is that when i get value is success but after get show alert empty. and put value empty in field.
$(".m_selectpicker").selectpicker();
$(document).on('change', '.changeLanguage', function () {
var selectedLanguage = $(this).val();
alert(selectedLanguage);
$(this).parents('.countries').find('.lang').attr('name', 'name' + '[' + selectedLanguage + ']');
});
language
English
Arabic
Turkey
You can update the value attribute as well, see here https://jsfiddle.net/Lq2fz7dg/
$(document).on('change', '.changeLanguage', function () {
var selectedLanguage = $(this).val();
alert(selectedLanguage);
$(this).parents('.countries').find('.lang').attr('name', 'name' + '[' + selectedLanguage + ']');
$(this).parents('.countries').find('.lang').attr('value', selectedLanguage);
});
Update
This will work when .selectpicker() is initialized:
$(".m_selectpicker").on("changed.bs.select",
function(e, clickedIndex, newValue, oldValue) {
$('.lang').attr('name', 'name' + '[' + this.value + ']');
$('.lang').attr('value', this.value);
});
https://jsfiddle.net/no0r3qjf/

How to create a enhanced HTML TransferBox with an attribute

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>

jquery get first text element attribute from selected dropdown

both simple and complicate question:
I have my dropdown item created programmatically from ajax request and that is ok. So i serve name and surname for convenient aestetic way, but i need to send an ajax post with only surname and value is needed for other purposes.
$('#dropDocente').append('<option value="'+value.idDocente+'"">' + value.surname + ' ' + value.name +'</option>');
what i would achieve is:
var testd = $("#dropDocente option:selected").text();
console.log("Surname is : "+testd);
desired output == Surname is : Doe
so, in other hand, i would like get only first element of text in selected dropbox.
I can help me to understand how to reach my goal?
In jQuery, you don't use the .text() method to get the value of a dropdown menu. You need to just have:
var testd = $("#dropDocente").val();
and that will return the selected option's value from the dropdown.
you can add value.surname as a data-surname data tag onto the option and then retrieve that value by selecting the option and using .data('surname'). you can do this for any other value you want to single out as well
$(document).ready(function() {
var values = [
{ surname: "Doe", name: "John", idDocente: "some value here" },
{ surname: "Shmo", name: "John", idDocente: "some value here2" },
{ surname: "Little", name: "John", idDocente: "some value here3" },
];
for (var i = 0; i < values.length; i++) {
var value = values[i];
$('#dropDocente').append('<option value="'+value.idDocente+
'" data-surname="'+ value.surname +'">' + value.surname + ' '
+ value.name +'</option>');
}
// default first
$('.results').text($("#dropDocente option:first").data('surname') + ', ' + $("#dropDocente option:first").val());
// on change, get the surname
$('#dropDocente').on('change', function() {
$('.results').text($("#dropDocente option:selected").data('surname')+ ', ' + $("#dropDocente option:selected").val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropDocente">
</select>
<br/><br/><br/>
<div class="results">
</div>
You could just split full name on select change.
Something like this:
$('select').on('change', function(){
var id = $(this).val();
var fullName = $('select option:selected').text();
var surname = fullName.split(" ", 1);
});
Full example here: https://jsfiddle.net/1aj06Lw6/1/

javascript save state of check boxes

I am having an issue where the current state of the checkbox is not being saved. I am new to this and any help would be appreciated. Here's the jQuery code that is partially working.
var userCityList = [];
$("#checkboxes").unbind('change').bind('change', function (event) {
var stateVal = $(':selected', $('#ResidentialLocationStateList')).val();
var cityID = $(event.target)[0].id;//stores city id
var cityVal = $(event.target)[0].value;//stores city value
if ($('#' + cityID).is(':checked')) {
if (userCityList.length < 5) {
userCityList.push(cityID);
}
else {
$('#' + cityID).prop('checked', false);
alert("5 cities have been selected");
return;
}
}//end if
if (!($("#" + cityID).is(':checked'))) {
userCityList.pop();
}
//console.log(userCityList);
});
LOGIC
When the user selects a state, a set of cities in checkboxes appear. When a user clicks a checkbox, that particular city is stored in the userCityList array. When the user clicks it again, it deletes it from the array. However, if the user changes the state, those cities are no longer checked, which does not allow one to delete it from the array, if needed.
Any suggestions?
HTML code
<div class="panel-body">
<p>Select upto 5 state/city combinations</p>
<div class="col-xs-3 no-pad-left less-width">
#*<p>Select upto 5 state/city combinations</p>*#
<select id="ResidentialLocationStateList" name="ResidentialLocationStateList" multiple></select>
</div>
<div class="col-xs-3" id="checkboxes">
</div>
</div>
UPDATE Here's the image that goes with this issue.
So when a few cities are selected and the user decides to change the state from the select element, those cities that were selected prior need to be saved.
UPDATE
Here's the AJAX code...
$("#ResidentialLocationStateList").change(function () {
url = "/ResidentialBuilding/getCityList?state=";
state = $("#ResidentialLocationStateList").val();
url = url + state;
//console.log(url);
$("#checkboxes").empty();
$.getJSON(url, function (data) {
//console.log(data);
$.each(data, function (index, value) {
//console.log(value.city);
id = value.city;
id = id.replace(/\s+/g, '');
valCity = value.city;
valCity = valCity.replace(/\s+/g, '');
$("#checkboxes").append('<input value="' + valCity + '"' + 'type=' + "'checkbox'" + 'id=' + id + '>' + value.city + '</input><br>');
});
});
});
If you're using a modern version of jQuery I would recommend using .off and .on and to use .off if you really have to.
lso the .pop() array method removes the last element but the element just clicked may not always be the one that was added last. And since, the check boxes are added dynamically, the following bind could be made at the very beginning of DOM ready and not necessarily in any event handler. Rather than give your checkboxes the same ID which leads to invalid HTML, use a class selector, .checkboxes.
Therefore, I would suggest the following code
var userCityList = [];
$(document).on("change", ".checkboxes", function() {
var stateVal = $('#ResidentialLocationStateList').val();
var cityID = this.id;//stores city id
var cityVal = this.value;//stores city value
var finalDiv = $('#final');
var tempDiv = $('#othertempdiv');
if( this.checked ) {
if( userCityList.length < 5 ) {
userCityList.push( cityID );
finalDiv.append( this );
} else {
$(this).prop('checked', false);
alert('5 cities have been selected');
}
} else {
var index = $.inArray( cityID, userCityList );
if( index > -1 ) {
userCityList.splice( index, 1 );
tempDiv.append( this );
}
}
});
Since you're -- per comments below -- replacing the selected cities each time you select a new state, you would have to have a second div which would hold all the selected cities. Un-checking any of the cities in this final div would move it back; if another state is selected, such a city would be lost.
<div id="final"></div>
Use a multidimensional array to store both state and city IDs, like userCityList [ stateVal ]:
var userCityList = [];
$("#checkboxes").unbind('change').bind('change', function (event) {
var stateVal = $(':selected', $('#ResidentialLocationStateList')).val();
var cityID = $(event.target)[0].id;//stores city id
var cityVal = $(event.target)[0].value;//stores city value
if ($('#' + cityID).is(':checked')) {
if (userCityList.length < 5) {
if(!userCityList[stateVal])userCityList[stateVal] = [];
userCityList[stateVal].push(cityID);
}
else {
$('#' + cityID).prop('checked', false);
alert("5 cities have been selected");
return;
}
}//end if
if (!($("#" + cityID).is(':checked'))) {
if(userCityList[stateVal]){
//Edited, now it can remove the city by its position (index)
var position = $.inArray(cityID, userCityList[stateVal]);
userCityList[stateVal].slice(position, 1);
}
}
});
So when you need to retrieve the checked cities for an state you can do just:
for(var i =0; i < userCityList[stateVal].length; i++){
console.log(userCityList[stateVal][i]);
}
UPDATE
The hard work is done. Now, in your ajax code, when you load a new set of checkboxes, you have to check if the checkbox was previously checked:
$("#ResidentialLocationStateList").change(function () {
url = "/ResidentialBuilding/getCityList?state=";
state = $("#ResidentialLocationStateList").val();
url = url + state;
//console.log(url);
$("#checkboxes").empty();
$.getJSON(url, function (data) {
//console.log(data);
$.each(data, function (index, value) {
//console.log(value.city);
id = value.city;
id = id.replace(/\s+/g, '');
valCity = value.city;
valCity = valCity.replace(/\s+/g, '');
$("#checkboxes").append('<input value="' + valCity + '"' + 'type=' + "'checkbox'" + 'id=' + id + '>' + value.city + '</input><br>');
//Let's check if this checkbox was previously checked
if($.inArray(id, userCityList[state])){
//if yes, let's check it again
$('#'+id).prop('checked', true);
}
});
});
});
Keep in mind that the userCityList variable must be global to store these values and you will loose your checkboxes memories if you refresh the page, of course.

DOJO: dojox.grid.TreeGrid + checkbox How to

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)

Categories