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
}
}
Related
I need to update the price global variable. I believe it may have something to do with scope. I would appreciate it if you could be of assistance in this regard.
This is the script:
var price = 0;
var nextdayClass = $('.delivery1');
var $standardClass = $('.delivery2');
var $pickupClass = $('.delivery3');
nextdayClass.on('click', function() {
var nextday = $('#nextday').data('price');
price = nextday;
console.log(price);
});
standardClass.on('click', function () {
var standard = $('#standard').data('price');
price = standard;
console.log(price);
});
pickupClass.on('click', function () {
var pickup = $('#pickup').data('price');
price= pickup;
console.log(price);
});
console.log(price);
cartTotalHTML += '<div>' +
'<ul>' +
'<li>' +
'<div>Subtotal</div>' +
'<div>' + formatMoney(total) + '</div>' +
'</li>' +
'<li>' +
'<div>Shipping</div>' +
'<div>' + formatMoney(price) + '</div>' +
'</li>' +
'<li>' +
'<div>Total</div>' +
'<div>' + totalAfterShipping(total, price) + '</div' +
'</li>' +
'</ul>' +
'</div>';
$('#cartOutput').html(cartItemHTML);
Here is the html where i am getting my data from:
<div class="delivery">
<div>Shipping method</div>
<div>Select the one you want</div>
<div class="delivery_options">
<label>Next day delivery
<input id="nextday" type="radio" name="radio" data-name="nextday" data-price="9000">
<span class="checkmark delivery1"></span>
<span class="delivery_price">R90</span>
</label>
<label>Standard delivery
<input id="standard" type="radio" name="radio" data-name="standard" data-price="3000">
<span class="checkmark delivery2"></span>
<span >R30</span>
</label>
<label>Personal pickup
<input id="pickup" type="radio" checked="checked" data-name="pickup" data-price="0" name="radio">
<span class="checkmark delivery3"></span>
<span >Free</span>
</label>
</div>
</div>
Here is the html where i am taking my data to:
<div class="col-lg-6 offset-lg-2">
<div class="cart_total">
<div>Cart total</div>
<div>Final info</div>
<div id="cartTotalOutput">
</div>
<div><input type="submit" class="button checkout_button"></div>
</div>
</div>
</div>
There's two issues here. Firstly add() is to add an element to a collection, not to attach an event handler. To do what you want use click() or on().
Secondly, price is only updated after the click event happens, yet your logic is attempting to read it immediately. To address this you need to put the console.log() line in that event handler. Try this:
var price = 0;
var $nextdayClass = $('.delivery1');
$nextdayClass.on('click', function() {
var nextday = $('#nextday').data('price');
price = nextday;
console.log(price);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="delivery1">Click me</button>
<div id="nextday" data-price="1.99">Next day: 1.99</div>
It's also worth noting that you should avoid the use of global variables where possible. A better pattern to use would be just retrieve the data attribute which holds the price where it's actually needed and remove the price variable completely.
It has nothing to do with scope.
Look at your code:
You get an element
You say that when you click the element price should be updated (well, you try to, you made a typo and called add instead of on)
You look at price
Presumably, at some point later, you click the element.
At this point price is updated.
You don't look at it again.
JavaScript does not time travel into the past and change price before you looked at it the first time.
The record of what the value was when you looked at it that is displayed in the console will not change.
If you want to log the value after you click on the element, you have to put the code that does the logging in the function that is called when you click on the element.
var price = 0;
var nextdayClass = $('.delivery1');
nextdayClass.on('click', function() {
var nextday = $('#nextday').data('price');
price = nextday; // The window object stuff is a waste of time
console.log("Clicked value", price);
});
console.log("Initial value", price);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="delivery1">5</button>
<span id=nextday data-price=5></span>
Try JQuery on() like this, also as I assume your element may be generated dynamically, try to bind the event handler to the body element/
var price = 0;
var nextdayClass = $('.delivery1');
$('body').on('click', nextdayClass, function() {
var nextday = $('#nextday').data('price');
window['price'] = nextday;
});
console.log(price); //Prints out 0
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);
});
I am trying to append some data in html table using jquery that is working fine but when the data is null or empty i have to append another div to that html table.
Am trying like this
$("#table").append(data.d[i].one!=""?
"<td id='divs'>
<input id="+ data.d[i].one +" type=" + "checkbox" + " class=" + "cbCheck" + ">
<label for="+ data.d[i].one +"></label>
</td>":"<div></div>");
but it is not working please help me how to fix this...
Never understand why somebody use this
$("#table").append(data.d[i].one!=""?
"<td id='divs'>
<input id="+ data.d[i].one +" type=" + "checkbox" + " class=" + "cbCheck" + ">
<label for="+ data.d[i].one +"></label>
</td>":"<div></div>");
Instead of this:
//class declaration
function YourTableCell(name, value) {
this.input = document.createElement('input');
this.input.value = value;
this.input.name = name;
this.label = document.createElement('label');
this.label.text = 'My Label';
this.container = document.createElement('td');
this.container.appendChild(this.input);
this.container.appendChild(this.label);
}
//application buisness logic
if(data.d[i].one != ''){
var cell = new YourTableCell(data.d[i].name, data.d[i].value);
$("#table").append(cell.container);
} else {
$("#table").append(document.createElement('div'));
}
Using this approach you can incapsulate table cell building inside of your class and make your code much more readable and reusable. Also, as I see now, you are trying to append td inside of something with id #table, and look like it is incorrect, because you should append td inside of tr.
Also, using this you can get references to all objects such as inputs and avoid of $('input, select, textarea') selectors.
You could use something like this,
var html = '<div></div>';
if(data.d[i].one) {
html = '<td id="divs"><input id="' + data.d[i].one + '" type="checkbox" class="cbCheck"><label for="' + data.d[i].one + '"></label></td>';
}
("#table").append(html);
You could use :
if( data.d ){
//Your code
}
That will check if data.d is NULL or empty string "".
If you want to check in every iteration use the index i :
if( data.d[i] ){
//Your code
}
Hope this helps.
Take a look to https://stackoverflow.com/a/5515349/4281779.
I am creating a table at run time using Jquery and binding the unique id to the checkbox.
$.getJSON('/api/Test/SelectionList' + '/' + ID)
.done(function (data) {
$.each(data, function (key, val) {
var myRow = $("<tr/>");
//$("<td> <input type='checkbox' ></input> </td>").text(val.IsActive).appendTo($(myRow));
var items = "";
items += '<input type="checkbox" id=' + val.FacilityID + ' ';
if (val.IsSelected) {
items += 'checked/>';
}
else {
items += '/>';
}
//$("<td/>").text(val.IsActive).appendTo($(myRow));
$("<td> " + items + "</td>").appendTo($(myRow));
$("<td/>").text(val.Facilityname).appendTo($(myRow));
$("<td/>").text(val.RegionName).appendTo($(myRow));
$("<td/>").appendTo($(myRow));
myRow.appendTo($("#Table"));
});
})
User can check and uncheck the checkboxex, On click of save i want to store the value of (table) all check boxex with checked/unchecked state with the ID.
I want to loop through the full table, and store the data as id#1 for checked box and id#0 for unchecked box in a same array.
I am bit new to jquery, So not getting the syntax. Please suggest.
Updated, here is the fiddle http://jsfiddle.net/MQQSv/1/
<table>
<tr>
<td>one</td>
<td>
<input type="checkbox" id='1' checked/></td>
</tr>
<tr>
<td>two</td>
<td>
<input type="checkbox" id='2' /></td>
</tr>
</table>
$('#save-btn').on('click', function() {
var output = []
$("table td input[type=checkbox]").each(function(){
id = $(this).attr("id");
output.push( id + "#" + ($(this).is(":checked") ? "1" : "0"))
})
console.log(JSON.stringify(output));
})
you can try this :
push id into two different array
$(document).ready(function() {
// bind click event to save-btn
$('#save-btn').on('click', function() {
// init two array
// (if you want to use var out of on's callback function, you need to do declaration outside)
var checkedList = [],
uncheckedList = [];
// push ckecked id into checkedList
$('input:checked').each(function() {
checkedList.push($(this).attr('id'));
});
// push unckecked id into uncheckedList
$('input').not(':checked').each(function() {
uncheckedList.push($(this).attr('id'));
});
});
});
I have one question. Is possible delete <span> element added with javascript append?
When i try remove added span then nothing happens.
Like this:
<script type="text/javascript">
$(document).ready(function(){
$('#SelectBoxData span').click(function(){
var StatusID = this.id;
var StatusIDSplit = StatusID.split("_");
var StatusText = $('#SelectBoxData #' + StatusID).text();
$("#SelectBox").append('<span id=' + StatusID + '>' + StatusText + '</span>');
$("#SelectBoxData #" + StatusID).remove();
InputValue = $("#StatusID").val();
if(InputValue == ""){
$("#StatusID").val(StatusIDSplit[1]);
}
else{
$("#StatusID").val($("#StatusID").val() + ',' + StatusIDSplit[1]);
}
});
$('#SelectBox span').click(function(){
var StatusID = this.id;
$("#SelectBox #" + StatusID).remove();
});
});
</script>
<div id="SelectBoxBG">
<div id="SelectBox"><div class="SelectBoxBtn"></div></div>
<div id="SelectBoxData">
<span id="StatusData_1">Admin</span>
<span id="StatusData_2">Editor</span>
<span id="StatusData_4">Test 1</span>
<span id="StatusData_6">Test 2</span>
</div>
<input type="hidden" id="StatusID" />
</div>
Please help me.
Thanks.
Yes, you can delete them. However, you can't add click event handlers to them before they exist. This code:
$('#SelectBox span').click(function(){
var StatusID = this.id;
$("#SelectBox #" + StatusID).remove();
});
will only add a click event handler to <span> elements inside of #SelectBox at the time the code is run (so, based on your provided HTML, zero elements). If you want the event handler to react to dynamically added elements then you need to use a technique called event delegation, using the .on() function:
$('#SelectBox').on('click', 'span', function() {
$(this).remove(); // equivalent to the code you had before
});