on() to watch changes in input - javascript

$("#myTextBox").on("change paste keyup", function() {
alert($(this).val());
});
How can I compare the new value inserted by the user and the current value that already existed in the input?

This is where you can use a closure:
$("#myTextBox").on("change paste keyup", (function() {
var previousValue = $("#myTextBox").val();
return function() {
var newValue = $(this).val();
alert('Was ' + previousValue + " and now it's " + newValue);
previousValue = newValue;
};
})());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="myTextBox" value="abc" />
The reason for the slightly convoluted closure: it creates a variable called previousValue that has a lifetime greater than the handler function, but yet can only be accessed by this handler function. You are guaranteed not to have naming collisions with other parts of your code.

You can save the previous value on the element itself and get it when the value changes.
$("#myTextBox").on("change paste keyup", function() {
// Get previous and current value
var prevValue = $(this).data('value'),
currValue = $(this).val();
console.log(prevValue + ' === ' + currValue);
// Update the prevValue
$(this).data('value', currValue);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input id="myTextBox" type="text" />

Weirdly, the input's value attribute is not actually updated when its value is changed. Therefore you can simply compare the .val() to the attr("value") and update the attr("value") after a change is made:
E.G:
$("#myTextBox").on("change paste keyup", function() {
alert($(this).attr("value")+" vs "+$(this).val());
$(this).attr("value",$(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="myTextBox" value="abc" />

Basically you can Save any value in JavaScript you can Save or Keep the previous data in 3 common ways:
Make a Variable and set to the value before it changes
Push to an Array
Add it to an Object as a Value
etc.
The best way you do it is using Variable, so something like this:
var previousValue = $ (this).val ();
and access it after...
$("#myTextBox").on("change paste keyup", function () {
var preValue = $(this).val();
return function () {
var newValue = $(this).val();
consol.log('preValue: ' + preValue + 'newValue: ' + newValue);
preValue = newValue;
};
});
The return happens after, so it works likes a Callback, basically it happens after and this way you can save both Variables...

Related

How can we get val from keyup in jquery

i want give val from keyup in jquery
my code is :
var vartest;
$( ".target" ).keyup(function() {
vartest= this.value;
console.log('in func:' + vartest);
});
console.log('out of func:' + vartest);
but vartest is undefined
Your function triggers only once your Element receives an event.
At the time you were calling vartest (outside of your function) its value is still undefined because the event (that actually attaches a value) will trigger at a later time.
Create a function getTargetsValues and call that function when needed.
Instead of "keyup" you might eventually listen for the "input" event:
// Cache your elements
const $targets = $(".target");
// Use this function to get an Array of inputs .target values
function getTargetsValues () {
return $targets.get().map(el => el.value);
}
$targets.on("input", function() {
console.log('in func: ' + getTargetsValues());
});
console.log('out of func: ' + getTargetsValues());
<input class="target" type="text" value="1. target">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
I’m not sure if this is what you need, but if you want to get value of input where event happened, you should take it from event target:
$(‘.target’).keyup(e => {
vartest = e.target.value;
});

How to preserve old input text value after the change in Javascript? [duplicate]

I have an input text in jQuery I want to know if it possible to get the value of that input text(type=number and type=text) before the onchange happens and also get the value of the same input input text after the onchange happens. This is using jQuery.
What I tried:
I tried saving the value on variable then call that value inside onchange but I am getting a blank value.
The simplest way is to save the original value using data() when the element gets focus. Here is a really basic example:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/e4ovx435/
$('input').on('focusin', function(){
console.log("Saving value " + $(this).val());
$(this).data('val', $(this).val());
});
$('input').on('change', function(){
var prev = $(this).data('val');
var current = $(this).val();
console.log("Prev value " + prev);
console.log("New value " + current);
});
Better to use Delegated Event Handlers
Note: it is generally more efficient to use a delegated event handler when there can be multiple matching elements. This way only a single handler is added (smaller overhead and faster initialisation) and any speed difference at event time is negligible.
Here is the same example using delegated events connected to document:
$(document).on('focusin', 'input', function(){
console.log("Saving value " + $(this).val());
$(this).data('val', $(this).val());
}).on('change','input', function(){
var prev = $(this).data('val');
var current = $(this).val();
console.log("Prev value " + prev);
console.log("New value " + current);
});
JsFiddle: http://jsfiddle.net/TrueBlueAussie/e4ovx435/65/
Delegated events work by listening for an event (focusin, change etc) on an ancestor element (document* in this case), then applying the jQuery filter (input) to only the elements in the bubble chain then applying the function to only those matching elements that caused the event.
*Note: A a general rule, use document as the default for delegated events and not body. body has a bug, to do with styling, that can cause it to not get bubbled mouse events. Also document always exists so you can attach to it outside of a DOM ready handler :)
Definitely you will need to store old value manually, depending on what moment you are interested (before focusing, from last change).
Initial value can be taken from defaultValue property:
function onChange() {
var oldValue = this.defaultValue;
var newValue = this.value;
}
Value before focusing can be taken as shown in Gone Coding's answer. But you have to keep in mind that value can be changed without focusing.
Just put the initial value into a data attribute when you create the textbox, eg
HTML
<input id="my-textbox" type="text" data-initial-value="6" value="6" />
JQuery
$("#my-textbox").change(function () {
var oldValue = $(this).attr("data-initial-value");
var newValue = $(this).val();
});
I have found a solution that works even with "Select2" plugin:
function functionName() {
$('html').on('change', 'select.some-class', function() {
var newValue = $(this).val();
var oldValue = $(this).attr('data-val');
if ( $.isNumeric(oldValue) ) { // or another condition
// do something
}
$(this).attr('data-val', newValue);
});
$('select.some-class').trigger('change');
}
I found this question today, but I'm not sure why was this made so complicated rather than implementing it simply like:
var input = $('#target');
var inputVal = input.val();
input.on('change', function() {
console.log('Current Value: ', $(this).val());
console.log('Old Value: ', inputVal);
inputVal = $(this).val();
});
If you want to target multiple inputs then, use each function:
$('input').each(function() {
var inputVal = $(this).val();
$(this).on('change', function() {
console.log('Current Value: ',$(this).val());
console.log('Old Value: ', inputVal);
inputVal = $(this).val();
});
my solution is here
function getVal() {
var $numInput = $('input');
var $inputArr = [];
for(let i=0; i < $numInput.length ; i++ )
$inputArr[$numInput[i].name] = $numInput[i].value;
return $inputArr;
}
var $inNum = getVal();
$('input').on('change', function() {
// inNum is last Val
$inNum = getVal();
// in here we update value of input
let $val = this.value;
});
The upvoted solution works for some situations but is not the ideal solution. The solution Bhojendra Rauniyar provided will only work in certain scenarios. The var inputVal will always remain the same, so changing the input multiple times would break the function.
The function may also break when using focus, because of the ▲▼ (up/down) spinner on html number input. That is why J.T. Taylor has the best solution. By adding a data attribute you can avoid these problems:
<input id="my-textbox" type="text" data-initial-value="6" value="6" />
If you only need a current value and above options don't work, you can use it this way.
$('#input').on('change', () => {
const current = document.getElementById('input').value;
}
My business aim was removing classes form previous input and add it to a new one.
In this case there was simple solution: remove classes from all inputs before add
<div>
<input type="radio" checked><b class="darkred">Value1</b>
<input type="radio"><b>Value2</b>
<input type="radio"><b>Value3</b>
</div>
and
$('input[type="radio"]').on('change', function () {
var current = $(this);
current.closest('div').find('input').each(function () {
(this).next().removeClass('darkred')
});
current.next().addClass('darkred');
});
JsFiddle: http://jsfiddle.net/gkislin13/tybp8skL
if you are looking for select droplist, and jquery code would like this:
var preValue ="";
//get value when click select list
$("#selectList").click(
function(){
preValue =$("#selectList").val();
}
);
$("#selectList").change(
function(){
var curentValue = $("#selectList").val();
var preValue = preValue;
console.log("current:"+curentValue );
console.log("old:"+preValue );
}
);

Testing input value in click handler

i have one textfield whose id is date. i want to give an dialog boxmsg when textfield is empty. i am tried the following code a lot times but it never going to execute button click function. Why this happen please tell me
var val = $('#date').val();
$(document).ready(function() {
$("#btnSubmit").click(function() {
if (val != null) {
$("#dialog").dialog();
return false;
}
});
});
Move var val = $('#date').val(); inside click handler so that val will always contain the latest value in the #date input.
$(document).ready(function() {
$("#btnSubmit").click(function() {
var val = $('#date').val().trim(); // Remove leading and trailing spaces
// Moved inside click handler
if (!val) { // Check if falsy value
$("#dialog").dialog();
return false;
}
});
});
Looks like your val variable scope is different. So you can try something like:
$(document).ready(function () {
$("#btnSubmit").click(function(){
if ($('#date').val()){
$("#dialog").dialog();
return false;
}
});
});
Something like this? Gets the value when you click and alerts if it's empty?
You need to get the textbox's value when you click, otherwise it will be empty since it's going to be set ONCE, when the page loads.
$(document).ready(function () {
$("#btnSubmit").click(function(){
var textbox = $('#textbox').val();
if (textbox.length == 0){
alert();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="textbox" type="text" placeholder="Type here"><br>
<button id="btnSubmit">Click me</button>

textarea.val() value changing but not displaying on page

I have a textarea like so,
<textarea id="txtaFilter" cols="45" rows="5"></textarea>
and the following script,
$(document).ready(function () {
$(".selector").bind('change', function () {
var value = $(this).val();
$("#txtaFilter").val($("#txtaFilter").val() + value);
$(this).children('option:eq(0)').prop('selected', true);
});
});
where ".selector" is a class applied to two dropdownlists.
When I chose a value on the dropdown, it appears to do nothing, but after looking at the debugger in chrome it is changing the value just not displaying it.
Does anyone know why this is? Is there something special I'm missing about the .val() property?
Problem/Solution:
I forgot that there are multiple "#txtaFilter"'s on the page when I removed the $(this).siblings("#txtaFilter"), So it was accessing the hidden one instead of the visible one. Sorry about that, guess I was wrong on the question too :/
You can use val method:
$("#txtaFilter").val(function(i, oldVal){
return oldVal + value
});
Use .val() to get the text of a textarea.
$(document).ready(function () {
$(".selector").bind('change', function () {
var value = $(this).val();
var txtaFilter = $("#txtaFilter");
txtaFilter.val(txtaFilter.val()+value);
$(this).children('option:eq(0)').attr('selected', true);
});
});

Append to a.href id from input field

I am trying to append to a link with id a value that is entered from the input text field. I came this far searching stackoverflow but id doesn't work!
<script type="text/javascript">
jQuery(function(){
$("#txt_name").keypress(function() {
var value = $("#txt_name").val();
});
$("a#coupon_link").attr("href", function(i) {
return href + '&discount_code='.text(value);
});
});
</script>
and this is how the html looks like
<form>
<fieldset>
<input id="txt_name" type="text" value="discount" />
</fieldset>
</form>
<a id="coupon_link" href="https://www.e-junkie.com/ecom/gb.php?c=cart&i=XXXXXX&cl=YYYYYY&ejc=2" target="ej_ejc" class="ec_ejc_thkbx" onClick="javascript:return EJEJC_lc(this);"><img src="http://www.e-junkie.com/ej/ej_add_to_cart.gif" border="0" alt="Add to Cart"/></a>
You probably meant this:
$(function() {
$("#coupon_link").on('click', function(e) {
e.preventDefault(); // apparently not needed
location.href = $(this).attr('href') + '&discount_code=' + encodeURIComponent($('#txt_name').val());
});
});
You don't have to update the value of #txt_name on keypress; you only have to use the value when the link is pressed.
Fix your code like this :
$(function(){
$("#txt_name").keypress(function() {
var value = $("#txt_name").val();
var link = $("#coupon_link");
var originalHref = link.attr('originalHref');
if (!originalHref) {
originalHref = link.attr("href");
link.attr("originalHref", originalHref)
}
link.attr("href", originalHref + '&discount_code='+value);
});
});
A few things to note :
never add anything to a selector when you're targeting an element by ID
your value variable wasn't in the same scope
the return of val can be directly concatenated, you don't need to try to change it to text
you don't need to pass a function to attr in your case
you're trying to make the href grow with every key stroke. This is a bad idea. The solution I propose is to keep the original href
if you're not sure the original href has yet some parameters (i.e. has '?') you should test it (I let you do that)
Overall a much cleaner solution wouldn't be to change the link but to build the href on click on the link :
$("#coupon_link").click(function(e) {
location = this.href + '&discount_code=' + $('#txt_name').val();
});
Not sure to understand, but it looks like a scope issue try this javascript :
<script type="text/javascript">
jQuery(function(){
var value = 0;
$("#txt_name").keypress(function() {
value = $("#txt_name").val();
$("a#coupon_link").attr("href", function(i) {
return href + '&discount_code=' + encodeURIComponent(value);
});
});
});
</script>
Try this:
jQuery(function(){
$("#txt_name").keypress(function() {
var value = $("#txt_name").val();
$("a#coupon_link").attr("href", '&discount_code=' + String(value));
});
});
This isnt working because the href isnt being changed as the function is called before a keypress event is triggered. Look into replacing keypress with blur and update the href when blur() is called
i think you need this:
<script type="text/javascript">
$(function(){
$("#txt_name").keypress(function() {
var value = $("#txt_name").val();
$("a#coupon_link").attr("href",href+'&discount_code='+value.toString);
});
});
</script>
look at href don't know where you have that var, if it is needed ok else remove that
You probably need to change the href when a key has been pressed, not only on page load. To do so you will have to do the replacing of the href inside the keyup function, like so:
$(function(){
var link = $("a#coupon_link");
link.data('href', link.attr("href"));
$("#txt_name").on('keyup', function() {
link.attr("href", link.data('href') + '&discount_code='+ this.value);
});
});
So as to not append the &discount_code=*** several times, you need to store the original href somewhere, like in a data attribute.
this one worked for me getting value from input field and append it to the existing link using jquery.
$('#qty').on('keyup', function() {
var theQty = 0;
theQty = $("#qty").val();
var oldHref=$("a#buybtn").attr("href");
$("a#buybtn").attr("href",oldHref+ '&qty=' + String(theQty));
});

Categories

Resources