views:

96

answers:

7

HTML:

<input type="text" id="priceperperson1" name="priceperperson1" />
<input type="text" name="personsvalue1" class="countme" readonly="readonly" />

JS:

jQuery(document).ready(function($) {
$('div.pricerow input.countme').each(function(){ 
var id = this.name.substr(this.name.length-1);
alert($('input#priceperperson'+id));
this.value = parseInt($('priceperperson'+id).value) * parseInt($('countpersons'+id).value); 
});
});

Shortened as possible. All I've in alert is "Object"... Value is NaN. I've tried to "parseInt" on id. I've tried:

$('[name=priceperperson'+id+']');
$('priceperperson'+id);

What I'm doing wrong?

+2  A: 

You should probably put the $ in the function definition.

I'm guessing it's causing the $ variable to be re-defined, in the function -- and not point to the jQuery's $() function anymore.


I'm thinking about this one :

jQuery(document).ready(function($) {

Try using, instead :

jQuery(document).ready(function() {
Pascal MARTIN
A: 

All I've in alert is "Object"... Value is NaN. I've tried to "parseInt"

Try giving a base to parseInt:

parseInt(variable, 10);
Sarfraz
+4  A: 

You are retrieving jQUery objects when you do the $(..)

To get the value (string) use the .val() method.

so

alert( $('input#priceperperson'+id).val() );
Gaby
A: 

There are some mistakes... to get the value of a jQuery object you must use .val() method, not .value.

Then, the parseInt() requires, as second parameter, the radix. Something like:

...
this.value = parseInt($('priceperperson'+id).val(), 10) * parseInt($('countpersons'+id).val(), 10); 
...
tanathos
+1  A: 

When you are looping through jquery objects, I believe you have to use:

$(this).attr('name'); instead of this.name

also, to call values from objects you have to use $.val() or $.attr('attributename');

// Shortcut for doc ready
$(function() 
{ 
 // Loop through values
 var id = $(this).attr('name');

 alert($('input#priceperperson' + id).val());
});
Jon
+1  A: 

Are you perhaps looking for .val()?

this.val(parseInt($('priceperperson'+id).val()));
BlueRaja - Danny Pflughoeft
A: 

your code may contain errors

your code id = lenght 1 OK if id lenght > 1 ?? possible exception

priceperperson1 to priceperperson_1

# option # proposal

<input type="text" id="priceperperson_1" name="priceperperson_1" /> // => use "_"
<input type="text" name="personsvalue_1" class="countme" readonly="readonly" />


jQuery(document).ready(function($) {
    $('div.pricerow input.countme').each(function(){ 
        var id = this.name.split("_")[1]; // => get array value 
        this.value = parseInt($('[name=priceperperson_'+id+']').value()) *parseInt($('[name=countpersons='+id+']').value()); 
    });
});
volkan er
Impossible - only 4 elements.
Misiur