little question,
I'm trying to automaticly run the function when the input field is 7 characters long.
I've tried some different snippets :
var barcodeMeting = document.getElementById("barcode").value.length;
if(barcodeMeting.innerHTML.length == 7)
{
document.getElementById('btn').click();
}
and
if(docement.getElementById('barcode').length == 7)
{
document.getElementById('btn').click();
}
and
count = barcodeParsing.length ;
if(count >= 6)
{
document.getElementById('btn').click();
}
Anyone who knows an easy solution?
my function with ajax post looks like :
$("#btn").click(function(){...}
and my input field :
<input type="text" name="barcode" id="barcode" class="inputBarcode" placeholder=" Wachten op barcode scan..">
The solution below uses a keyup and sets the maxlength on the input to 7 to simplify UI handling. Once the desired length is met, then it submits the containing form.
Sample JSFiddle: http://jsfiddle.net/hmvmLqaa/4/
Updated input with maxlength set to 7:
<input type="text" name="barcode" id="barcode" class="inputBarcode" placeholder=" Wachten op barcode scan.." maxlength="7"/>
Javascript code:
$(document).ready(function() {
$('#barcode').keyup(function() {
if (this.value.length > 6) {
$(this.form).submit();
}
});
});
Instead of watching on the click event, you need to watch on keypress, or keyup events.
Also, you do not have a btn ID in your code. The ID of your input is 'barcode'.
Try something like...
$('#barcode').on('keypress', function(){
// function to run
});
Related
In javascript I need to check whiwh value user enter in an html input like this:
<input type="text" id="volume" class="form-control" name="voilume"></input>
<div id"button"></div>
Ineed to know if the input is between 0,5 and 8 (so I have int and float as you can understand).
So the value has to be >= 0,5 and <= 8
If value input if between 0,5 and 8 I have to display a button, else nothing to do. But I need to prevent if user change the value many times.
So if he enters 3 display a button in div id=button", if it changes for another value like 2 for example keep displaying the button, but if he changes value input for 100 I need to remove the button in div id="button".
for now I tried something like this in order to test if it works:
var input= $('#volume').val();
if (input >= 0.5 && input <= 8) {
$('#button').html('ok');
} else {
$('#button').empty();
}
But it does not work.
You can exploit the CSS Constraint Validation here a little bit. It seems to me like a X/Y Problem. Actually, we could set our min, max and step values for this <input> element and then let the browser do the validation:
<input type="number" min="0.5" max="8" step="0.1" required id="volume" class="form-control" name="voilume">
Alongside this, we can make usage of the pseudo css selectors :valid and :invalid like so:
input:valid~div#button {
display: block;
}
input:invalid~div#button {
display: none;
}
This would have the effect, that if we enter a valid value in our input control, the button will be displayed. If not, the button disappears. Magic!
Example: https://jsfiddle.net/4q1fjqwp/
.val() of an input field is a string, you have to convert it to a number in order to be able to compare it to numbers by >=, <=. You also had a typo: id"button"
function go() {
var input=parseFloat($('#volume').val(), 10);
if (input >= 0.5 && input <= 8) {
$('#button').html('ok');
} else {
$('#button').empty();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="volume" class="form-control" name="voilume"/>
<div id="button"></div>
<button onclick="go()">run</button>
The problem may happen when input contain comma ,
so "0,5" >= 0.5 will return false and parseFloat("0,5") will return 0.
You need replace , with .
Something like below will work.
<input type="text" id="myTextField" onblur="change()"/>
<input type="submit" id="byBtn" value="" />
JavaScript
function change() {
var myTextbox = document.getElementById('myTextField').value;
var button = document.getElementById('byBtn');
if (parseFloat(myTextbox) >= 0.5 && parseFloat(myTextbox) <= 8) {
button.value = "OK";
} else {
button.value = "";
}
}
you need to parse string value to integer. for that use parseInt().
it will parse string to integer.
replace this:
var input= $('#volume').val();
by
var inputval= parseInt($('#volume').val());
I have an input field that I am monitoring for changes using an .on('input') function as this covers .change and .keyup.
There is no submit button yet I just want to change the behaviour of the input field depending on what is entered.
I will validate server side later and I'm using html5 type='number'.
I only want the field to be able to hold a number, or it can be empty. The user might want to empty the contents to type the number 15 for example.
However I don't want any other characters to be accepted - if they are entered, a prompt should show notifying the user of this and the field is defaulted back to it's starting value of 1.
HTML
<input type="number" class="input-field" placeholder="" value="1" min="1">
JS
$(document).ready(function ($) {
var num = $('input[type="number"]').val();
$('input[type="number"]').on('input', function () {
var num = $(this).val();
if (num < 1 || isNaN(num) || num !== '') {
alert(num + ' is not a number or is less than 1');
$(this).val(1);
}
});
});
I have tried with the above code and it doesn't allow for an empty field. I've also tried if (num < 1 || isNAN(num) || num.length != 0) {
do I need to use .replace() with a Regexr. I've been looking at a few questions on here like here but I'm not sure thats what I'm looking for considering I'm testing for an empty string.
JSFIDDLE
You can use the constraint validation API:
$('input[type="number"]').on('input', function () {
if (!this.validity.valid) {
alert(this.value + ' is not a number or is less than 1');
this.value = 1;
}
});
$('input[type="number"]').on('input', function () {
if (!this.validity.valid) {
alert(this.value + ' is not a number or is less than 1');
this.value = 1;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" class="input-field" placeholder="" value="1" min="1">
However, note that this behavior is obtrusive. If an user types the wrong key, you will annoy him with a modal dialog and will clear the number.
Consider doing nothing. HTML5 browsers won't send the form if the input is not valid.
The HTML5 answer is definitely more elegant.
But if you want to offer more support, this is usually the route I take when trying to verify numbers.
Note that I am using data-min attribute but if you want to switch you can always use $.attr() to grab your min="" attribute.
$(document).ready(function ($) {
$('input[type="number"]').on('change', function () {
var min = parseInt(this.dataset.min),
num = isNaN(parseInt(this.value)) ? 0 : parseInt(this.value),
clamped = Math.max(num, min);
if(num != clamped) {
alert(num + ' is less than 1');
this.value = clamped;
}
});
});
jsfiddle
So i already have a textbox in which you can only enter numbers and they have to be within a certain range.The textbox defaults to 1,and i want to stop the user from being able to make it blank.Any ideas guys?Cheers
<SCRIPT language=Javascript>
window.addEventListener("load", function () {
document.getElementById("quantity").addEventListener("keyup", function (evt) {
var target = evt.target;
target.value = target.value.replace(/[^\d]/, "");
if (parseInt(target.value, 10) > <%=dvd5.getQuantityInStock()%>) {
target.value = target.value.slice(0, target.value.length - 1);
}
}, false);
});
<form action="RegServlet" method="post"><p>Enter quantity you would like to purchase :
<input name="quantity" id="quantity" size=15 type="text" value="1" />
You could use your onkeyup listener to check if the input's value is empty. Something along the lines of:
if(target.value == null || target.value === "")
target.value = 1;
}
You could add a function to validate the form when the text box loses focus. I ported the following code at http://forums.asp.net/t/1660697.aspx/1, but it hasn't been tested:
document.getELementById("quantity").onblur = function validate() {
if (document.getElementById("quantity").value == "") {
alert("Quantity can not be blank");
document.getElementById("quantity").focus();
return false;
}
return true;
}
save the text when keydown
check empty when keyup, if empty, restore the saved text, otherwise update the saved text.
And you could try the new type="number" to enforce only number input
See this jsfiddle
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Auto-format structured data (phone, date) using jQuery plugin (or failing that vanilla JavaScript)
Insert space after certain character into javascript string
I am trying to write a script that handles product keys like the ones you see on the back of software and games.
I would like so when the user is inputing their key code the '-' are inserted every 5 characters for 5 sets of characters. Ex(ABCDE-FGHIJ-KLMNO-PQRST-UVWXY). So when the user enters ABCDE as soon as the 'E' is enetered a '-' is inserted immeditly after via jQuery or JavaScript.
Thanks In Advance.
Comment if you have any questions or if I was unclear :)
Form:
<form method="post" action="process.php">
<p>Key: <input name="key" id="key" size="40"></p>
<p><input type="submit"></p>
</form>
You can use http://digitalbush.com/projects/masked-input-plugin/
jQuery(function($){
$("#key").mask("aaaaa-aaaaa-aaaaa-aaaaa-aaaaa");
});
HTML:
<fieldset id="productkey">
<input type="text" size="5" maxlength="5">
<input type="text" size="5" maxlength="5">
<input type="text" size="5" maxlength="5">
<input type="text" size="5" maxlength="5">
<input type="text" size="5" maxlength="5">
</fieldset>
JavaScript:
$( '#productkey' ).on( 'keyup', 'input', function () {
if ( this.value.length === 5 ) {
$( this ).next().focus();
}
});
Live demo: http://jsfiddle.net/XXLND/3/show/
You can also enhance the code, so that when the last text-box is filled out, a processing mechanism is activated:
$( '#productkey' ).on( 'keyup', 'input', function () {
var $field = $( this );
if ( $field.val().length === 5 ) {
if ( $field.is( ':last-of-type' ) ) {
$field.blur();
processKey();
} else {
$field.next().focus();
}
}
});
Live demo: http://jsfiddle.net/XXLND/4/show/
Simply because I don't like JQuery :)
function insertSpace(string, part, maxParts) {
"use strict";
var buffer = string.split("-"), step, i;
for (i = 0; i < buffer.length; i += 1) {
step = buffer[i];
if (step.length > part) {
buffer[i] = step.substr(0, part);
buffer[i + 1] = step.substr(part) + (buffer[i + 1] || "");
} else if (step.length < part) {
if (i == buffer.length - 1) {
if (!step) {
buffer.pop();
}
} else {
buffer[i + 1] = step + (buffer[i + 1] || "");
buffer.splice(i, 1);
i -= 1;
}
}
}
buffer.length = Math.min(maxParts, buffer.length);
return buffer.join("-");
}
How about using http://digitalbush.com/projects/masked-input-plugin
With that plugin, the following:
jQuery(function($){
$("#key").mask("99999-99999-99999-99999-99999",{placeholder:" "});
});
or, if your key is all letters use:
$("#key").mask("aaaaa-aaaaa-aaaaa-aaaaa-aaaaa",{placeholder:" "});
or, if it's alpha/numeric use:
$("#key").mask("*****-*****-*****-*****-*****",{placeholder:" "});
Here's one approach:
// binds to both the 'keyup' and 'paste' events
$('input:text').on('keyup paste', function(e) {
var that = $(this), // caches the $(this)
val = that.val(), // access the value of the current input
key = e.which, // determines which key was pressed
allowed = [8, 46, 9, 16]; // defines 'allowed' keys (for editing/focusing)
// backspace, delete, tab, shift
if ($.inArray(key, allowed) == -1) {
// if the pressed key is *not* an 'allowed' key
if (val.length == 5) {
// focuses the next element
that.next().focus();
}
else if (val.length > 5) {
// truncates the string, if greater than 5 characters
that.val(val.substring(0, 5));
that.next().focus();
}
}
});
JS Fiddle demo.
The advantage of this approach is that rather than masking or manipulating the entered string, and accounting for multiple edge-cases, you're simply aiding the user by moving the focus at the right point. And, in this case, also allowing the user to refocus the re-edit the previously entered data.
two things:
One the user experience side, I would avoid dynamically adding character in the input field as the user type a code. Depending on the environment you run the risk to interfere with what the user type.
However, the '-' helps user typing the code since this is a reference point for him. So I would suggest to have an input field and to show a pretty version of the code next to it (or make the field invisible and manage the focus of the field yourself).
For the php code, instead of adding a character every 5 characters I would do the opposite and simplify the code by removing all the unnecessary characters.
Something like that
if ( str_replace('-', '', $userInputKey)==str_replace('-', '', $officialKey) {
echo 'Yeah! Valid key!';
}
hi guys i have a html form where i have a textfield which is having capabilities to enter two digits the first digit is autopopulated to be 0 and i donot want users to change that hows that possible using javascript or jQuery or anything else.
Here is another way.
the onKeyUp might not be how you want it to work but at least you have some ideas
<script>
window.onload=function() {
document.getElementById('part2').focus();
}
</script>
<form onSubmit="this.realvalue.value='0'+document.getElementById('part2').value">
<input type="text" name="realvalue" value="">This can be hidden<br />
<input type="text" style="border-right:0; width:12px" value="0" readonly="readonly" size="1"><input type="text" id="part2" style="border-left:0; width:13px" size="1" maxsize="1"
onKeyUp="this.value=(this.value.length>1)?this.value.substring(-1):this.value">
<input type="submit">
You can use the event "keyup" triggered when the user enters text in the field:
$('#my-input').keyup(function() {
var theInputValue = $(this).val();
// Do whatever you want with the value (like check its length,
// append 0 at the beginning, tell the user not to change first
// character
//
// Set the real value
$(this).val(newValue);
});
You may be better off with a '0' as text in front of a textbox that can only accept a single digit and then prepend the '0' programmatically?
I wrote and tested this code, and works exactly as you expect:
$(function (){
$('#input_id').bind('input',function (){
var val = $(this).val();
var r = val.match(/^[0][0-9]$/g);
if (r !== null){
val = r[0];
if (val.length === 1){
val = '0' + val;
}
}else{
val = '0';
}
$(this).val(val);
});
});
And works for copy/paste too =]