elize elize - 6 months ago 11
Javascript Question

how can convert jquery code to functions?

I have multi html block with same code like this:

<div id="up1">
<input id="sub1" />
</div>


<div id="up2">
<input id="sub2" />
</div>

.
.
.

<div id="upn">
<input id="subn" />
</div>


for each html these block I have same jquery code (with own id for each of them)

like this:

$(document).on("change", "#up1",function() {
e.preventDefault();
... some code ...
}));

$(document).on("change", "#up2",function() {
e.preventDefault();
... some code ...
}));
.
.
.

$(document).on("change", "#upn",function() {
e.preventDefault();
... some code ...
}));


this is my qestion

how to avoid repeating code?..

maybe u suggest me I must use class instead id,But it's not my answer.I want use only id.

I must use id,not class... because I want print result (or send data) on it's block.

seems I must use a function, but how can I call them in a function?

for example is this valid?

function myfunction(id1,id2) {
$(document).on("change", "#up1",function() {
e.preventDefault();
... some code ...
}));

}


myfunction('up1','sub1');
myfunction('up2','sub2');
myfunction('up3','sub3');

Answer

Why don't you use multiple selectors:

$(document).on("change", "#up1, #up2, #upn", function() {
    e.preventDefault();
    ... some code ...
})); 

In this case if any of elements up1 ... upn is changed the event handler will be fired. Additionally you need to access the item that was changed by using $(this) instead of accessing it directly by ID.

To access the sub element you can use some other selector based on your parent element, for example:

$(document).on("change", "#up1, #up2, #upn", function() {
    e.preventDefault();
    var sub = $(this).find('input').eq(0);  // find first input element inside changed element
})); 

Or if it possible change your HTML structure not to use ID for sub items and use class instead:

<div id="up1">
   <input id="sub1" class="sub" />
</div>

In this case you can use class selector:

$(document).on("change", "#up1, #up2, #upn", function() {
    e.preventDefault();
    // find first element inside changed element that has class 'sub':
    var sub = $(this).find('.sub').eq(0);      
}));