0

I've got an html input text element created like this in C#:

boxIndex1 = new TextBox()
{
    CssClass = "dplatypus-webform-field-input indexcell",
    Width = TEXTBOX_WIDTH,
    ID = "boxIndex1foapalrow2"
};

...and this jQuery to respond to the blur event of "boxIndex1foapalrow2" and its cousins ("boxIndex2foapalrow3", "boxIndex3foapalrow4", etc.):

$(document).on("blur", '.indexcell', function (e) {
    var $currentindexcell = $(this);
    if ($currentindexcell == $('[id$=boxIndex1foapalrow2]')) {
        alert('index cell 1 exited'); // testing
    }
});

I stepped through it, and the element assigned to $currentindexcell when I tab out of "boxIndex1foapalrow2" seems to be what I'm expecting:

<input name="ctl00$ctl24$g_5f3fedca_19f7_4bc3_b84e_efbef0c48a33$ctl00$boxIndex1foapalrow2" type="text" id="ctl00_ctl24_g_5f3fedca_19f7_4bc3_b84e_efbef0c48a33_ctl00_boxIndex1foapalrow2" class="dplatypus-webform-field-input indexcell" style="width:88px;">

...but the alert is not showing/the if condition equates to false. Why? It seems to me that the value of $currentindexcell in this instance does equal $('[id$=boxIndex1foapalrow2]'), but why doesn't it seem that way to the Javascript execution engine?

gilly3
  • 87,962
  • 25
  • 144
  • 176
B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862
  • http://stackoverflow.com/questions/201183/how-to-determine-equality-for-two-javascript-objects – Alex W Aug 10 '15 at 18:38
  • 2
    While [How to determine equality for two JavaScript objects?](http://stackoverflow.com/questions/201183/how-to-determine-equality-for-two-javascript-objects) is helpful for understanding the language-level issue of object equality, the jQuery-specific solution here is certainly to use `.is()`, which is not covered in that non-jQuery question. – apsillers Aug 10 '15 at 18:49

1 Answers1

5

Two jQuery objects that contain the same set of elements are not equal. To test whether your jQuery object matches a selector, use .is():

if ($currentindexcell.is('[id$=boxIndex1foapalrow2]')) {

If you really wanted to check for equality, you should compare the actual elements (not the jQuery objects that hold them):

if (this == $('[id$=boxIndex1foapalrow2]')[0]) {
gilly3
  • 87,962
  • 25
  • 144
  • 176