0

I am trying to change the text of a label in JQuery, when that label is clicked.

This code works when I refer to the control ('ACCP') using its exact name:

$("label[for='ACCP']").text("the new text");

But I want to be able to refer to the control using a variable, not its exact name. This doesn't work:

$("label[for=' + this.id + ']").text("the new text");

I am quite sure the right control is behind this.id, because when I pop up a message to retrieve the id for the current control, it gives me the expected control name:

var ctrlName = this.id;
alert(ctrlName); 

-> correctly returns 'ACCP' in this case.

I am probably missing an obvious syntax error in my code, but I never do JQuery - my code is all copy-paste ;)

Thanks in advance for your precious help, JM

drWatson
  • 3
  • 2
  • 2
    If `$("label[for='ACCP']").text("the new text");` works, and `this.id` is `ACCP`, then your code should work, can you make a [MCVE] so we can see the error for ourselves? – CertainPerformance Feb 26 '20 at 08:08
  • maybe you need to close double quotes before adding the `...'"+ this.id +"' ...`? Because looks like a string – Zander Feb 26 '20 at 08:14
  • Thanks guys, for the quick replies! Cheshire, you nailed it. It was the double quotes indeed. This works: $("label[for='" + this.id + "']").text("the new text"); Thank you so much. I had been on this for 2 hours! – drWatson Feb 26 '20 at 08:17
  • You are welcome, sometimes the smallest things you don't think they would break the code, they do. Also, I don't know which Code editor you are using, but in most cases, the color of the code changes to indicate you that you are using strings, functions, etc... – Zander Feb 26 '20 at 08:20

2 Answers2

1

You need to close the double quotes: https://jsfiddle.net/gz61mdbf/

this.id = 'new_code'
$("label[for='" + this.id + "']").text("the new text");

You are doing a string into the for without closing them, that's why is not working for you.

Zander
  • 1,076
  • 1
  • 9
  • 23
  • Thanks guys, for the quick replies! Cheshire, you nailed it. It was the double quotes indeed. This works: $("label[for='" + this.id + "']").text("the new text"); Thank you so much. I had been on this for 2 hours! ... And now I just feel stupid ;)))) – drWatson Feb 26 '20 at 08:23
0

Have you tried $("label[for=" + $(this).id + "]").text("the new text");?

Like told in this link:

When using this, you can call DOM methods on it, but not jQuery methods. When using $(this), you can call jQuery methods on it, but not DOM methods.

Hope this can help you.

xKobalt
  • 1,498
  • 2
  • 13
  • 19
  • 1
    Hi xKobalt, thanks for your reply. I tried that, but that didn't seem to work for me. Thanks again – drWatson Feb 26 '20 at 08:43