purple11111 purple11111 - 1 month ago 5
Javascript Question

how to use auto numbered class into click function

I have the following HTML on a webpage multiple times which is generated by PHP.

<a href="#" class="generate">generate</a><div class="selectArea selectBox"></div>


Now I use this code to give each div their own individual classes

$(document).ready(function() {
$(".selectArea").each(function(i) {
$(this).addClass("selectBox" + (i+1));
});
});


But now I need to change this:

$(".selectBox").html($select);


which is inside a click function

$(document).on('click', '.generate', function () {


So that it also works with (i+1).

what i try to achieve



The above code is part of a entire project. In this project I got a selectbox with options generated from several inputs. In the
.html
I add this selectbox to the div. But right now it is added to all the divs on the page instead of just one.

Answer

if the .generate element is right before .selectBox div, then instead of:

$(".selectBox").html($select);

use jQuery's .next():

$(this).next('.selectArea').html($select);
Comments