not able to pass dynamic div id by for loop

383 views Asked by At

i have dynamic id that are store in input field when i tried to res[i] it will give me error.i tried by javascript but no success. getting this error

TypeError: $(...) is null


newprice = $("#"+res[i]).value();

form input

<input type="hidden" id="customprice" value="select_91,select_92,select_93" />




    <select  id="select_91" ><option value="">-- Vælg venligst --</option><option value="287" price="0" >1 pose  </option><option value="288" price="50" selected>2 poser  +DKK 50,00</option></select> 

<select  id="select_92" ><option value="">-- Vælg venligst --</option><option value="287" price="0" >1 pose  </option><option value="288" price="50" selected>2 poser  +DKK 50,00</option></select>  

<select  id="select_93" ><option value="">-- Vælg venligst --</option><option value="287" price="0" >1 pose  </option><option value="288" price="50" selected>2 poser  +DKK 50,00</option></select>   

my code is

customprice = $('customprice').value;
res = customprice.split(",");
price = 0;
alert(res.length);
for (i = 0; i < res.length; i++) {
    alert(res[i]);
     newprice = $("#"+res[i]).value();
    price = price + parseFloat(newprice);
}
1

There are 1 answers

3
Geek Num 88 On BEST ANSWER

If this is PrototypeJS then your error is the $('#<elementid>'), as the $() method takes an id not a CSS selector.

So IF this is PrototypeJS heres how to fix your problem and improve/simplify it a bit as well

Given your HTML above

customprice = $('customprice').value;
res = customprice.split(",");
price = 0;

res.each(function(item){
    price += parseFloat($F(item));
});

You could also chain these together like this

var price = 0;
$F('customprice').split(',').each(function(item){
    price += parseFloat($F(item));
});

** The $F() method returns the value of the passed id so essentially

$('<elementid>').value === $F('<elementid>')

EDIT

to get the price attribute of the selected option element

var price = 0;
$F('customprice').split(',').each(function(item){

    var optionprice = $(item).options[$(item).selectedIndex].readAttribute('price');

    price += parseFloat(optionprice);

    //this way might also work but the above will work
    var option1price = $(item).down('option[selected]').readAttribute('price');


});