jQuery val() not updating input field - javascript

I have input field:
<input class="form-control" id="Page" min="1" name="Page" type="number" value="1">
and with jQuery I'm trying to change value after button press.
Here is my code:
$(document).ready(function () {
$("#Right").on("click", function () {
var page = $("#Page").val();
page = page++;
$("#Page").val(page);
})
I can read value.
increment it.
But when I'm trying to save it to he input field value it's keeps old value.
I also tried parsing it to int like this:
var value= parseInt(page);
value = value++;
$("#Page").val(value);
And this also gave no effect.
Can you suggest something?

Simply use page++;
$(document).ready(function () {
$("#Right").on("click", function () {
var page = parseInt($("#Page").val());
page++;
$("#Page").val(page);
});
});
Fiddle Demo
value++ is known as postfix , add 1 to a returns the old value.Hence while using value = value++; , the value of value will be always 1

The problem is that value = value++ won't sum, instead use just value++.
var value = parseInt(page);
value++;
$("#Page").val(value);

Use parseInt() to convert the value as integer, then apply increment. Try with this
$(document).ready(function () {
$("#Right").on("click", function () {
var page = parseInt( $("#Page").val() );
page++;
$("#Page").val(page);
})

Related

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

Get value from textbox not working in JavaScript

I want to alert the value of the textbox topValue, but when solve () is called, a textbox does appear, but with no text / value / number
Here is my code:
var topValue = document.getElementById('topValue').value
function solve() {
alert(topValue);
}
$('#solveButton').click(function () {
solve();
});
The value of the textbox is first fetched from DOM. But, when clicked on button, the same cached value is used.
This can be solved by moving the statement that read value from DOM in the function.
function solve() {
var topValue = document.getElementById('topValue').value
alert(topValue);
}
Note that
$('#solveButton').click(function () {
solve();
});
can also be written as
$('#solveButton').click(solve);
But, there is a better way.
I'll suggest you to use jQuery to get the value from the textbox.
// When DOM is completely loaded
$(document).ready(function () {
// On click of the `solveButton`
$('#solveButton').click(function () {
// Get the value of the `#topValue`
var topValue = $('#topValue').val();
// For debugging use `console.log` instead of `alert`
console.log('topValue', topValue)
});
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function () {
var topValue = document.getElementById('topValue').value; // have the initial value
function solve() {
alert(topValue);
alert(document.getElementById('topValue').value) // current value
}
$('#solveButton').click(function () {
solve();
});
});
</script>
</head>
<body style="width:50%;">
<input type="text" id="topValue" value="ssss"/>
<input type="button" value="Solve" id="solveButton" />
</body>
</html>

on() to watch changes in input

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

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

Categories

Resources