[英]How to reset a value to its original state if changed
If I change an inputs value and want to reset it back to the original value onClick of a link how can I accomplish that? 如果我更改输入值并希望将其重置回原始值onClick链接我该如何实现?
I can use .data() to grab and store the original value but I am not sure of the best way to restore it if needed. 我可以使用.data()来获取和存储原始值,但我不确定如果需要还原它的最佳方法。
HTML: HTML:
<input class="someClassName" type="text" value="100" />
<a href="#">Edit</a>
<a href="#">Reset</a>
This is how I think it would work... 这就是我认为它会起作用的方式......
In the HTML above, the input will be rendered with a value of "100". 在上面的HTML中,输入将使用值“100”呈现。 If I then click "edit" I can use .date() to store the original value (100). 如果我然后单击“编辑”,我可以使用.date()来存储原始值(100)。 I can then change the value of the input but if I wanted to reset the value back it's original state I would need to call the .data() info and use it to restore the value of the input. 然后,我可以更改输入的值,但如果我想将值重置为原始状态,我需要调用.data()信息并使用它来恢复输入的值。
How would I do that using jQuery? 我怎么用jQuery做到这一点?
using .data
is perfect for that. 使用.data
是完美的。 look no further 别再看了
update - with some code directions 更新 - 包含一些代码说明
Assuming you want to have this done for many input fields and not just one I am assuming each input+edit+reset are contained in a single parent 假设您希望为许多输入字段完成此操作而不仅仅是一个我假设每个输入+编辑+重置都包含在单个父项中
<div>
<input class="someClassName" type="text" value="100" />
<a class="EditLink" href="#">Edit</a>
<a class="ResetLink" href="#">Reset</a>
</div>
and in your init script block 并在您的init脚本块中
$(".EditLink").click(
function() {
$(this).parent().children("INPUT").data("val",
$(this).parent().children("INPUT").val());
});
$(".ResetLink").click(
function() {
$(this).parent().children("INPUT").val(
$(this).parent().children("INPUT").data("val"));
});
I didn't test it but it should work 我没有测试它,但它应该工作
I would recommend giving your input an id then reference that. 我建议给你的输入一个id然后引用它。
<input class="someClassName" id="theInput" type="text" value="100" />
<a href="#" id="Edit">Edit</a>
<a href="#" id="Reset">Reset</a>
<script type="text/javascript">
$(document).ready(function{
$("#Edit").click(function{
$("#theInput").data('originalValue',$("#theInput").val());
});
$("#Reset").click(function{
$("#theInput").val($("#theInput").data('originalValue'));
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.