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);
});
Related
I have dynamically generated checkbox based on JSON data and that is generated by jQuery. I need to dynamically generate checkbox class name. Here is my code that is generated a checkbox
<td>
<label class="switch">
<input
id="chkEnabled"
checked
type="checkbox"
onchange="checkedorUncheked(' + result.data.resultSet[i].id + ',' + count + ')" class="chkEnabled"' + count +' >
<span class="slider round"></span>
</label >
</td>
Here class="chkEnabled"' + count +' I'm incrementing class value but when I call the method checkedorUncheked I get count value but not getting the class value. Here I console it
` this.checkedorUncheked = function (item, item2) {
//console.log('.chkEnabled' + item2);
$('.chkEnabled' + item2).change(function () {
console.log(item2);`
I'm not able to console inside change event because of class name.
when HTML elements are dynamically generated, you need to rebind the events of the generated element
Try
this.checkedorUncheked = function (item, item2) {
//console.log('.chkEnabled' + item2);
$('.chkEnabled' + item2).on('change',function () {
console.log(item2);
Use on() method instead of directly using .change(), but in comments as suggested don't generate class, generate Id instead and use the same.
then code becomes
$('#chkEnabled' + item2).on('change',function () {
console.log(item2);
UPDATE
<input
id=' + result.data.resultSet[i].id + '
checked
type="checkbox"
onchange="checkedorUncheked(this);" count=' + count +' >
<span class="slider round"></span>
function checkedorUncheked (e){
var itme1 = $(e).attr('id'); /// for id
var item2 = $(e).attr('count'); // count
if($(e).prop('checked') == true){
//do something
}
else{
/// do another
}
}
I have done the dynamic generates textbox based on the number that user type. For example, user types 10 in the input box clicked add will generate 10 input box. I have a label to catch the number.
here is my question
how do I start from 1?
how do I rearrange the number when user remove one of the input boxes
here is my javascript
$(document).ready(function () {
$("#payment_term").change(function () {
var count = $("#holder input").size();
var requested = parseInt($("#payment_term").val(), 10);
if (requested > count) {
for (i = count; i < requested; i++) {
$("#payment_term_area").append('<div class="col-lg-12 product_wrapper">' +
'<div class="col-lg-12 form-group">' +
'<label>' + i + 'Payment</label>' +
'<input type="text" class="payment_term form-control" name="PaymentTerm[]"/>' +
'</div>' +
'cancel' +
'</div>');
}
$("#payment_term_area").on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('.product_wrapper').remove();
calculateTotal();
x--;
})
}
});
});
here is my view
<input type="text" id="payment_term" />
<button onclick="function()">Add</button>
<div id="payment_term_area"></div>
You were nearly there, however, by hardcoding the label's you were making updating them difficult for yourself. I have created a jsfiddle of my solution to your problems. I personally prefer to cache the values of my jQuery objects so that they arent hitting the DOM each time they are referenced, for the performance boost (hence why they are listed at the top). I also, find it nicer to bind the click event in JS rather than using the html attribute onclick, but this is just a preference.
JSFIDDLE
Javascript
// create cache of jQuery objects
var add_payment_terms_button = $('#add_payment_terms');
var payment_term_input = $('#payment_term');
var payment_term_area = $('#payment_term_area');
var default_payment_values = ['first value', 'second value', 'third value', 'forth value', 'fifth value'];
var default_other_value = 'default value';
// bind to generate button
add_payment_terms_button.on('click', generatePaymentTerms);
function generatePaymentTerms(){
var requested = parseInt(payment_term_input.val(), 10);
// start i at 1 so that our label text starts at 1
for (i = 1; i <= requested; i++) {
// use data-text to hold the appended text to the label index
payment_term_area.append(
'<div class="col-lg-12 product_wrapper">' +
'<div class="col-lg-12 form-group">' +
'<label data-text=" Payment"></label>' +
'<input type="text" class="payment_term form-control" name="PaymentTerm[]"/>' +
'</div>' +
'cancel' +
'</div>');
}
// call the function to set the labels
updateProductIndexes();
}
function updateProductIndexes(){
// get all labels inside the payment_term_area
var paymentLabels = payment_term_area.find('.product_wrapper label');
for(var x = 0, len = paymentLabels.length; x < len; x++){
// create jQuery object of labels
var label = $(paymentLabels[x]);
// set label text based upon found index + 1 and label data text
label.text( getOrdinal(x + 1) + label.data('text'));
// either set the next input's value to its corresponding default value (will override set values by the user)
label.next('input.payment_term').val(default_payment_values[x] || default_other_value)
// or optionally, if value is not equal to blank or a default value, do not override (will persist user values)
/* var nextInput = label.next('input.payment_term');
var nextInputValue = nextInput.val();
if(nextInputValue === '' || default_payment_values.indexOf(nextInputValue) >= 0 || nextInputValue === default_other_value){
nextInput.val(default_payment_values[x] || default_other_value)
} */
}
}
// courtesy of https://gist.github.com/jlbruno/1535691
var getOrdinal = function(number) {
var ordinals = ["th","st","nd","rd"],
value = number % 100;
return number + ( ordinals[(value-20) % 10] || ordinals[value] || ordinals[0] );
}
payment_term_area.on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('.product_wrapper').remove();
// after we remove an item, update the labels
updateProductIndexes();
})
HTML
<input type="text" id="payment_term" />
<button id="add_payment_terms">Add</button>
<div id="payment_term_area"></div>
First you have to give id for each label tag ex:<label id='i'>
Then you can re-arrange the number by using document.getElementById('i')
Refer the Change label text using Javascript
hope this will be much helpful
I have a list of checkboxes in my kendo grid.Select all option is also there.
Problem is When i click select all then all the checkboxes selected and then unselect some checkboxes and going to save then it shows me all the checkboxes.(un checked checkboxes also shown )
My Code
$('#itemGrid').on('change', '.usedchk', function () {
var checked = $(this).is(':checked');
var grid = $('#itemGrid').data().kendoGrid;
var dataItem = grid.dataItem($(this).closest('tr'));
var selected = $('#selected').val();
var id = dataItem.itemId;
if ($('#selected').val().indexOf(id) == -1) {
if ($('#selected').val() == '') {
$('#selected').val(id);
} else {
$('#selected').val(selected + "," + id );
}
}
});
use below code on save, to get all checked checkboxes as a comma separated string
var output = $.map($('#selected:checked'), function(n, i){
return n.value;
}).join(',');
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.
}
I had a quick question that I can't figure out. I am working with this code:
http://jsfiddle.net/spadez/ZTuDJ/32/
// If JS enabled, disable main input
$("#responsibilities").prop('disabled', true);
// $("#responsibilities").addClass("hidden");
// If JS enabled then add fields
$("#resp").append('<input placeholder="Add responsibility" id="resp_input" ></input><input type="button" value="Add" id="add"> ');
// Add items to input field
var eachline='';
$("#add").click(function(){
var lines = $('#resp_input').val().split('\n');
var lines2 = $('#responsibilities').val().split('\n');
if(lines2.length>10)return false;
for(var i = 0;i < lines.length;i++){
if(lines[i]!='' && i+lines2.length<11){
eachline += lines[i] + '\n';
}
}
$('#responsibilities').text($("<div>" + eachline + "</div>").text() );
$('#resp_input').val('');
});
The idea is that you type something in the responsibility field and it gets inserted into a text area. What I also want to do is that when an item is inserted into the text area it also prints it out above it in a list format like this:
<li>inserted item 1</li> <li>inserted item 2</li>
I'm really new to javascript but this was my best stab at it based on information found online:
$("#resp").append('<li> +eachline </li> ')
$('#responsibilities').text($("<div>" + eachline + "</div>").text() ).before("<li>"+lines+"</li>");
Demo ---> http://jsfiddle.net/ZTuDJ/34/
http://jsfiddle.net/pjdicke/ZTuDJ/35/
You will need to create a <ul> then add this below
$('#responsibilities').text( $("<div>" + eachline + "</div>").text() );
// add this line after above
$('<li>' + lines + '</li>').appendTo('#list');
I already fixed that for you in your previous question.
Jquery adding items to a list without reloading page
http://jsfiddle.net/blackjim/VrGau/15/
var $responsibilityInput = $('#responsibilityInput'),
$responsibilityList = $('#responsibilityList'),
$inputButton = $('#addResp'),
rCounter = 0;
var addResponsibility = function () {
if(rCounter < 10){
var newVal = $responsibilityList.val()+$responsibilityInput.val();
if(newVal.trim()!==''){
var newLi = $('<li>');
$('ul#respList').append(newLi.text(newVal));
$responsibilityList.val('');
rCounter+=1;
}
}
}
$inputButton.click(addResponsibility);