繁体   English   中英

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

[英]Update input field with jQuery when .text(); changes

我正在将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/

您不能在div上放置change事件,更不用说字符串了。 您所描述的是MutationEvent,被认为是不好的做法(不再受支持)。 您可以在这里阅读有关内容: https : //developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events

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

尝试更换:

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

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

胡安的回答是正确的,我只想让你知道为什么。

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

没有name属性,这是您要求jQuery选择元素的依据。

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

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

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

要么

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

correctPrice是未格式化的,str带有美元符号和逗号。

正如一些答案所说,您不能将更改事件绑定到文本值。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM