开发者

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?

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.

HTML:

<input class="someClassName" type="text" value="100" /> 
<a href="#">Edit</a>
<a href="#">Reset</a>

This is how I think it woul开发者_开发问答d work...

In the HTML above, the input will be rendered with a value of "100". If I then click "edit" I can use .date() to store the original value (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.

How would I do that using jQuery?


using .data is perfect for that. 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

$(".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.

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜