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
Related
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 );
I want a function to be called whenever there is any change within my text area, i.e. char typed, removed, cut, pasted etc.
Currently I am using:
onkeyup || onmousemove = function();
This seems to only be calling onmousemove, what can I use to call my function on ANY change to the textarea.
I am creating this JS as a string to add it as a parameter to the creation of a text_area using codeigniteras described here at form_input section
e.g:
$js= 'onkeyup || onmousemove = "function()"';
echo text_area('name', " ", $js);
There's no way to combine multiple HTML attribute assignment, you have to do them separately. Try:
text_input('name', ' ', 'onkeyup="function()" onmousemove="function()"');
try this :
$('#element').on('keyup keypress blur change', function() {
...
});
Just give textarea an id say myId and bind events to it to trigger handler.
var element = document.getElementById("myId");
var myEvents = "oninput onchange onkeyup onpaste".split(" ");
var handler = function (e) {
};
for (var i=0, len = myEvents.length; i < len; i++) {
element.addEventListener(myEvents[i], handler, false);
}
Try something like below
Example
<textarea id='textarea1'>data</textarea>
//....................
$("textarea").bind('input propertychange', function(){
alert($(this).val());
});
Note: Use jquery plugin
DEMO
If you want to prevent simultaneous triggers then use the below code
<textarea id="textarea"></textarea>
//.......
var text = "";
$("#textarea").on("change keyup paste", function() {
var Val = $(this).val();
if(Val == text) {
return; //prevent multiple simultaneous triggers
}
text = Val;
alert("changed!");
});
DEMO2
I have implemented a JS counter in my app. I have 2 form fields that my two different counters should work for. A #post_title and a #body-field.
This is my JS:
counter = function() {
var title_value = $('#post_title').val();
var body_value = $('#body-field').val();
if (title_value.length == 0) {
$('#wordCountTitle').html(0);
return;
}
if (body_value.length == 0) {
$('#wordCountBody').html(0);
return;
}
var regex = /\s+/gi;
var wordCountTitle = title_value.trim().replace(regex, ' ').split(' ').length;
var wordCountBody = body_value.trim().replace(regex, ' ').split(' ').length;
$('#wordCountTitle').html(wordCountTitle);
$('#wordCountBody').html(wordCountBody);
};
$(document).on('ready page:load', function () {
$('#count').click(counter);
$('#post_title, #body-field').on('change keydown keypress keyup blur focus', counter);
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<label for="title">Title</label>
<textarea id="post_title" placeholder="Enter Title"></textarea>
<span id="wordCountTitle">0</span> words<br/>
<label for="report">Report</label>
<textarea id="body-field"placeholder="Provide all the facts." rows="4">
</textarea><br />
<span id="wordCountBody">0</span> / 150 words
</body>
</html>
The seemingly stray $(document).ready(ready); corresponds to a var ready = function() called earlier in the file that I left out for brevity purposes. But I left the document.ready() call in the order that it appears just incase it could be causing an issue.
So the issue I am having is, whenever you click on the #post_title field and enter words the counter does not update. But as soon as I click on the #body-field and start typing not only does the counter for the #body-field work and start updating immediately, but the counter for the #post_title starts working too and shows the correct amount of words in that field.
What could be causing this?
Edit 1
Just playing with that code snippet I realized that the error exists in another state too. If you just add text to the 2nd field first (i.e. the #body-field) before entering in the title...the counter for the body-field won't increment. It will only update AFTER you start entering a title in the #post_title. So they are both linked somehow.
You should not have the counter function check and perform operations on both fields. The counter function should do exactly the same operation, by utilizing jquery's this keyword inside it, or by taking an event parameter and using that as an alternative, with event.target.
Here's the refactor:
var counter = function(event) {
var fieldValue = $(this).val();
var wc = fieldValue.trim().replace(regex, ' ').split(' ').length;
var regex = /\s+/gi;
var $wcField = $(this)[0] === $('#post_title')[0] ? $('#wordCountTitle') : $('#wordCountBody');
if (fieldValue.length === 0) {
$wcField.html('');
return;
}
$wcField.html(wc);
};
$(document).on('ready page:load', function () {
$('#post_title, #body-field').on('change keyup paste', counter);
});
JSBin playground
Also, I am not entirely sure why you are listening to that many events on those textareas, when change keyup paste ought to do it.
the error you're having is because of these 2 blocks of code
if (title_value.length == 0) {
$('#wordCountTitle').html(0);
return;
}
if (body_value.length == 0) {
$('#wordCountBody').html(0);
return;
}
This means that in order for the counters to run, both title and body should have some value. Just remove the return on both and it should work.
EDIT
I think removing both if blocks will also give you the same behavior you want. If you want to have both if blocks, you'll have to separate the counter for the title and body.
EDIT 2
here's a simpler implementation of counter function.
counter = function() {
var title_value = $('#post_title').val();
var body_value = $('#body-field').val();
$('#wordCountTitle').html(title_value.split(' ').length);
$('#wordCountBody').html(body_value.split(' ').length);
}
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
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"] + "'>";