简体   繁体   中英

jquery how to get input previous and new value

I am facing an issue in javascript. I want to get value of input field previous value and current value .

My Code:

 $(document).on('change', '#licensekey', function () { var prev = $(this).data('val'); //undefined var current = $(this).val(); console.log("Prev value " + prev); console.log("New value " + current); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <label> License Key</label> <input id='licensekey' type='text' class='input'>

what should i do? anyone help me.

You could store prev in a variable like so:

 var prev = null; $(document).on('change', '#licensekey', function () { var current = $(this).val(); console.log("Prev value " + prev); console.log("New value " + current); prev = current; });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <body> <label> License Key</label> <input id='licensekey' type='text' class='input'> </body>

You never set $(this).data('val', current) so there is no reason to expect it to change from undefined

 $(document).on('change', '#licensekey', function () { var prev = $(this).data('val'); //undefined first time only var current = $(this).val(); console.log("Prev value " + prev); console.log("New value " + current); // store current for next change $(this).data('val', current) });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <label> License Key</label> <input id='licensekey' type='text' class='input'>

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