JQuery: Get original input value

前端 未结 7 1942
面向向阳花
面向向阳花 2021-02-07 01:51

Is it possible to get the initial value of a form input field?

For example:

相关标签:
7条回答
  • 2021-02-07 02:25

    The HTML does change. Just that the browser's default view source tool always shows you the original source fetched from server. If you use something like Firebug, you'll be able to see the dynamic changes in HTML.

    One way of getting the initial value is by storing it in an additional attribute in addition to 'value'. For example, if you serve out your HTML like:

    <input type="text" name="one" value="one" origvalue="one" id="one" />
    

    You can always get back the original value by calling:

    $("#one").attr("origvalue");
    
    0 讨论(0)
  • 2021-02-07 02:37
    var initialVal = $('#one').val();
    alert(initialVal);
    $('#one').live("focusout", function() {
        var attribute = $("#one").attr("value");
        var value = $(this).val();
        var get = $(this).get(0).value;
        alert( "Attribute: " + attribute + "\n\nValue: " + value + "\n\ninit val: " + initialVal +"\n\nGet: " + get );
    });
    
    0 讨论(0)
  • 2021-02-07 02:38

    Input element got property called defaultValue that is storing the original value.

    To reach it via jQuery, just use .prop():

    var value = $(this).prop("defaultValue");
    

    Updated jsFiddle - after changing to "two", the above will return "one".

    0 讨论(0)
  • 2021-02-07 02:44

    Try this:

    $("#one")[0].defaultValue;
    
    0 讨论(0)
  • 2021-02-07 02:48
    Save the original_values @ document.ready.
    
    $(function(){
      var original_values = $.map($('form input'), function(input){ return $(input).val() });
    })
    
    0 讨论(0)
  • 2021-02-07 02:48

    You could try storing the value in data. For example:

    $('#one').data('val',$('#one').val());
    

    And then you could easily retrieve it later like this:

    console.log($('#one').data('val'));
    
    0 讨论(0)
提交回复
热议问题