使用jQuery更新输入字段.text();变化

时间:2014-05-08 01:20:40

标签: javascript jquery html

我正在将jQuery定价计算器与购物车集成。我想在.text();时更新一个隐藏字段。元素的值被改变。

这是我要更新的字段:

<input id="firewall-price" type="hidden" name="price" value="" />

从这里开始:

<div class="orderRow server firewall" contain="firewall" id="">
   <div class="quantity"><span></span></div>
   <div class="name">Firewall</div>
   <div class="price orderPrice">$0</div>
</div>

使用这个jQuery:

$(document).ready(function(){
   var price = $( ".firewall .price" ).text().substr(1);

   $(price).change(function(){
      $("input[name=firewall-price]").val(price);
   });
});

当数字发生变化时,我无法获得输入值[name = firewall-price]进行更新。我知道这样做有点奇怪,但我想从计算器中取出最终值并将它们发送到购物车。

以下是开发网站的链接:http://mindcentric.thelabelcreative.com/pricing_calculator/

5 个答案:

答案 0 :(得分:1)

您无法在div上添加更改事件,更不用说字符串了。你所描述的是一个MutationEvent,被认为是不好的做法(并且不再受支持)。您可以在此处阅读:https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events

相反,您需要挂钩更改该div值的事件/操作。

答案 1 :(得分:0)

尝试更换:

$("input[name=firewall-price]").val(price);

使用

$("#firewall-price").val(price);

答案 2 :(得分:0)

Juan的答案是对的,我会告诉你原因。

<input id="firewall-price" type="hidden" name="price" value="" />

没有name属性,这就是你要求jQuery选择你的元素。

要在不更改jQuery调用的情况下使代码正常工作,只需将name属性添加到输入字段即可。在html中,当元素提交给服务器时,name属性用于关联键/值对。

答案 3 :(得分:0)

Sahbeewah关于div的更改事件是正确的。如果您能够编辑main.js文件的内容,我建议您在lastPrice函数中添加逻辑。第451行之后添加

$('#firewall-price').val(correctPrice);

$('#firewall-price').val(str);

correctPrice未格式化,str具有美元符号和逗号。

答案 4 :(得分:0)

正如一些答案所说,你无法将更改事件绑定到文本值上。

然而,您可以将更改事件绑定到输入中,因此您需要反转逻辑,而不是更新$( ".firewall .price" ).text()而是更新输入,将更改事件绑定到输入$('#firewall-price')并设置text()元素的.price基于此。

$(document).ready(function(){
   var $priceTextElement = $( ".firewall .price" );
   var $priceTextInput = $('#firewall-price');

   $priceTextInput.on('change', function(){
      $priceTextElement.text('$'+$priceTextInput.val());
   });
});