FrenkyB FrenkyB - 15 days ago 7
Javascript Question

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?

Answer

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).