Using jquery, how to auto subtracting amount from input after typing it without button
Ex. When I type a number in an input , I want to subtract it -5 after I leave it automaticaly without submit button , 200 will be 195 .
Is it posible?
Ok here's a quick way to do this in jquery. Try the code below. Add a number and tab off the input or click out of it and the value will change.
$('input').on('blur', function() {
var num = $(this).val() - 5;
$(this).val(num);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
EDIT: In case you are looking for a pure JavaScript alternative (without jQuery):
You can attach this process to an input event such as onkeyup or onfocusout:
function update() {
amount = document.getElementById("amount");
amount.value = parseInt(amount.value) - 5;
}
<input type="text" id="amount" onfocusout="update()">
JavaSript solution.
This will work for you.
document.getElementById("input").onblur = substract;
function substract() {
let firstValue = event.currentTarget.value;
let finalValue = Number(firstValue) - 5;
document.getElementById("input").value = finalValue;
}
To do this you need need to create a function and attach the input Element to the function.
Creating a function to reduce input element on change by 5.
var myfunction = function(){
var value = parseInt(this.value);
//check if input is of type int and less than five to avoid negative numbers.
if( !value || value < 5 ){
return false;
}
this.value = value - 5;
};
//ataching function to the element
var element = document.getElementById('my_input');
element.addEventListener( 'change', myfunction, false );
Related
this is for a personal art project. What I basically want to do is create a blank web page where a user can type in text (like a text-editor), but have the text fade out as they type.
By fade out, I don't want the user to have the ability to see the text they had just written. So, I don't want to just transition the font color to match the background color as the user can select the text again.
So far, I've made a textarea that on keyup will store the text input, which will show in a separate div. I've specified in Javascript that when the entered text has reached a certain length: the div will fade out, clear the text, and show up again to show the current text input. The problem is that according to the console, I can't clear the value of the div. Does this make sense?
Here is a fiddle: http://jsfiddle.net/anelec/k40p72xk/5/
HTML:
<textarea type='text' id='myinput'></textarea>
<div><span id="fade"></span></div>
Javascript:
//on keyup store text input into a variable "text"
$( "#myinput" ).keyup(function( event ) {
var text = $("#myinput").val();
console.log("event working");
console.log(text);
//show values of "text" variable in id "fade"
$("#fade").text(this.value);
var fade = $("#myinput").val();
//function to clear text value of id "fade"
function cleartext(){
document.getElementById("#fade").value="";
}
//clear text value of id "fade" after 15 letters
if (fade.length >=15) {
$("#fade").fadeOut(200);
cleartext();
}
//show the incoming text input somehow
if (fade.length <=15) {
$("#fade").fadeIn("fast");
}
});
Please let me know if there is a better way I can approach this.
Try something like this:
// Keep track of how many sets of 15 chars there are
var accum = 0;
// If the length is divisible by 15
if (text.length % 15 == 0) {
$("#fade").fadeOut(200, function() {
accum ++;
// $(this) refers to $("#fade")
$(this).val(''); // set the value to an empty string
});
} else {
$("#fade").fadeIn('fast');
}
// Use the substring method to get every 15 characters to display in #fade
var start = accum * 15,
end = (accum + 1) * 15,
next = text.substring(start, end);
$("#fade").text(next);
This is the closest I've gotten:
Javascript:
$( "#myinput" ).keyup(function( event ) {
var text = $("#myinput").val();
console.log("event working");
console.log(text);
//show values of "text" variable in id "fade"
$("#fade").text(this.value);
var fade = $("#myinput").val();
if (text.length >=5) {
$("#fade").fadeTo(600,0);
$(this).val("");
$("#fade").fadeTo(20,1);
}
});
If I understood you correctly, this should work. You'll want to use the innerHTML instead of value.
Try changing:
function cleartext(){
document.getElementById("#fade").value="";
}
to this:
function cleartext(){
document.getElementById("#fade").innerHTML="";
}
You use value for input fields, and innerHTML for non-input fields.
Option 1:
$( "#myinput" ).keyup(function( event ) {
var text = $("#myinput").val();
console.log("event working");
console.log(text);
$("#fade").text(this.value);
var fade = $("#myinput").val();
function cleartext(){
document.getElementById("fade").innerHTML="";
// you use value this time because it's input field
document.getElementById("myinput").value = "";
}
if (fade.length >=15) {
$("#fade").fadeOut(200);
cleartext();
}
if (fade.length <=15) {
$("#fade").fadeIn("slow");
}
});
Option 2:
THIS EXAMPLE IS FROM ALEX CASSEDY - IF ITS THE BETTER ANSWER, GIVE HIM CREDIT AND NOT MINE, I SIMPLY FIXED ONE THING ON IT SO IT WORKS.
$( "#myinput" ).keyup(function( event ) {
var text = $("#myinput").val();
console.log("event working");
console.log(text);
$("#fade").text(this.value);
var fade = $("#myinput").val();
// Keep track of how many sets of 15 chars there are
var accum = 0;
// If the length is divisible by 15
if (text.length % 15 == 0) {
$("#fade").fadeOut(200, function() {
accum ++;
// $(this) refers to $("#fade")
$(this).val(''); // set the value to an empty string
});
} else {
$("#fade").fadeIn('fast');
}
// Use the substring method to get every 15 characters to display in #fade
var next = text.substring(fade.length - 15);
$("#fade").text(next);
});
I'm using an ID scanner that acts as a keyboard input and I want an input field to listen for the value and substring (or slice) out unnecessary, extra values.
Currently, the ID scanner formats numbers like this: ;708089113=0184?
I want to grab only the 708089113. I want to remove the semi-colon and everything after the 3.
I'm just not sure how to do this automatically. The stripped value should appear in the field before submitting.
Javascript:
var suid = document.getElementById("SUID").value;
var stripSUID = suid.substring(1,10);
document.getElementById("SUID").value = stripSUID;
HTML:
<input name="SUID" id="SUID" type="text" value="">
JSFiddle Link
You can use jQuery for this.
HTML:
<input name="suid" id="suid" type="text" value="">
JavaScript:
$(function() {
$('#suid').change(function() {
var suid = $(this).val();
var stripSUID = suid.split('=');
var stringLength = stripSUID[0].length;
var returnValue = stripSUID[0].substr(1, stringLength);
$(this).val(returnValue);
});
});
jsFiddle update: http://jsfiddle.net/jhjr288o/4/
So you're asking how to listen for a change to the <input>?
var elm = document.getElementById('SUID');
elm.addEventListener('change', function (e) {
var s = this.value, i = s.indexOf('=');
if (i !== -1) {
s = s.slice(1, i);
this.value = s;
}
});
DEMO
The change event fires when the element loses focus
The input event fires every time oldvalue !== newvalue (i.e. for every char typed)
Also note, this code must be run after the Element exists, i.e. wait for the Window's load event
I'd like the user to be blocked from typing more if the value is over 100. So far I have the following from reading different posts:
$('.equipCatValidation').keyup(function(e){
if ($(this).val() > 100) {
e.preventDefault();
}
});
To confirm I want the value not the string length, and it can't be above 100.
However this is not preventing further input in the field. What am I missing.
Checking keyup is too late, the event of adding the character has already happened. You need to use keydown. But you also want to make sure the value isn't > 100 so you do need to also use keyup to allow js to check the value then too.
You also have to allow people to delete the value, otherwise, once it's > 100 nothing can be changed.
<input class="equipCatValidation" type="number" />
When using input type="number", change also needs to be on the event list.
$('.equipCatValidation').on('keydown keyup change', function(e){
if ($(this).val() > 100
&& e.keyCode !== 46 // keycode for delete
&& e.keyCode !== 8 // keycode for backspace
) {
e.preventDefault();
$(this).val(100);
}
});
http://jsfiddle.net/c8Lsvzdk/
Basically keypress events are fired before accepting the current value. So when you press on any key, keypress event is subscribed but you don't get the updated value/result for the recently pressed key. So, to get the last pressed key we can use the fromCharCode method and concat it with the value we got from the textbox. That's it,
HTML :
<input id="inputBox" type="text" />
jQuery :
$("#inputBox").on("keypress", function(e){
var currentValue = String.fromCharCode(e.which);
var finalValue = $(this).val() + currentValue;
if(finalValue > 100){
e.preventDefault();
}
});
jsFiddle
Maybe keydown instead of keyup?
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(function() {
$('.equipCatValidation').keydown(function(e){
if ($(this).val() > 100) {
e.preventDefault();
}
});
})
</script>
</head>
<body>
<input type="text" class="equipCatValidation">
</body>
</html>
EDIT: There is a valid comment here - Prevent user from typing in input at max value - to circumvent that you should probably store the previous value and restore it when necessary.
It is bad UI to disable the input if a user inputs a bad value. I'm assuming you simply want to put a max value that the user cannot go over. If so, you can either clamp the value, or use the max attribute in your markup:
<form>
<input type='number' max='100'>
</form>
If you input an invalid value, the input will turn red, and you cannot submit the form.
<input class="equipCatValidation" />
var maxValue = 100;
jquery
$('.equipCatValidation').on('keypress', function(e){
/* preventing set value when it doesn't pass conditions*/
e.preventDefault();
var input = $(this);
var value = Number(input.val());
var key = Number(e.key);
if (Number.isInteger(key)) {
value = Number("" + value + key);
if (value > maxValue) {
return false;
}
/* if value < maxValue => set new input value
in this way we don't allow input multi 0 */
$element.val(value);
}
});
vanilla js
document.querySelector(".equipCatValidation")
.addEventListener("keypress", function(e) {
e.preventDefault();
var input = e.target;
var value = Number(input.value);
var key = Number(e.key);
if (Number.isInteger(key)) {
value = Number("" + value + key);
if (value > maxValue) {
return false;
}
input.value = value;
}
});
example
addition to the this answer
$('.equipCatValidation').on('keypress', function(e){
var $element = $(this);
var value = Number($element.val());
var key = Number(e.key);
if (Number.isInteger(key)) {
value = Number("" + value + key);
}
if (value > 100) {
return false;
}
});
Here's a solution for those using modern vanilla Javascript:
Just snap the value back down to the max when the user focuses away from the input.
You would set the input to a number type and the max value
<input type="number" max="100">
and then add a function to the onblur method of the element
document.querySelector('input[max]').onblur = function (event) {
// If the value is less than the max then stop
if (Number(event.target.value) < event.target.max) return
// Snap the value to the max
event.target.value = event.target.max
}
You can also use oninput instead of onblur but that may cause the user to have to fight the input in certain situations.
Example
I have an html input as,
<input type="text" id="txtCheckoutBCode" name="barcode" class="sfInputbox" />
Now I want to fire some ajax call meanwhile barcode reader reads barcode and the barcode is reflected in above text field.
I tried following codes,
$('#txtCheckoutBCode').on('change', function() {
var me= $(this);
var number = 0;
number = $.trim(me.val());
if (number.length == 12) { // 12 coz my barcode is of length 12
//ajaxcall method
}
});
But fires only when the focus is changed from the input field. Also ,
$('#txtCheckoutBCode').on('keyup', function() {
var me= $(this);
var number = 0;
number = $.trim(me.val());
if (number.length == 12) { //12 coz my barcode is of length 12
//ajax call method
}
});
This fires the ajax call twice, and I do not prefer this.
I need to call the ajax code as soon as the input field is filled with barcode. But not twice.
First of all you should use propertychange keyup input paste instead of keyup in order to be sure to detect any interaction with your input (such as pasting for example). But it might trigger the event twice, especially in Firefox. I'd recommend using keyup pasteonly.
change, as you said, will be triggered when the input loses focus.
keyup will be triggered at each key press.
If you want your ajax call to be executed only once, try using stopImmediatePropagation():
$('#txtCheckoutBCode').on('keyup paste', function(e) {
e.stopImmediatePropagation();
var me= $(this);
var number = 0;
number = $.trim(me.val());
if (number.length == 12) { // 12 coz my barcode is of length 12
//ajaxcall method
}
});
http://jsfiddle.net/fC5yh/
change keyup to keypress
<script type="text/javascript" >
$(function() {
$('#txtCheckoutBCode').on('keypress', function() {
var self = $(this);
var number = 0;
number = $.trim(self.val());
if (number.length == 12) { //12 coz my barcode is of length 12
//ajax call method
}
});
});
</script>
<input type="text" id="txtCheckoutBCode" name="barcode" class="sfInputbox" />
Basically I need to check if the value is changed in a textbox on the 'blur' event so that if the value is not changed, I want to cancel the blur event.
If it possible to check it the value is changed by user on the blur event of an input HTML element?
I don't think there is a native way to do this. What I would do is, add a function to the focus event that saves the current value into a variable attached to the element (element.oldValue = element.value). You could check against that value onBLur.
Within the onblur event, you can compare the value against the defaultValue to determine whether a change happened:
<input onblur="if(this.value!=this.defaultValue){alert('changed');}">
The defaultValue will contain the initial value of the object, whereas the value will contain the current value of the object after a change has been made.
References:
value vs defaultValue
You can't cancel the blur event, you need to refocus in a timer. You could either set up a variable onfocus or set a hasChanged variable on the change event. The blur event fires after the change event (unfortunately, for this situation) otherwise you could have just reset the timer in the onchange event.
I'd take an approach similar to this:
(function () {
var hasChanged;
var element = document.getElementById("myInputElement");
element.onchange = function () { hasChanged = true; }
element.onblur = function () {
if (hasChanged) {
alert("You need to change the value");
// blur event can't actually be cancelled so refocus using a timer
window.setTimeout(function () { element.focus(); }, 0);
}
hasChanged = false;
}
})();
Why not just maintaining a custom flag on the input element?
input.addEventListener('change', () => input.hasChanged = true);
input.addEventListener('blur', () =>
{
if (!input.hasChanged) { return; }
input.hasChanged = false;
// Do your stuff
});
https://jsfiddle.net/d7yx63aj
Using Jquery events we can do this logic
Step1 : Declare a variable to compare the value
var lastVal ="";
Step 2: On focus get the last value from form input
$("#validation-form :input").focus(function () {
lastVal = $(this).val();
});
Step3:On blur compare it
$("#validation-form :input").blur(function () {
if (lastVal != $(this).val())
alert("changed");
});
You can use this code:
var Old_Val;
var Input_Field = $('#input');
Input_Field.focus(function(){
Old_Val = Input_Field.val();
});
Input_Field.blur(function(){
var new_input_val = Input_Field.val();
if (new_input_val != Old_Val){
// execute you code here
}
});
I know this is old, but I figured I'd put this in case anyone wants an alternative. This seems ugly (at least to me) but having to deal with the way the browser handles the -1 index is what was the challenge. Yes, I know it can be done better with the jquery.data, but I'm not that familiar with that just yet.
Here is the HTML code:
<select id="selected">
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
Here is the javascript code:
var currentIndex; // set up a global variable for current value
$('#selected').on(
{ "focus": function() { // when the select is clicked on
currentIndex = $('#selected').val(); // grab the current selected option and store it
$('#selected').val(-1); // set the select to nothing
}
, "change": function() { // when the select is changed
choice = $('#selected').val(); // grab what (if anything) was selected
this.blur(); // take focus away from the select
//alert(currentIndex);
//setTimeout(function() { alert(choice); }, 0);
}
, "blur": function() { // when the focus is taken from the select (handles when something is changed or not)
//alert(currentIndex);
//alert($('#selected').val());
if ($('#selected').val() == null) { // if nothing has changed (because it is still set to the -1 value, or null)
$('#selected').val(currentIndex); // set the value back to what it originally was (otherwise it will stay at what was newly selected)
} else { // if anything has changed, even if it's the same one as before
if ($('#selected').val() == 2) { // in case you want to do something when a certain option is selected (in my case, option B, or value 2)
alert('I would do something');
}
}
}
});
Something like this. Using Kevin Nadsady's above suggestion of
this.value!=this.defaultValue
I use a shared CSS class on a bunch of inputs then do:
for (var i = 0; i < myInputs.length; i++) {
myInputs[i].addEventListener('blur', function (evt) {
if(this.value!=this.defaultValue){
//value was changed now do your thing
}
});
myInputs[i].addEventListener('focus', function (evt) {
evt.target.setAttribute("value",evt.target.value);
});
}
Even if this is an old post, I thought i'd share a way to do this with simple javascript.
The javascript portion:
<script type="text/javascript">
function HideLabel(txtField){
if(txtField.name=='YOURBOXNAME'){
if(txtField.value=='YOURBOXNAME')
txtField.value = '';
else
txtField.select();
}
}
function ShowLabel(YOURBOXNAME){
if(txtField.name=='YOURBOXNAME'){
if(txtField.value.trim()=='')
txtField.value = 'YOURDEFAULTVALUE';
}
}
</script>
Now the text field in your form:
<input type="text" id="input" name="YOURBOXNAME" value="1" onfocus="HideLabel(this)"
onblur="ShowLabel(this)">
And bewn! No Jquery needed. just simple javascript. cut and paste those bad boys. (remember to put your javascript above the body in your html)
Similar to #Kevin Nadsady's post, the following will work in native JS functions and JQuery listener events. Within the onblur event, you can compare the value against the defaultValue:
$(".saveOnChange").on("blur", function () {
if (this.value != this.defaultValue) {
//Set the default value to the new value
this.defaultValue = this.value;
//todo: save changes
alert("changed");
}
});
The idea is to have a hidden field to keep the old value and whenever the onblur event happens, check the change and update the hidden value with the current text value
string html = "<input type=text id=it" + row["cod"] + "inputDesc value='"
+ row["desc"] + "' onblur =\"if (this.value != document.getElementById('hd" + row["cod"].ToString() +
"inputHiddenDesc').value){ alert('value change'); document.getElementById('hd" + row["cod"].ToString() +
"inputHiddenDesc').value = this.value; }\"> " +
"<input type=hidden id=hd" + row["cod"].ToString() + "inputHiddenDesc value='" + row["desc"] + "'>";