开发者

Noob jQuery "$" function return question

开发者 https://www.devze.com 2023-01-07 04:57 出处:网络
HTML: <input type=\"text\" id=\"priceperperson1\" name=\"priceperperson1\" /> <input type=\"text\" name=\"personsvalue1\" class=\"countme\" readonly=\"readonly\" />

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开发者_如何学Go($('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?


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

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

so

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


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() {


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());
});


Are you perhaps looking for .val()?

this.val(parseInt($('priceperperson'+id).val()));


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

Try giving a base to parseInt:

parseInt(variable, 10);


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); 
...


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()); 
    });
});
0

精彩评论

暂无评论...
验证码 换一张
取 消