Bobernac Alexandru
Bobernac Alexandru

Reputation: 209

Pass a string as an id name into jQuery from an array javascript

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]]"

Upvotes: 0

Views: 362

Answers (1)

palaѕн
palaѕн

Reputation: 73896

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!

Upvotes: 1

Related Questions