1

So I have a question. It's probably simple, but I've tried so many things and can't seem to get it to work. If you can just quickly rewrite this in the correct syntax, that would be sooo awesome.

I need my javascript object to include a variable that's a counter that adds.


Here is my code that works.

$(div_1).droppable("option", "disabled", false);


Here is what i need to work.

var counter = 1;

$('div_' + counter).droppable("option", "disabled", false);

counter++;



Hopefully i explained this well enough...

Thank you so much!!

3 Answers 3

1

Interesting, this is how I would do it:

var counter=1;
$(window['div_' + counter]).droppable("option", "disabled", false);
counter++;

This assumes div_1 is a variable, as your question is written. By getting the element out of the window array, I avoid the nasty nasty eval.

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

3 Comments

This is completely counter to the purpose of a jQuery selector.
@Darthg8r please note how the question was written. 'div_1' is not a string selector, it is a variable that holds the selector/is a reference to a dom element. The OP needs a way to increment up through selectors/elements.
That worked!! Thank you so much Shad! Yeah, the only variable is the counter. The div_1 is a jQuery droppable selector. I have a whole bunch of droppables that the code needs to increment through and enable as the draggables are dropped. Thank you so much. I swear i had it written this way once, but just couldn't get it to work!
0

If div_x is the name of the element id, then:

var counter = 1;

$("#div_" + counter).droppable("option", "disabled", false);

counter++;

The # matches element id's, "." matches element classes. Simply "div" would match all divs on the page.

Comments

0

Your code should work. if you add a # before your string and you're targeting $('#div_1) (a div with id="div_1") Basiclly you can add a Number type variable to an string and result is string

var n = 1; // n is Number type
var hey = "hey "; // hey is an String type

console.log(hey + n); // returns "hey 1"
console.log(n + hey); // returns "1hey "

What I'm guessing is you declared the div_1 before like div_1 = $('#div1');. So if you pass "div_1" to your jQuery selector you will fail

1 Comment

Thanks for the answer! Plus i appreciate the javascript lesson. That is such a good thing to know! Thanks!

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.