0

I want to make a javascript that randomly takes a string from an array and uses it as a jQuery selector but I don't know how.

$(document).ready(function() {
    var x = Math.floor(Math.random() * 10 + 1);
    var array = ["img1", "img2", "img3", "img4", "img5", "img6", "img7", "img8", "img9", "img10", "img11"];
    $("id[name^=array[x]]").click(function() {
        var src1 = $("id[name^=array[x]]").attr("src");
        var src2 = $("#img").attr("src");
        if (src1 != src) {
            $("#img").attr("src", src1);
        }
    });
    $("id[name^=array[x]]").trigger("click");
})

It doesn't work if I write "id[name^=array[x]]", it says:

"Uncaught Error: Syntax error, unrecognized expression: id[name^=array[x]]"
1
  • "id[name^=" + array[x] + "]" Commented Aug 25, 2015 at 14:27

1 Answer 1

1

You can try like this:-

$(document).ready(function () {
    var x = Math.floor(Math.random() * 10 + 1);
    var array = ["img1", "img2", "img3", "img4", "img5", "img6", "img7", "img8", "img9", "img10", "img11"];
    var $id = $("[name^=" + array[x] + "]");
    console.log($id);
    $id.click(function () {
        var src1 = $id.attr("src");
        var src2 = $("#img").attr("src");
        if (src1 != src) {
            $("#img").attr("src", src1);
        }
    });
    $id.trigger("click");
});

EDIT:

Your selector is wrong here. So, if you want to select elements w/ id like img1, img2, etc. you need to use:-

var $id = $("[id^=" + array[x] + "]");

In case you want to get elements with name like img1, img2, etc. you need to use:-

var $name = $("[name^=" + array[x] + "]");

Please modify the code based on your requirements.

Hope this helps!

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

2 Comments

Problem solved, I wrote like this: var src = $("#"+array[x]).
@BobernacAlexandru Cool. If the img1 is just a id you can use it simply like that. Please do mark the answer as accepted to help other users too.

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.