0
$('#form').find('input').focus(function(){
  var a = $(this).attr(id);
  $(a+'Help').addClass('elementHelp');
});

I am trying to make a short code to target all the input elements inside a specific form. Whenever any input element is in focus, get it's id and change the font color of another element(if it exists) whose id is the concatenation of the input element's id followed by the word "Help".

I could make a function for this but I don't want the HTML guy to call it. I just want that he includes the script and it works. I have explained him the naming convention.

All that said the above code does not work. Can anyone please help me solve this.

Thanks a lot.

Also tell me if I am horribly wrong in doing it this way, even though I have been ordered to do so.

1 Answer 1

4

id (the variable) is undefined here...it needs to be a string to use with .attr(), like this:

$(this).attr("id");

...but the much simpler way is using the already-present DOM property .id, like this:

$('#form').find('input').focus(function(){
  $('#'+this.id+'Help').addClass('elementHelp');
});
Sign up to request clarification or add additional context in comments.

2 Comments

I understand what you did but I don't know why it doesn't work. It's probably something really stupid I am doing. Could you take a look at this and tell me what's wrong: jsfiddle.net/PVP2j/3
@Aayush - doh, my fault, you need the # prefix for the ID selector: jsfiddle.net/nick_craver/PVP2j/4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.