Jay wardan Jay wardan - 4 years ago 64
Javascript Question

Not getting min attribute value in given elements set

I've:

for(var k=0;k<10;k++){
$(eleid).after('<li class="pgs_li_cls" id="stpli_'+k+'" data-pos="'+k+'"><input type="button" value="'+k+'" class="stkpgmb" id="stkpgid_'+k+'" onclick="func_is(this);"></li>');
}

function func_is(ele){
var max = 0, min=0;
$('.pgs_li_cls').each(function() {
max = Math.max($(this).attr("data-pos"), max);
min = Math.min($(this).attr("data-pos"), min);
});
var an_id = ele.id;
an_id = an_id.substr(0, an_id.length-1);
$('#stpli_'+min).remove();
console.log(max+" "+min);
}


As you can see i'm creating
li
containing a button 10 times and which ever button is clicked function
func_is()
is called, So what happens is that when a button is clicked it retrieves the
li
which have the minimum
data-pos
and remove that.

The problem is that for the first time when a button is clicked it find the min result to be
0
and max result to be
10
which is great and then it removes the
li
with minimum
data-pos
.

but when I click another button the
min
value is still 0 as it suppose to be 1 even though
li data-pos 0
has been removed (in my browser inspect after first click can't find the
li
data-pos 0).

I would really appreciate is someone tell what am I doing wrong :)

Answer Source

That is because you are initializing min value to 0 in func_is function.

Try setting it to bigger value

function func_is(ele){
  var max = 0, min= 1000;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download