Home > Net >  how to improve jquery javascript elements with equivalent id?
how to improve jquery javascript elements with equivalent id?

Time:04-30

i have 5 modules with big equal js code, but only INT ID is different.

How to simple access to get one-style javascript jquery for all modules with dynamical id? ok 3 int is num. CODE eg:

$("#super_mod_519").find('form');
$("#super_mod_345").find('form');
$("#super_mod_430").find('form');
$("#super_mod_632").find('form');
$("#super_mod_234").find('form');
$("#super_mod_713").find('form');

$("#super_mod_519 .button input").val('');
$("#super_mod_345 .button input").val('');
$("#super_mod_430 .button input").val('');
$("#super_mod_234 .button input").val('');
$("#super_mod_632 .button input").val('');
$("#super_mod_713 .button input").val('');

CodePudding user response:

If the ids are the key elements here then you could collect them in an array and simplify things this way:

const ids=[519,340,430,632,234,713];

ids.forEach(id=>
  $(`#super_mod_${id} form`) // some action ...
);

ids.forEach(id=>
  $(`#super_mod_${id} .button input`).val('')
);

(In order for the above snippet to work we still need some HTML and jQuery of course.)

If you want to perform the jQuery-based operations at the same time you can of course run them both in the same ids.forEach() loop.

CodePudding user response:

The jQuery selector below will select all elements that start with an id of "super_mod_".

$("*[id^='super_mod_']").find('form');
$("*[id^='super_mod_'] .button input").val('');
  • Related