将html字段值传递给JQuery

时间:2019-07-08 12:34:40

标签: jquery html

当尝试从HTML字段获取数据时,出现NaN错误。

如果在代码中添加了数字值,则在测试时查询将起作用,并且显示警报并显示返回的值。

<label>Monthly Cost</label>
<input type="number" name="pricepermonth" id="pricepermonth" class="form-control" >
<label>ProRata Cost</label>
<input type="text" name="remainingprice" id="remainingprice" class="form-control" >

var dt = new Date();  
month = dt.getMonth();
day   = dt.getDate();
year  = dt.getFullYear();


if(month == 11)
var nextMonth = new Date(year+1,0,1);
else
var nextMonth = new Date(year,month+1,1);

var today = new Date(year,month,day);

var remain = (nextMonth.getTime() - today.getTime())/1000;  
remain = remain/(60*60*24);
totaldays = day+remain;     
var priceperday = pricepermonth/totaldays;

var remainingprice = priceperday.toFixed(2)*remain;
alert(remainingprice);
return remainingprice;
}

var pricepermonth = $('#pricepermonth').data();
code(pricepermonth);

预期结果是,当将一个数字值添加到“每月成本”字段中时,这将触发查询,然后查询将在第二个字段中将其输出为按比例成本。

我收到的唯一错误消息是NaN(不是数字)错误。

1 个答案:

答案 0 :(得分:0)

由于使用的是输入内容,因此应使用.val()进行以下操作:

  

获取第一个匹配元素的value属性的内容

在您的代码中:

var pricepermonth = $('#pricepermonth').val();

.data()用于其他用途:

  

存储与匹配元素关联的任意数据或返回   命名数据存储区中第一个元素的值   匹配的元素。

换句话说,对于将各种对象,字符串,数组等与DOM元素关联起来很有用