简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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