Get clicked Radio Button Values from all the row - javascript

I have a grid (dhtmlx) with lots of rows. What I am trying to achieve is to get all the values of clicked radio button of each row plus the row id separated by comma and put it into an input box ? The row ids and radio button values are separated by :
The row ids are automatically generated in this format 110014742~01~01
rowId:radioBtnValue, rowId:radioBtnValue, rowId:radioBtnValue
13004238~01~01:02, 110012178~01~01:05, 110014742~01~01:03 --> inside the input box when the radio buttons are clicked.
The column that contains all the radio button and its header had an id of rbBtn_sel
There will be another button when it is clicked will take the values from the input box and save it.
function DoRowSaveConfig() {
var colIndex=mygrid.getColIndexById("rdBtn_sel");
var radioBtn = mygrid.getCheckedRows(colIndex);
var CommaCount = radioBtn.split(",").length - 1 ;
for (var i= 0; i<radioBtn.length; i++)
if (radioBtn[i].checked) {
var selectedVal = radioBtn[i].value;
document.getElementById('an.ret.sys.4.').value = selectedVal;
document.getElementById('an.ret.sys.5.').click();
}
}
return false;
};
Maybe Jquery will have a better solution. Open to it.
http://jsfiddle.net/19eggs/ep6JE/
/**********EDIT**************/
Thanks all, and it works as expected but I may have mislead you. Upon clicking the radio button it needs to get the value of the row id not id(second col). Updated the image.
Row ids are automatically generated in this format 110012178~01~01. Also we are using xml and DHTMLX grid will automatically convert to a table.
<rows><row id="13004238~01~01"><cell>James Brown</cell>
<cell>12545</cell>
<cell><![CDATA[<div class="rd"><input type="radio" name="130042380101" value="00"></div>
<div class="rd"><input type="radio" name="1100121780101" value="01"></div>
<div class="rd"><input type="radio" name="130042380101" value="02"></div>
<div class="rd"><input type="radio" name="130042380101" value="03"></div>
<div class="rd"><input type="radio" name="130042380101" value="04"></div>
<div class="rd"><input type="radio" name="130042380101" value="05"></div>
<div class="rd"><input type="radio" name="130042380101" value="06"></div>]]>
</cell>
</row>\</rows>';

Here is my attempt - note it is much simpler than the map and assume you only have radios that you want to handle on the page
Live Demo
$(function() {
$("input[type=radio]").on("click",function() {
var clicked = [];
$("input[type=radio]:checked").each(function() {
clicked.push($(this).closest("td").prev().text()+"~"+this.value);
});
$("#an\\.ret\\.sys\\.4\\.").val(clicked);
});
});
If you need the NAME of the radio:
clicked.push(this.name+":"+this.value);

Use .map()
Fiddle Demo
function DoRowSaveConfig() {
var arr = $('table').find('input[type="radio"]:checked').map(function () {
return $(this).closest('tr').find('td:eq(1)').text() + ':' + this.value;
}).get().join();
console.log(arr);
};

Using .map() which create an array with .join() allow you to do that :
function DoRowSaveConfig(){
var arr = $('tr:not(:first)').map(function(){
var id = $.trim($(this).find('td').eq(1).text()); //1 == second column
var value = $(this).find(':checked').val(); //Find the checked one
return id + ':' + value; //Build an array of strings
}).get()
alert(arr.join(', ')); //Join them.
}
http://jsfiddle.net/ep6JE/1/
Edit
After your edit, this code should work :
function DoRowSaveConfig(){
var arr = $('row').map(function(){
var id = this.id;
var value = $(this).find(':checked').val(); //Find the checked one
return id + ':' + value; //Build an array of strings
}).get()
alert(arr.join(', ')); //Join them.
}

Related

Check if KendoGrid selected checkbox is checked or not

I have a ASP.Net MVC Kendo Grid with checkbox selection, as the documentation I added the checkbox using columns.Select().Width(50); as, then I want to fill an array of selected checkboxes inside of onChange function with javascript as:
Note: the stations array already have some values I.E [1,2,3], so I want to add new values in the next script
function onChange(e) {
const grid = $("#grid").data("kendoGrid");
var items = grid.items();
let ids = '';
grid.select().each(function() {
if (ids === '')
ids = grid.dataItem(this).StationId.toString();
else
ids = ids + ',' + grid.dataItem(this).StationId.toString();
stations.push(grid.dataItem(this).StationId);
})
}
The problem is on each check it is adding all existing checked checkboxes, I have no way to do something like if(checkbox is not checked) do a pop instead a push.
How can I check if clicked checkbox is checked or not in order to implement push or pop logic?
The select method will return all rows that are currently selected. If you need to figure out which is the checkbox that the user clicked last, you can probably toggle a class when the checkbox is checked/unchecked
function onChange(e) {
const grid = e.sender;
var items = grid.items();
let ids = '';
grid.select().each(function(idx,itm) {
$(itm).find("input").hasClass("checkedFlag") ?
kendoConsole.log(grid.dataItem(itm).ProductName + " was checked") :
kendoConsole.log(grid.dataItem(itm).ProductName + " was NOT checked");
})
var selected = $.map(this.select(), function(item) {
return $(item).text();
});
kendoConsole.log("Selected: " + selected.length + " item(s), [" + selected.join(", ") + "]");
}
function onDataBound(arg) {
$("input.k-select-checkbox").change(function(){
$(this).toggleClass("checkedFlag")
})
kendoConsole.log("Grid data bound");
}
If you are interested in only the Id's of the selected items then the Grid exposes a selectedKeyNames method, that you could use instead.
The change event of the Kendo grid will fire when the user selects or deselects a table row or cell in the grid (documentation), but it does not provide us with which rows are selected or deselected.
What you will need to do is store the selected items outside of the grid, compare it to the results of the select method in the change event, then store the updated results.
Something along these lines:
var selectedRecords = [];
function onChange(e) {
var updatedSelectedRecords = e.sender.select();
if (selectedRecords) {
var recordsSelected = updatedSelectedRecords.filter(record => !selectedRecords.includes(record)).map(record => record.StationId.toString());
stations.push(...recordsSelected);
var recordsDeselected = selectedRecords.filter(record => !updatedSelectedRecords.includes(record));
// do something with deselected records?
}
selectedRecords = updatedSelectedRecords;
}

jQuery update value with its parent in format

I have html markup like this
<input type="hidden" value="" id="shortcode_selected_package" name="shortcode_selected_package">
<div class="selected-packages-wrap">
<div class="shortcode-wrap">
<a class="data-remove" href="#" data-id="417" data-name="Test New Packs">-</a><label>Test New Packs</label>
<span class="checkbox-wrap">
<span><input type="checkbox" value="5">10 GB</span>
<span><input type="checkbox" value="26">Sony</span>
</span>
</div>
<div class="shortcode-wrap">
<a class="data-remove" href="#" data-id="220" data-name="New custom pack">-</a><label>New custom pack</label>
<span class="checkbox-wrap">
<span><input type="checkbox" value="5">10 GB</span>
<span><input type="checkbox" value="25">Unlimited Calls</span>
</span>
</div>
</div>
Here you can see in the first div element there are two checkbox with value 5, 26 (10 GB and Sony). So when someone check the checkbox of first div ten its value should be added with its parent value in the shortcode_selected_package div.
So lets say when user check both 10 GB and Sony then the value of the div should be like this
417[5|26]
if user checks the checkbox for the 2nd div then the value should be like this
417[5|26],220[5,25]
But if user unchecks any checkbox then its value should be remove from the set value. Like if user unchecks Unlimited Calls from the 2nd div then the value should be like
417[5|26],220[5,25]
I have tried this code but the values are not updating
$('body').on('click', '.selected-packages-wrap input[type=checkbox]', function() {
var PackageSelected = $('input#shortcode_selected_package').val();
var selectedVal = this.value;
var ParentId = $(this).parents('.shortcode-wrap').find('a.data-remove').attr('data-id');
if( this.checked ) {
selectPackage(ParentId, selectedVal, PackageSelected);
}
else {
unselectPackage(ParentId, selectedVal, PackageSelected);
}
});
function selectPackage(ParentId, selectedVal, PackageSelected) {
Packages = PackageSelected.split(',');
var Arr = [];
if(jQuery.inArray(ParentId, Packages) !== -1) {
$.each( Packages, function( key, val ) {
if( val == ParentId ) {
Packages[key] = val.replace(val, val + '[' + selectedVal + ']');
Arr.push(Packages);
}
});
console.log(Arr[0]);
}
}
First, I think that you should put the data-id of the link as a checkbox attribute or better yet at each div holding the checkboxes (it will be more convienient for selection instead of doing:
.parents('.shortcode-wrap').find('a.data-remove').attr('data-id');
)
Then what you do is every time on change or on click of any of the checkboxes you loop through the divs with class of shortcode wrap.
$('.selected-packages-wrap input[type=checkbox]').on('change', function() {
var checkboxes_data = [];
// Loop through the divs
for(var divs_count = 0; divs_count < $('.shortcode-wrap').length; divs_count++) {
checkboxes_data[divs_count] = {div_id: $('.shortcode-wrap:eq(' + divs_count + ')').attr('data-id'), checkboxes_id: [],}
// Loop through the checkboxes
for(var chBox_count = 0; chBox < $('.shortcode-wrap:eq(' + divs_count + ') input[type=checkbox]').length; chBox_count++) {
var $.current_checkbox = $('.shortcode-wrap:eq(' + divs_count + ') input[type=checkbox]:eq(' + chBox_count + ')');
// If the checkbox is checked add the value to the array
if($.current_checkbox.is(":checked")) {
checkboxes_data[divs_count].checkboxes_id.push($.current_checkbox.val()
}
}
}
var final_value = '';
// Goes trough the the newly created array adds the div value followed by the corresponding checkboxes value
checkboxes_data.forEach(function(div) {
var checkbox_ids = div.checkbox_ids.join(", ");
final_value += div.div_id + '[' + div.checkbox_ids + '], ';
});
$('#shortcode_selected_package').val(final_value);
});

Get ids of checked check boxes in a form using pure javascript

I have a table- each row has a checkbox of name checkBoxDelete. The id of the check box is unique(used the customer id).
I would like to get all the unique ids that were selected. So, I started by gathering all the elements of the form. Then check if it is a checkbox that is checked. If it is ,then get it's id.
var elLength = document.deleteForm.elements.length;
for (var i=0; i<elLength; i++){
var type = deleteForm.elements[i].type;
if (type=="checkbox" && deleteForm.elements[i].checked){
var rowID=deleteForm.elements[i].id;
checkedIds += rowID + ";" ;
count++;
}
}
However, rowID is always ";".
I believe I am not getting a reference to the checkbox correctly.
Change this var rowID=deleteForm.elements[i].id; to var rowID= document.deleteForm.elements[i].id;
You forgot document before selecting deleteForm

Monitor HTML and add changes to an input value

I have an indeterminate number of span and input tags with random IDs.
The user has the ability to change the HTML inside of <span> but not <input>.
It looks like this:
<span id="0">235</span>
<input id="5239aac3" value=235>
<span id="1">12</span>
<input id="123abc2" value=12>
<span id="2">235</span>
<input id="5res345" value=235>
I have put all the IDs of <input> into an array called arrayOfIDs and through JavaScript given all matching <span> tags and Id of the index.
for (var i = 0, l = arrayOfIDs.length; i < l; ++i) {
$('#' + i).on("change", function(){
var txt = $(this).find().text();
var $idval = $(arrayOfIDs[i]);
$idval.val(txt)
}).trigger("change");
}
What I need help with in the code above is how to monitor the change in the innerHTML of all spans and update the corresponding input.
I think that you need to change your first selector from $('#i') to $('#' + i)
otherwise you're selecting the element with the literal id of 'i' , which doesn't exist
Also, is the function firing at all? If so, what output do you get?
Finally, I think that you'll want to change var $idval = $(arrayOfIDs[i]); to var $idval = $('#' + arrayOfIDs[i]);

creating textbox onfly with jquery

I have a div to update say div id="txtbx". I need to insert textboxes inside this div. But the textbox should be equal to the no of the checkboxes in my page. So I am looping the checkbox as
$("#checkboxid").find("input[type=checkbox]").each (function(index)
{
//code to insert textboxes
});
But I am not sure how to insert these textboxes for each checkboxes. I tried using append()., but it will not update that div(txtbx) rather it will append the textboxes.
Rather than loop through each checkbox, you should count them first:
var num_boxes = $('#checkboxid').find('input[type="checkbox"]').length;
for(var i = 0; i < num_boxes; i++)
{
var this_box = $('<input type="text" name="textbox_' + i + '" />');
$('#txtbx').append(this_box);
}
You should do
$('#checkboxid').find('input[type=checkbox]').each(function(index)
{
var text_box = $('<input>', { type : "text", name="textbox_"+index});
$('#txtbx').append(text_box);
});
also note that you must use the same comma type here
$('#checkboxid")

Categories

Resources