Jquery get value from a dynamically generated input box? - javascript

I would like to extract the value from a dynamically generated inputbox which is inside a tr tag . But for some reason, I am facing error and I am getting undefined as the value. What could I be doing wrong? I am relatively new to Jquery. So,please I would like to know where I am doing wrong.
index.js
function dynamic_children() {
$(function () {
var no = $('#number_children').val()
$('#id_children-TOTAL_FORMS').val = no
children_added = $('#children_td_table tr').length
remaining = 4 - children_added
//determine if the no of children input are more than those left
if (no > remaining) {
//show alert that max children reached
$('max-children').show()
setTimeout(function () {
$('max-children').hide()
}, 3000);
} else if (no < children_added) {
no_to_remove = children_added - no
for (i = 0; i < no_to_remove; i++) {
$('#children_td_table').children().last().remove();
}
}
else {
for (var i = 0; i < remaining && i < no; i++) {
no_ = i + 1
$('#children_td_table')
.append($('<tr>')
.append('<td>' + no_ + '</td>')
.append($('<td>')
.append($('<input>')
.addClass('Input-text')
.attr('name', 'children-' + i + '-child_name')
.attr('id', 'children-' + i + '-child_name')
)
)
.append($('</td>'))
.append($('<td>')
.append($('<input>')
.addClass('Input-text')
.attr('name', 'children-' + i + '-child_dob')
.prop('type', 'date')
.prop('class', 'children-' + i + '-child_age')
.change(function () {
d = new Date($(this).val());
var before = moment($(d, 'YYYY-MM-DD'));
var age = moment().diff(d, 'years');
age_id_name = "#" + $(this).attr('class')
$(age_id_name).val(age);
})
))
.append($('</td>'))
.append($('<td>')
.append($('<input>')
.addClass('Input-text')
.attr('id', 'children-' + i + '-child_age')
.attr('name', 'child')
.prop('type', 'text')
))
.append($('</td>'))
)
.append($('</tr>'))
}
}
//
// for (var i = 0; i < no && i < 4; i++) {
//
//
// $("#delete_row").click(function () {
// if (i > 1) {
// $("#addr" + (i - 1)).html('');
// i--;
// }
// });
// }
})
}
function savechildinfo(){
var numofchildren = $("#number_children").val();
console.log("CHildrennumber",numofchildren);
var tr = $("#children_td_table").closest('tr');
for(var i =0;i<numofchildren;i++){
var c = "children-"+i+"-child_name";
var d = tr.find(c).val();
console.log("childrenname",d);
}
}

It is hard to understand and read you code, but I highlight your issue down below.
First no need to use closest just use $("#children_td_table") alone for var tr. Second you forget to add # for var c if you want to find it by ID so should use var c = "#children-" + i + "-child_name";
var i = 1;
var no_ = '123' // just for fix the error
$('#children_td_table')
.append($('<tr>')
.append('<td>' + no_ + '</td>')
.append($('<td>')
.append($('<input type="text"/>')
.addClass('Input-text')
.attr('name', 'children-' + i + '-child_name')
.attr('id', 'children-' + i + '-child_name')
.val('test') // remove this later
))
.append('</td>')
.append('</tr>')
);
savechildinfo(); // I execute this on load
function savechildinfo() {
var numofchildren = 2; // just for fix the error
console.log("CHildrennumber", numofchildren);
var tr = $("#children_td_table");
// remove closest
for (var i = 0; i < numofchildren; i++) {
var c = "#children-" + i + "-child_name";
// -----^ add #
var d = tr.find("#children-" + i + "-child_name").val();
console.log("childrenname", d);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="children_td_table"></table>

Related

Is there a way to have multiple inline configured ckeditors with single toolbar DOM element

An inline configured ckeditor has its toolbar attached to document body. Unless the user didn't focus the editor the toolbar is hidden. If we have multiple inline editors on same page, there will be the same number toolbar DOM elements attached to the body - each one with specific identifier. My question is, if there is a way to have a single toolbar DOM element for multiple inline ckeditors? I know (and I'm using in different context) the shared space plugin which does that, but the drawback is that one should provide an element to which the single toolabar would be attached. That's OK, but it is static and stays at the place where it's placed in the DOM order and I'd like it to be repositioned next to the currently focused editor.
Seems like I either have to use the default inline behavior or to use the shared space plugin and to reposition the single toolbar instance myself.
Any ideas on this issue or something I'm missing?
No, every CKEditor creates its own toolbar. But you can create your own plugin for this which is actually just displaying the toolbar of the active element. I have created one have a look. You do require to configure the your editor config too.
CKEDITOR.plugins.add('grouplabel', {
init : function(editor) {
function getCorrespondingName(no) {
var tempNo = 0;
for (var i = 0; i < editor.config.toolbar.length; i++) {
if (editor.config.toolbar[i].groupName != undefined) {
if (tempNo == no) {
return i;
}
tempNo++;
}
}
}
function toggleGroupDisplay(evt) {
if (evt.data.isMinimized) {
resetAllAbsolute();
$(this).find(".absoluteToolCont").toggleClass("displayNone");
} else {
$('.' + evt.data.grpID).each(function() {
toggleGroupDisplayInd(this)
});
}
}
function resetAllAbsolute() {
$(".absoluteToolCont").addClass("displayNone");
}
function toggleGroupDisplayInd(obj) {
var idM = $("#" + obj.id).parent().attr("id");
$("#" + idM + "> span").toggleClass("displayNone");
$("#" + idM).toggleClass("toggleMargin");
$("#groupLabel_" + idM).toggleClass("toggleMargin");
$("#groupLabelArrowBtn_" + idM).toggleClass("groupLabelArrowDown");
}
var openContainerArray = [ "CHARACTER", "TEXT ALIGN" ];
function createMainGroups() {
for (var j = 0; j < editor.toolbox.toolbars.length; j++) {
var grpId = editor.toolbox.toolbars[j].id;
var conNo = getCorrespondingName(j);
var isGroup = editor.config.toolbar[conNo].groupNR;
if (!isGroup) {
createMainGroup(conNo, grpId);
}
}
}
function createMainGroup(conNo, grpId) {
// console.log(conNo, grpId)
var name = editor.config.toolbar[conNo].groupName[0];
var className = editor.toolbar[conNo].name;
var name = editor.config.toolbar[conNo].groupName[0];
var elementDiv = groupLabelElementDiv(grpId, className);
var textDiv = "<div class='textGroupLabel'></div>";
var arrowDiv = "<div id='groupLabelArrowBtn_" + grpId
+ "' class='groupLabelArrowUp'></div>";
$("#" + grpId).addClass("editorGroup transitionType");
if (editor.config.showIconOnly) {
detachAndMakeAbsolute(grpId);
}
$("#" + grpId).prepend(elementDiv);
$("#groupLabel_" + grpId).append(textDiv);
if (!editor.config.showIconOnly) {
$("#groupLabel_" + grpId).append(arrowDiv);
}
addNameOrIcon(editor, name, grpId);
$(" #groupLabel_" + grpId).unbind("click").bind("click", {
grpID : "groupLabel_" + className,
isMinimized : editor.config.showIconOnly
}, toggleGroupDisplay);
var bool = false;
if (!editor.config.showIconOnly) {
for (var k = 0; k < openContainerArray.length; k++) {
if (name == openContainerArray[k]) {
bool = true;
}
}
}
showGroup(bool, grpId);
}
function detachAndMakeAbsolute(grpId) {
var divId = "absoluteToolCont_" + grpId
var absoluteDiv = "<div class='displayFlexAbsolute"
+ " absoluteToolCont' id='" + divId + "'></div>";
$("#" + grpId).prepend(absoluteDiv);
var detachedDiv = $("#" + grpId + "> span").detach();
// console.log(detachedDiv)
detachedDiv.appendTo("#" + divId);
resetAllAbsolute();
}
function showGroup(bool, grpId) {
if (!bool) {
$("#" + grpId + "> span").toggleClass("displayNone");
$("#" + grpId).toggleClass("toggleMargin");
$("#groupLabel_" + grpId).toggleClass("toggleMargin");
$("#groupLabelArrowBtn_" + grpId).toggleClass(
"groupLabelArrowDown");
}
}
function addNameOrIcon(editor, name, grpId) {
var groupName = $("#groupLabel_" + grpId + ">.textGroupLabel");
var divId = "absoluteToolCont_" + grpId
if (!editor.config.showIconOnly) {
groupName.text(name);
} else {
var clsName = name.replace(/ /g, '');
var detachedDiv = $("#" + divId).detach();
$("#groupLabel_" + grpId).prepend(detachedDiv);
groupName.html("<div class='iconToolbar " + clsName
+ "'></div>");
var overFlowRObj = "#cke_" + editor.name + " .cke_inner "
+ ".cke_top";
$(overFlowRObj).addClass("cke_top_overflow");
}
}
function groupLabelElementDiv(grpId, className) {
var elementDiv = "<div id='groupLabel_" + grpId
+ "' class='groupLabel transitionType groupLabel_"
+ className + "'></div>";
return elementDiv;
}
function createSubGroup() {
var loopVar = 0;
var divEle = '<div class="subGrpLabel textGroupLabel">' + "Font"
+ '</div>';
/*
* for (var k = 0; k < editor.toolbar.length; k++) { if
* (editor.toolbar[k] != "/") { for (var l = 0; l <
* editor.toolbar[k].items.length; l++) { if
* (editor.toolbar[k].items[l].type == "separator") { //
* console.log("sep") // $(editor.toolbar[k].items[l]).text("name"); } } } }
*/
}
editor.on('destroy', function() {
/* alert(this.name) */
var undoName = "undoRedoCont" + editor.name;
$("#" + undoName).remove();
});
editor.on('instanceReady', function() {
// console.log(previewSeen);
$("#universalPreloader").addClass("displayNone");
createMainGroups();
createSubGroup();
focusEvent();
undoRedoButtonSeprator();
});
function undoRedoButtonSeprator() {
var undoRedoContEle = "<div class='urcEle' id='undoRedoCont"
+ editor.name + "'></div>";
$("#undoRedoContSetParent").append(undoRedoContEle);
var ele = $("#" + editor.ui.instances.Undo._.id).detach();
$("#undoRedoCont" + editor.name).append(ele);
$(ele).addClass("cke_button_75px");
ele = $("#" + editor.ui.instances.Redo._.id).detach();
$("#undoRedoCont" + editor.name).append(ele);
$(ele).addClass("cke_button_75px");
$("#undoRedoCont" + editor.name).addClass("displayNone");
}
function focusEvent() {
var editorObj = /* parent. */$("#cke_wordcount_" + editor.name);
editorObj.addClass("displayFlexRelative").addClass("displayNone")
.addClass("vertical-align-middle").addClass(" flexHCenter")
.css("width", "160px");
var undoRedoCont = /* parent. */$("#undoRedoCont" + editor.name);
undoRedoCont.addClass("displayNone");
editor.on('focus', function(e) {
onFoucs(e);
});
editor.on('blur', function(e) {
onBlur(e);
});
}
function onBlur(e) {
var editorObj = /* parent. */$("#cke_wordcount_" + e.editor.name);
editorObj.addClass("displayNone");
$("#undoRedoCont" + editor.name).addClass("displayNone");
$("#dummyUNDOREDO").removeClass("displayNone");
resetAllAbsolute();
/*
* if (e.editor.config.customInline) {
* $("#toolbarEditorInline").addClass("displayNone"); }
*/
}
function onFoucs(e) {
var editorObj = /* parent. */$("#cke_wordcount_" + e.editor.name)
editorObj.removeClass("displayNone");
$("#undoRedoCont" + editor.name).removeClass("displayNone");
$("#dummyUNDOREDO").addClass("displayNone");
/*
* if (e.editor.config.customInline) {
* $("#toolbarEditorInline").removeClass("displayNone"); }
*/
}
CKEDITOR.document.appendStyleSheet(CKEDITOR.plugins
.getPath('grouplabel')
+ 'css/style.css');
}
});

How to process large jquery each loop without crashing browser(mainly firefox)

I made a javascript code to create some html element in parent iframe based on user selection from an iframe in a popup.
My code is given below.
The each loop may contain 50 to 150 iteration. Sometimes when I call function AddProcedures the Mozilla crashes during iteration, Is there any way to fix this issue or to reduce the browser load. I tried to put setTimeout after some code blocks but it didn't help.
I have also changed the for loop to jquery each, just to try if that helps.
var tot_codes = 0;
function doAddProcedure(thisVal,resolve){
var enc_id = $("#cpt_encounter").val();
var rowId = window.parent.$("[data-encounterBilled='"+ enc_id +"']").closest('tr').attr('id'); // table row ID
var recalc = parseInt(rowId.substring(rowId.indexOf('id-')+3));
var countval = $("#last_id").val();
//Load issue Fix
//Old code
//for (i = 0; i < document.cpt.elements.length; i++) {
//if (document.cpt.elements[i].type == "checkbox") {
//if (document.cpt.elements[i].checked == true) {
$('#cpt input:checkbox:checked').each(function(){
setTimeout(function() { }, 100);
var currentCodeMod = $(this).attr("data-codemod");
var currentCodeTypid = $(this).attr("data-codeTypeid");
if (currentCodeMod == null)
return;
tot_codes++;
var nextcntval = parseInt(countval) + 1;
var code_no = $(this).attr("id").replace("cpt_chkbx", "");
var Code = $("#codeVal" + code_no).val();
var just = $("#codeType" + code_no).val();
var categoryId = $("#codeType" + code_no).data("categoryid"); //Added to get category //Bug Fix
var Name = $("#cpttext" + code_no).val();
var codedisp = Code + ':' + Name;
var Modifier = '';
//if($("#modifier_setngs").val() == 1){
var Modifier1 = $("#modcpt1"+code_no).val() != '' ? $("#modcpt1"+code_no).val() + ":" : '';
var Modifier2 = $("#modcpt2"+code_no).val() != '' ? $("#modcpt2"+code_no).val() + ":" : '';
var Modifier3 = $("#modcpt3"+code_no).val() != '' ? $("#modcpt3"+code_no).val() + ":" : '';
var Modifier4 = $("#modcpt4"+code_no).val() != '' ? $("#modcpt4"+code_no).val() + ":" : '';
Modifier = Modifier1 + Modifier2 + Modifier3 + Modifier4;
//}
var codetableid = $("#code_tab_id" + code_no).val();
var j = countval; /* lineitem wise uniqid */
//var encounter = window.parent.$('#codetype-' + j).closest('tr.charge-entry-row').find('.expand-actions').attr('data-encounterid');
var encounter = enc_id;
var codeforarr = encounter + ':' + just + ':' + Code + '::' + Modifier;
window.parent.pushToArray(codeforarr);
var f = 0;
$(window.parent.$("#codetype-" + countval).parents().find('.inner-table .charge-entry-row')).each(function() {
//console.log($(this).find('.inputStringHidden').val() + '/' + codeforarr);
if ($(this).find('.inputStringHidden').val() == codeforarr) {
var exis_row_id = $(this).find('.inputStringHidden').attr('id').split('inputStringHidden-');
j = exis_row_id[1].toString();
f = 1;
$(this).find('.front_pay_codes_display').trigger('click');
}
});
if (f == 0) {
if (window.parent.document.getElementById('inputStringHidden-' + countval).value != '') {
window.parent.$("#codetype-" + countval).children().parent().parent().parent().siblings().find('.addnew-row').attr('data-rowadd', 'fromdb').trigger("click");
countval = parseInt(countval) + 1;
j = countval.toString();
}
window.parent.$("#add-" + countval).trigger("click");
window.parent.$("#codetype-" + (countval)).val(currentCodeTypid);
window.parent.$("#codetype-" + countval).trigger("change");
}
window.parent.document.getElementById('inputString' + j).value = codedisp;
window.parent.document.getElementById('category-' + j).value = categoryId; //Added to set category //Bug Fix
window.parent.document.getElementById('string_id' + j).value = Code;
window.parent.document.getElementById('string_value' + j).value = Name;
window.parent.document.getElementById('inputStringHidden-' + j).value = codeforarr;
window.parent.document.getElementById('codetableid-' + j).value = codetableid;
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.val-change-bit').val(1);
setTimeout(function() {}, 100);
window.parent.$("#suggestions" + j).hide();
window.parent.$("#inputString" + j).focus();
var uniqidHidden = window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.uniqid-hidden').val();
window.parent.$('#add-modifier' + j).parent().find('.displaymode-elem').text(Modifier);
//if($("#modifier_setngs").val() == 1){
if (f == 0) {
window.parent.$('#add-modifier' + j).parent().find('.displaymode-elem').addClass('area-hide');
}else{
window.parent.$('#add-modifier' + j).parent().find('.displaymode-elem').removeClass('area-hide');
}
window.parent.$('#modifiers' + uniqidHidden).val(Modifier);
arr = Modifier.split(':');
window.parent.$('#modifier-' + uniqidHidden + '-1').val(arr[0]);
window.parent.$('#modifier-' + uniqidHidden + '-2').val(arr[1]);
window.parent.$('#modifier-' + uniqidHidden + '-3').val(arr[2]);
window.parent.$('#modifier-' + uniqidHidden + '-4').val(arr[3]);
//}
var eclaimPlanActive = window.parent.$('#eclaimPlanActive').val();
var price = $("#cpt_price" + code_no).val();
var price_level = $("#pricelevelhidden" + code_no).val();
if (price == 0 || price == null)
price = 0;
window.parent.$('#price-' + j).val(price);
window.parent.$('#bill-pricelevel-' + j).val(price_level);
/** Charge Total **/
var chargeTotal = window.parent.$('#charge-total').text().replace(/[\s\,]/g, '').trim();
if (chargeTotal == '')
chargeTotal = parseFloat(0);
var tempChargeTotal = parseFloat(chargeTotal) + parseFloat(price);
window.parent.$('#charge-total span').html(tempChargeTotal);
/** End **/
var units = $("#cpt_units" + code_no).val(); //data[0]['units']
if (units == 0 || units == null)
units = 1;
window.parent.$('#qty-' + j).val(units);
var tax = 0;
var disc = 0;
setTimeout(function() { }, 100);
if (window.parent.$('#tax-' + j).length > 0)
tax = window.parent.$('#tax-' + j).val().replace(/[\s\,]/g, '');
if (window.parent.$('#discount-' + j).length > 0)
disc = window.parent.$('#discount-' + j).val().replace(/[\s\,]/g, '');
var amount = price * units;
amount = amount + ((amount * tax) / 100);
if (disc > 0) {
var p = price * units;
var dc = ((p * disc) / 100);
amount = amount - dc;
}
/** Discount Total **/
var disTotal = window.parent.$('#discount-total').text().replace(/[\s\,]/g, '').trim();
if (disTotal == '')
disTotal = parseFloat(0);
var tempDisTotal = parseFloat(disTotal) + parseFloat(dc);
if (isNaN(tempDisTotal) == true) {
tempDisTotal = '0.00';
}
window.parent.$('#discount-total').html(tempDisTotal);
/** End **/
if (!parseFloat(window.parent.$('#lineitempaid-' + j).val()))
window.parent.$('#lineitempaid-' + j).val('0.00');
window.parent.$('#total-' + j).val(amount);
window.parent.$('#remainder-' + j).val(amount);
window.parent.$('#hidremainder-' + j).val(amount);
//insurance and patient_share
if (eclaimPlanActive == '1') {
var codetableid = window.parent.$('#codetableid-' + j).val();
var parentRowVal = parseInt(window.parent.$('#codetableid-' + j).closest('tr').find('.row_value').attr('data-rowvalue')) - 1;
var insData1 = window.parent.$('tr#row-id-' + parentRowVal + ' .encounter').attr('data-insdata1');
window.parent.getBenefitCategoryOfCode(j, codetableid, insData1);
if (window.parent.$('#have-benefit').val() == '0') {
var insData2 = window.parent.$('tr#row-id-' + parentRowVal + ' .encounter').attr('data-insdata2');
window.parent.getBenefitCategoryOfCode(j, codetableid, insData2);
}
}
var passParams = '';
window.parent.calculate('qty-' + j, passParams);
//Updating the title
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.fi-searchitems').attr('data-original-title', codedisp);
if (f == 0) {
//Display DIv :: Relace with new values
var cloneLabel = window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.show_label').clone();
//In Edit Mode
if (cloneLabel.find('.displaymode-elem').length > 0) {
var $max_length = 16;
var trucncateCode = Name;
if (trucncateCode.length > $max_length)
trucncateCode = trucncateCode.substring(0, $max_length) + '...';
cloneLabel.find('.front_pay_codetype').text(just + ":");
cloneLabel.find('.front_pay_code').text(trucncateCode);
cloneLabel.find('.displaymode-elem').removeClass('area-hide');
cloneLabel.removeClass('area-hide');
cloneLabel.find("input[name='code_type']").val(just).attr('id', 'code_type-' + j);
cloneLabel.find("input[name='string_id']").val(Code).attr('id', 'string_id-' + j);
cloneLabel.find("input[name='string_value']").val(Name);
var dataType = $("#inputString" + j).closest('tr.charge-entry-row').find('.data_type').val();
if (dataType == "lab") {
var lab = $("select[name='lab_type']").find('option:selected').val();
if (cloneLabel.find("input[name='lab_type']").length > 0) {
cloneLabel.find("input[name='lab_type']").val(lab);
} else {
cloneLabel.append('<input type="hidden" name="lab_type" class="lab_type" value="' + lab + '">');
}
} else {
cloneLabel.find("input[name='lab_type']").remove();
}
setTimeout(function() { }, 100);
//Making the view
cloneLabel.removeClass('area-hide');
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.front_pay_codes_editelem').removeClass('area-show').addClass('area-hide');
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.show_label').replaceWith(cloneLabel);
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.show_autosuggest').html('');
}
window.parent.$("#codetype-" + countval).children().parent().parent().parent().siblings().find('.addnew-row').attr('data-rowadd', 'fromdb').trigger("click");
countval = nextcntval.toString();
}
else {
window.parent.$("#suggestions" + j).hide();
countval = countval.toString();
}
setTimeout(function() { }, 150);
});
window.parent.reCalculatePlanEncounterWise(recalc);
resolve("Success!");
}
function doAddPromise(thisVal){
return new Promise(function(resolve){
doAddProcedure(thisVal,resolve);
});
}
function AddProcedures(thisval)
{
$('#procedureSaveButton').text('Processing....');
// $('.fa-spinner').removeClass('hide');
top.ShowAjaxLoader('Loading..');
setTimeout(function(){
}, 2000);
//top.ShowAjaxLoader('Loading..');
setTimeout(function(){
$.when(doAddPromise(thisval)).done(function(){
if (tot_codes > 0) {
window.parent.phFrntpayClosePopup();
top.notification('Successfully added the procedures.');
//top.HideAjaxLoader('Loading..');
top.HideAjaxLoader();
$('body').removeClass('modal-open');
} else {
top.notification('Please select atleast one procedure.');
$('#procedureSaveButton').text('Add Procedures');
//$('.fa-spinner').addClass('hide');
top.HideAjaxLoader();
}
});
}, 10);
}

jQuery use dynamically created ID

I am trying to use dynamically created IDs in javascript function, but it's not working. I thought that prepending # to string id should work, but it's not.
Code:
var IterateCheckedDatesAndUncheckWithSameValue = function (elementNumber) {
idCheckBoxToCompare = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + elementNumber.toString();
if ($("'#" + idCheckBoxToCompare + "'").prop('checked') === false) {
return;
}
textBoxID = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + elementNumber.toString();
textBoxValue = $("'#" + textBoxID + "'").val();
for (i = 1; i < 8; i++) {
if (i !== elementNumber) {
idCheckBox = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + i.toString();
idInputBox = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + i.toString();
inputBoxValue = $("'#" + idInputBox + "'").val();
if ($("'#" + idCheckBox + "'").prop('checked') === true) {
if (inputBoxValue === textBoxValue) {
$("'#" + idCheckBox + "'").prop('checked', false);
}
}
}
}
}
I've tried to build same id as this is:
'#testid'
so usage would be:
$('#testid')
But it's not working. How to use properly dynamically created IDs?
Your code is look complicated with too many " and '. Also Javascript can concat string and number by just use +. No need to convert it to string first. So, I updated it to make it more readable.
Try this
var IterateCheckedDatesAndUncheckWithSameValue = function(elementNumber) {
idCheckBoxToCompare = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + elementNumber;
if ($('#' + idCheckBoxToCompare).prop('checked') === false) {
return;
}
textBoxID = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + elementNumber;
textBoxValue = $('#' + textBoxID).val();
for (i = 1; i < 8; i++) {
if (i !== elementNumber) {
idCheckBox = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + i;
idInputBox = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + i;
inputBoxValue = $('#' + idInputBox).val();
if ($('#' + idCheckBox).prop('checked') === true) {
if (inputBoxValue === textBoxValue) {
$('#' + idCheckBox).prop('checked', false);
}
}
console.log('#' + idCheckBox); //print here just to see the id results
}
}
}
ID in html can be only one element per page. So please make sure that the ID you generate from this method not match with other.
Jquery selector can read String variable.
So you can just do var id = "#test". Then put it like this $(id).
Or
var id = "test"; then $("#"+test).
Use this,
var IterateCheckedDatesAndUncheckWithSameValue = function (elementNumber) {
idCheckBoxToCompare = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + elementNumber.toString();
if ($("#" + idCheckBoxToCompare).prop('checked') === false) {
return;
}
textBoxID = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + elementNumber.toString();
textBoxValue = $("#" + textBoxID).val();
for (i = 1; i < 8; i++) {
if (i !== elementNumber) {
idCheckBox = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + i.toString();
idInputBox = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + i.toString();
inputBoxValue = $("#" + idInputBox).val();
if ($("#" + idCheckBox).prop('checked') === true) {
if (inputBoxValue === textBoxValue) {
$("#" + idCheckBox).prop('checked', false);
}
}
}
}
}
I face the same problem using Jquery .Try $(document).getElementbyId('myid'). Hope help.
Edit
Change :
$("#" + idCheckBoxToCompare) by $(document).getElementbyId(idCheckBoxToCompare)

jquery toggle only execute the first condition

This must be fairly simple for many of you. I wrote a function to select all checkboxes if user clicks on anchor tag (). However, on the first click the function select all checkboex but nothing happens when I click on the anchor tag again (it should deselect all the checkboxes again). Here is my JS function
function createFooterRowForRunningDoubles(trClassName, colspanNumber, mainTable, table, i) {
var mainTableId = $.data(mainTable, 'BetTableData').tableId;
var tr = $('<tr/>')
.addClass(trClassName)
.appendTo(table)
.append($('<td colspan="' + colspanNumber + '"/>'))
.append($('<td />')
.append($('<a id="fieldSelectAll"/>')
.html(field)
.click(function() {
var els = document.getElementsByName(mainTableId + "_select" + i);
for (var j = 0; j < els.length; j++) {
if ($("#fieldSelectAll").toggle()) {
els[j].checked = true;
}
}
})) )
}
Edit 1:
So if I remove the anchor tag and replacing with a select all check box it works if I modify my function as follow:
function createFooterRowForRunningDoubles(trClassName, colspanNumber, mainTable, table, i) {
var mainTableId = $.data(mainTable, 'BetTableData').tableId;
// Create row with checkbox
var tr = $('<tr/>')
.addClass(trClassName)
.appendTo(table)
.append($('<td colspan="' + colspanNumber + '"/>'))
// Create checkbox
.append($('<td/>')
.html(field)
.append($('<input type="checkbox" id="' + mainTableId + '_select' + i + '"/>'))
.click(function () {
var els = document.getElementsByName(mainTableId + "_select" + i);
for (var j = 0; j < els.length; j++) {
if ($("#" + mainTableId + "_select" + i).is(':checked')) {
els[j].checked = true;
} else els[j].checked = false;
}
}))
}
However, instead of using a 'checkall' checkbox, I simply need to toggle the checkall thing on anchor tag click. If that makes senses?
Use a variable to keep track of the state:
function createFooterRowForRunningDoubles(trClassName, colspanNumber, mainTable, table, i) {
var mainTableId = $.data(mainTable, 'BetTableData').tableId;
var allChecked = false;
var tr = $('<tr/>')
.addClass(trClassName)
.appendTo(table)
.append($('<td colspan="' + colspanNumber + '"/>'))
.append($('<td />')
.append($('<a id="fieldSelectAll"/>')
.html(field)
.click(function() {
var els = document.getElementsByName(mainTableId + "_select" + i);
allChecked = !allChecked;
for (var j = 0; j < els.length; j++) {
els[j].checked = allChecked;
}
})) )
}

JQuery click function not working after removing and adding back elements

this is my click function
$('.cal table tbody td').on('click', function () {
if($(this).hasClass('available'))
{
alert('asd');
}
});
the problem i am having is that after i have switched to the next or previous month, my clicking function on the calendar does not work.
For example in my JSFIDDLE, if u move to the previous month and then move back to the current month and do the click function, it wouldn't work anymore.
EDIT: I'm using an external library called date.js, check out my jsfiddle for a clearer idea of what is going on.
EDIT 2: updated jsfiddle link
jsfiddle
Use this
$(document).on('click','.cal table tbody td', function () {
if ($(this).hasClass('available')) {
alert('asd');
}
});
instead of this
$('.cal table tbody td').on('click', function () {
if ($(this).hasClass('available')) {
alert('asd');
}
});
Former is the correct replacement for delegate
one thing I notice immediately is that when you do things like:
$('#calendar tbody').append('<tr id = row'+i+'></tr>');
you need to remember that when you want to give an ID to an element the 'value' portion of the ID should be enclosed in quotations.
So you need to escape the string to include them so your browser can interpret the html properly.
ie
$('#calendar tbody').append('<tr id = \"row'+i+'\"></tr>');
that way your output looks like:
<tr id="rowx"></tr>
instead of:
<tr id=rowx></tr>
Your previous and next event handlers are recreating the DOM elements used for rendering the calendar. However, your click handler is only only attached to the elements that exist in the DOM at the time that handler is registered. The documentation of on() states:
Event handlers are bound only to the currently selected elements; they
must exist on the page at the time your code makes the call to .on()
You'll probably need to re-register that click handler as part of your calendarInit() function after the new rows in the calendar - the new elements - have been rendered.
You may view a working version here. Or take a look at the updated jQuery below.
var firstday = new Date();
var lastday = new Date();
var calendarmonth = new Date();
var CCheck;
$(document).ready(function () {
Date.today();
firstday.setMonth(Date.today().getMonth(), 1);
lastday.setMonth(Date.today().getMonth() + 1, 0);
calendarmonth.setMonth(Date.today().getMonth());
calendarInit();
$('#calendar-prev').on('click', function () {
if (CCheck > 35) {
//render 6 rows
for (i = 1; i < 7; i++) {
$('#row' + i).remove();
}
} else {
//render 5 rows
for (i = 1; i < 6; i++) {
$('#row' + i).remove();
}
}
$("#month").empty();
calendarmonth.addMonths(-1);
firstday.addMonths(-1);
lastday.setMonth(firstday.getMonth() + 1, 0);
calendarInit();
});
$('#calendar-next').on('click', function () {
if (CCheck > 35) {
//render 6 rows
for (i = 1; i < 7; i++) {
$('#row' + i).remove();
}
} else {
//render 5 rows
for (i = 1; i < 6; i++) {
$('#row' + i).remove();
}
}
$("#month").empty();
calendarmonth.addMonths(1);
firstday.addMonths(1);
lastday.setMonth(firstday.getMonth() + 1, 0);
calendarInit();
});
addRemoveClickTrigger();
});
function calendarInit() {
CCheck = lastday.getDate() + firstday.getDay();
var i;
var colNo;
var a = 1;
var days = new Array();
$("#month").append("Month: " + calendarmonth.toString("MMMM, yyyy"));
if (CCheck > 35) {
//render 6 rows
for (i = 1; i < 7; i++) {
$('#calendar tbody').append('<tr id = row' + i + '></tr>');
colNo = a + 6;
for (a; a <= colNo; a++) {
var datenum = a - firstday.getDay();
if (datenum < 1) {
$('#row' + i).append('<td></td>');
} else if (datenum > lastday.getDate()) {
$('#row' + i).append('<td></td>');
} else {
$('#row' + i).append('<td id = Y' + calendarmonth.getFullYear() + 'M' + calendarmonth.getMonth() + 'Day' + datenum + '>' + datenum + '</td>');
days[datenum] = new Date();
days[datenum].set({
month: calendarmonth.getMonth(),
day: datenum,
year: calendarmonth.getFullYear()
});
}
}
}
} else {
//render 5 rows
for (i = 1; i < 6; i++) {
$('#calendar tbody').append('<tr id = row' + i + '></tr>');
colNo = a + 6;
for (a; a <= colNo; a++) {
var datenum = a - firstday.getDay();
if (datenum < 1) {
$('#row' + i).append('<td></td>');
} else if (datenum > lastday.getDate()) {
$('#row' + i).append('<td></td>');
} else {
$('#row' + i).append('<td id = Y' + calendarmonth.getFullYear() + 'M' + calendarmonth.getMonth() + 'Day' + datenum + '>' + datenum + '</td>');
days[datenum] = new Date();
days[datenum].set({
month: calendarmonth.getMonth(),
day: datenum,
year: calendarmonth.getFullYear()
});
}
}
}
}
/*alert(Date.today().getMonth());
alert(calendarmonth.getMonth());*/
if (Date.today().getMonth() == calendarmonth.getMonth() && Date.today().getFullYear() == calendarmonth.getFullYear()) {
for (i = 1; i <= lastday.getDate(); i++) //Date highlight
{
if (Date.today().getDate() == i) //highlight today's date
{
$('#Y' + calendarmonth.getFullYear() + 'M' + calendarmonth.getMonth() + 'Day' + i).addClass("today");
} else if (Date.today().getDate() > i) //highlight unavailable dates
{
$('#Y' + calendarmonth.getFullYear() + 'M' + calendarmonth.getMonth() + 'Day' + i).addClass("unavailable");
} else if (Date.today().getDate() < i) {
$('#Y' + calendarmonth.getFullYear() + 'M' + calendarmonth.getMonth() + 'Day' + i).addClass("available");
}
}
} else if (Date.today() > calendarmonth) {
for (i = 1; i <= lastday.getDate(); i++) //Highlight dates before today to unavailable
{
$('#Y' + calendarmonth.getFullYear() + 'M' + calendarmonth.getMonth() + 'Day' + i).addClass("unavailable");
}
} else {
for (i = 1; i <= lastday.getDate(); i++) //Condition highlighting
{
$('#Y' + calendarmonth.getFullYear() + 'M' + calendarmonth.getMonth() + 'Day' + i).addClass("available");
if (days[i].getDay() == 0 || days[i].getDay() == 6) // set weekends to unavailable
{
$('#Y' + calendarmonth.getFullYear() + 'M' + calendarmonth.getMonth() + 'Day' + i).removeClass("available");
$('#Y' + calendarmonth.getFullYear() + 'M' + calendarmonth.getMonth() + 'Day' + i).addClass("unavailable");
}
}
}
addRemoveClickTrigger();
} //calendarInit()
function addRemoveClickTrigger()
{
$('.cal table tbody td').off();
$('.cal table tbody td').on({
'click':
function ()
{
alert(jQuery(this).prop('class'));
if ($(this).hasClass('available'))
{
alert('asd');
}
}
});
} //addRemoveClickTrigger()
I hope this helps.

Categories

Resources