0

I want to change the src of an image file. Tried the below using with the variable, but it actually doesnt change it. Where did I made a mistake on using variable ?

jquery

var p2begen = "416";
$("[id=i'" + p2begen + "']").attr("src", "check.png");

html

<img src="nocheck.png" id="i416" \>
2
  • you are forgetting the # in $("[id=#i'" + p2begen + "']") Commented Dec 17, 2015 at 15:18
  • With this code you are modifying id i'416', remove those '. Also, as answered by others, the correct way to select ID is with # $('#element_id') Commented Dec 17, 2015 at 15:33

3 Answers 3

3

To reference an id in jquery you need to add the #. See here in the jquery docs. It is important to note that ids must be unique, but you can use a class on as many elements as you like.

var p2begen = "416";
$("#i" + p2begen).attr("src", "check.png");

If you wish to use classes instead your code should look like this:

<img src="nocheck.png" class="i416" \>

var p2begen = "416";
$(".i" + p2begen).attr("src", "check.png");
Sign up to request clarification or add additional context in comments.

4 Comments

its an id not a class.
Here is the deal, I want this applied on all the divs that has the same id. So will that do this ?
You can only have one id... if you want to reference numerous elements by the same name you need to use a class name and then use . as opposed to #. there is a description here - ryanfait.com/articles/the-difference-between-ids-and-classes
Does the solution work if you change it to use a class?
1

add the # at the start.

var p2begen = "416";
$("#i" + p2begen).attr("src", "check.png");

if you want to stick with the attribute selector, use:-

var p2begen = "416";
$("[id='#i" + p2begen + "']").attr("src", "check.png");

by adding the # and moving the ' back 2 places.

Comments

1

The simplest way for doing that is to use selector for ids, and your selector will looks like this:

var p2begen = "416";
$('#i' + p2begen).attr("src", "check.png");

Comments

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.