Detect the value of a Textbox entered by the User - javascript

I have a textboxwhere I can enter values directly from keyboard or from mouse click. If I click from mouse the value is increment by one from the previous value. Whereas from keyboard I can enter any value. My question is how do I detect the value of the textbox entered by any user.
suppose if any value is entered by keyboard I need to reset to zero.
Here is what I got so far
function AddTrackingItem()
{
var counter;
$("#Item_Count").keyup(function (event) {
if(event.which == 13)
counter = 0; // if value is enter from keyboard then reset value
else
{
counter = $("#Item_Count").val();
}
});
TIA

I am assuming the html looks something like this:
<input type="text" id="item_count" value="0" />
<input type="button" id="btn" value="Increment"/>
You'll need an event handler for clicks on the button (obviously), and an event handler for the change event on the input field. The click on the button will not trigger the change event, but changing the input field manually will. Therefore we can safely reset the counter to 0 if the user alters the field.
$('#btn').on( 'click', function() {
$('#item_count').val( function( i, oldval ) {
return (oldval*1) + 1;
} );
} );
$('#item_count').on( 'change', function() {
$('#item_count').val( '0' );
} );
Edit: There are only two ways of entering data. One is by keyboard. The other one is by the button. That means that if the change event isn't triggered by the button, 100% of the cases where the change event is triggered, it must be via the keyboard. You can alter the code a bit to include the .data(...) (docs) functionality of jQuery and do something like the following code. It will reset the input when it was altered, and subsequently the button was pressed.
$('#btn').on( 'click', function() {
$('#item_count').val( function( i, oldval ) {
if( $(this).data( 'fromKeyboard' ) == 1 ) {
$(this).data('fromKeyboard', 0 );
return 1;
}
return (oldval*1) + 1;
} );
} );
$('#item_count').on( 'change', function() {
$(this).data( 'fromKeyboard', 1 );
} );
Example on jsbin.

if you don't want user to manually enter value in the textbox, why not make it readonly?
Anyway, if you want to do what you insist to do. Here is how to do it.
$("#btn").click(function(){
var currentVal = $("#item_count").val();
var counter = parseInt(currentVal) + 1;
$("#item_count").val(counter);
});
$("#item_count").keyup(function (event) {
$("#item_count").val("0");
});
Notice that I don't have the listener for enter key event (13) because I change the value to 0 upon keyup. If you want to have the value change to 0 on enter key you can do what you have in your code. Remember to convert the string to int so you can add/increment the value. When you do a .val() it returns a string not int. Hope this helps. Let me know if you have any questions.

Related

OnChange event not working in Input Type = Number when click on spinner in JQuery

I have an
<input type="number" class="post-purchase-amount"/>.
I am calling an
ajax call when the value get changed. It is working (with the following code) when the cursor is in the
text box itself and doing any changes. But it not working when i click the spinner (up/down button) of the input type.
parentPanel.on("change", ".post-purchase-amount", null, function (event) {
updateAmount($(this));
});
My problem is that i could use the "input" event here but that can call the ajax
every time when in change the value like if i want to send value 65
then it calls twice when typing each number. I need to call ajax only when the value has been changed not every key
stroke.
Sorry for my English. Thanks in advance
How about you create a function to throttle the input and trigger it on keypress instead. Something like this:
function throttle(func, interval) {
var last = 0;
return function() {
var now = Date.now();
if (last + interval < now) {
last = now;
return func.apply(this, arguments);
}
};
}
parentPanel.on("keypress", ".post-purchase-amount", null, throttle(function(event) {
updateAmount($(this));
}, 800));
Your problem is that you are watching for a change and anytime you make a change this is going to fire. What you could do instead is use focusout to watch when you "exit" the number input. What the below function does is it checks to see if the previous value is equal to the new value when you exit focus on the input. If the current value is not the same then it has been updated.
var prevVal = $('.numOfPeople').val();
$('.numOfPeople').on('focusout', null, function(e) {
var curVal = $('.numOfPeople').val();
if(prevVal !== curVal) {
//Value is different so do your updates here.
preVal = curVal;
$('#changed').show();
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="numOfPeople" type="number" name="quantity" min="1" max="5">
<p id="changed" style="display: none;">Value has changed</p>

Make JavaScript Detect Buttons That Are Pressed In a Certain Order

I am trying to make a number keypad from 0 to 9 and when certain numbers get pressed in a certain order an event will happen.
So something like this
if ( button1 gets pressed then button2 then button3 )
alert('You did the code!')
}
else {
alert('You did not do the code')
}
No jQuery please
Thanks!
//sequence is 358
//SOLUTION
sequence = {
check : function(e){
sequence.value += this.textContent;
if (sequence.value == sequence.sequence)
{
alert(1);
sequence.value = "";
}
else
{
if (sequence.timer)
{
clearTimeout(sequence.timer);
}
sequence.timer = setTimeout("sequence.value=''", 1000);
}
},
value : "",
sequence : "358"
}
//THIS CODE ATTACHES CLICK HANDLERS TO THE BUTTON, NOT PART OF THE SOLUTION
Array.prototype.map.call(document.querySelectorAll("button"), function(element){
element.addEventListener("click", sequence.check, false);
});
//end
<button>7</button><button>8</button><button>9</button><br/>
<button>4</button><button>5</button><button>6</button><br/>
<button>1</button><button>2</button><button>3</button><br/>
<button>0</button>
How does this work. I don't want to pollute the global scope with values so I used an object to store the variables and the check method in.
The object is called sequence.
It has three properties
check, the method that checks the input when a button is clicked.
value, that holds the sequence value until the correct sequence is found.
sequence, the property that holds the correct value.
Each button on the page is assigned with a click handler. When clicked it fires sequence.check. Via the this keyword (referring to the button) we extract the number (via textContent). We add that number to the value string. Then we check if the value matches the sequence. If so execute some code (in this case an alert) and reset the value.
There is a timer set. If the user doesn't enter a new number within a second the timer will reset the value. setTimeout does this. The 1000 stands for 1000 milliseconds = 1 second.
I would achieve this by monitoring the keydown event, and if the key is a number, add in to an array. At the same time, check the array contents to see if they are in a certain defined order. If they are, fire whatever you need to do, if not, do nothing but add the key to the array. Once your sequence has been completed, clear the array to make way for a new sequence.
You could get complicated with things like, clearing the array after a certain interval of not completing the sequence etc.
Here is a simple system that does part of what you are looking for:
var buttons = document.querySelectorAll('button'),
i;
for (i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', function() {
var pressed = document.getElementById('pressed');
pressed.value += this.value + "|";
if (pressed.value === '1|2|3|') {
alert('You unlocked it!');
}
if (pressed.value.length >= 6) {
//Start over
pressed.value = "";
}
}, false);
}
<input id='pressed' type='text' />
<button value='1'>One</button>
<button value='2'>Two</button>
<button value='3'>Three</button>

Javascript capturing keydown

I have a form with many fields and when the user does a "double Enter" in any of the fields doSomething() should happen.
The code below basically works ok, apart from the fact that doSomething() gets called as many times as there are characters in that field. It should only be called once, while if I put "ABC" in the field, doSomething() gets called 3X. It only needs to be called once after 2X Enter, regardless of what was entered in the field.
I (kind of) understand why it's happening (keydown was called 3 times) but have no idea how to fix it. Do I need to unbind something? Resetting the counter to 0 when e.keyCode isn't 13 doesn't seem to make a difference.
EDIT - http://jsfiddle.net/hzr8cezn/ - I'm using 2X SPACE bar character to test since Enter tries to submit the form on jsfiddle. Hit 2X space (in Chrome) and check your console
$("#dynamicFields").on('keydown', 'input', function(e) {
var counter = 0
var field = $(this)
field.keydown(function (e) {
if(e.keyCode == 13) {
counter++;
if(counter == 2) {
console.log('twice!')
doSomething()
}
}
else {
counter = 0
}
})
})
You are attaching to the "keydown" event twice, once using on() and the other using keydown(). You only need to do this once.
Since you are tracking the counter per element, you can use a data() call to track it on the element itself.
// init counter to 0
$("#dynamicFields input").data('counter',0);
// bind to keypress event
$("#dynamicFields").on('keydown', 'input', function(e) {
// the input field
var $field = $(this);
// enter key?
if ( e.keyCode == 13 ){
// how many times?
var counter = $field.data('counter');
// increment it
$field.data('counter',++counter);
// do the stuff
if ( counter >= 2 ){
alert('well, you did it.');
}
} else {
// reset
$field.data('counter',0);
}
})
See it working in this jsFiddle.

Disabling/enabling a button based on multiple other controls using Javascript/jQuery

I have a bunch of controls:
When a user clicks the Generate button, a function uses all of the values from the other controls to generate a string which is then put in the Tag text box.
All of the other controls can have a value of null or empty string. The requirement is that if ANY of the controls have no user entered value then the Generate button is disabled. Once ALL the controls have a valid value, then the Generate button is enabled.
What is the best way to perform this using Javascript/jQuery?
This can be further optimized, but should get you started:
var pass = true;
$('select, input').each(function(){
if ( ! ( $(this).val() || $(this).find(':selected').val() ) ) {
$(this).focus();
pass = false;
return false;
}
});
if (pass) {
// run your generate function
}
http://jsfiddle.net/ZUg4Z/
Note: Don't use this: if ( ! ( $(this).val() || $(this).find(':selected').val() ) ).
It's just for illustration purposes.
This code assumes that all the form fields have a default value of the empty string.
$('selector_for_the_parent_form')
.bind('focus blur click change', function(e){
var
$generate = $('selector_for_the_generate_button');
$generate.removeAttr('disabled');
$(this)
.find('input[type=text], select')
.each(function(index, elem){
if (!$(elem).val()) {
$generate.attr('disabled', 'disabled');
}
});
});
Basically, whenever an event bubbles up to the form that might have affected whether the generate button ought to be displayed, test whether any inputs have empty values. If any do, then disable the button.
Disclaimer: I have not tested the code above, just wrote it in one pass.
If you want the Generate button to be enabled as soon as the user presses a key, then you probably want to capture the keypress event on each input and the change event on each select box. The handlers could all point to one method that enables/disables the Generate button.
function updateGenerateButton() {
if (isAnyInputEmpty()) {
$("#generateButton").attr("disabled", "disabled");
} else {
$("#generateButton").removeAttr("disabled");
}
}
function isAnyInputEmpty() {
var isEmpty = false;
$("#input1, #input2, #select1, #select2").each(function() {
if ($(this).val().length <= 0) {
isEmpty = true;
}
});
return isEmpty;
}
$("#input1, #input2").keypress(updateGenerateButton);
$("#select1, #select2").change(updateGenerateButton);
The above assumes that your input tags have "id" attributes like input1 and select2.

action keyup after the third charecter

Hi could someone help me figure out how to stop a function running until a specific number of characters are pressed?
currently using the following function:
$('input#q').keyup
this works as soon as you press any key...
Something like this should start firing code after 3 letters have been added:
Live Example
JavaScript
$('input#q').keyup( function() {
if( this.value.length < 4 ) return;
/* code to run below */
$('#output').val(this.value);
});
HTML
<input id="q" />
<br /><br />
<input id="output"/>
you could do :
$('input#q').keyup(function(){
if($(this).val().length > 3)
{
//do something
}
});
You could store the characters in a string variable each time a key is pressed and then run a conditional statement to check the length of the variable. If it's equal to three, run whatever function
Well you'll probably need to take into account the way focus changes. Do you want to clear the counter when the field is newly focused or not? You should also decide whether you're counting characters actually added to the field, or instead if you want to could actual discrete key presses - a "shift" key press, for example, won't add any characters, but it's a key being pressed.
Anyway it'd probably be something like this:
$(function() {
var keyCount = 0;
$('#q').keyup(function() { // "keypress" to count characters
if (++keyCount === 3) {
// do the thing
}
})
.focus(function() {
keyCount = 0; // if this is what you want
});
});
If you're counting the "keypress" event instead of "keyup", you might want to count the actual length of the text field value rather than trying to count events.
How's about:
var c = 0;
('input#q').keyup( function() {
c++;
if (c >= 3) {
startGame();
}
} );

Categories