2

jQuery not working with variable. the issue is with this line:

$('img[alt = id]').trigger("click");

if I change it to

$('img[alt = "6"]').trigger("click");

Everything works as expected. I just can't workout how to use a variable instead of a value within the quotes. I have tried putting id in single / double quotes with no luck. I'm sure it will be something obvious. Can anyone help.

This is the full code.

$(window).load(function () {
        // run code
       // $('img[alt ="6"]').trigger("click");
        var id = localStorage.getItem("CustomerID");
        $('img[alt = id]').trigger("click");
      //  window.alert(id);
    });

2 Answers 2

3

You can combine a string and use that instead:

$('img[alt = "' + 6 + '"]').trigger("click");

Here it is as a variable:

var id = 6;
$('img[alt = "' + id + '"]').trigger("click");

It's called string concatenation.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks mate. So simple when you know how. I will accept your answer once I can in few minutes.
I actually tried something similar. $('img[alt = ' + id + ']').trigger("click"); But I user it without the double quotes, I didn't realise they are needed as part of the statement.
1

Watch this

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Example:

$(`img[alt = "${id}"]`).trigger("click");

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.