Make JS Functions More Efficient and Dynamic

I have these 3 functions currently used in the html page:

$('#windowPanel1:first-child').children('div:eq(0)').click(function(){
    $('#edit1').val("1");
});
$('#windowPanel1:first-child').children('div:eq(1)').click(function(){
   $('#edit1').val("2");
});
$('#windowPanel1:first-child').children('div:eq(2)').click(function(){
    $('#edit1').val("3");
});

I would like to have one function that covers all these functions. What would be the most efficient way? Thank!

+4
source share
1 answer

Bind an event to all elements of a direct divelement stream #windowPanel1:first-child. Use index()to get the index of the clicked item. Returned indexis an index based on a zero value.

$('#windowPanel1:first-child > div').click(function() {
    $('#edit1').val($(this).index() + 1);
});

> direct child / child selector that will return the same elements as .children('div').

+6
source

Source: https://habr.com/ru/post/1658419/


All Articles