always want to keep first digit of my textfield as 0 - javascript

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 =]

Related

regex to replace non numeric

I want to replace all my non numeric characters with an empty string. I found this solution
I am trying to replace the value of an input element on change. But when I use above, it is not replacing until I press a number.
Each non-digit I type stays until I type a digit
Ex: 2aaaaa will not be replaced. But as soon as 2aaaa3 is typed it will replace all the a's and it becomes 23
Is this the normal behaviour? How can I achieve my requirement.
component.ts
mobileChanged = () => {
this.mobile = this.mobile.replace(/\D/g,'');
};
angular component.html
<input type="text" [(ngModel)]="mobile" (ngModelChange)="mobileChanged()">
You can use keyup from jQuery or onkeyup from Javascript.
$("document").ready(function() {
$("input").keyup(function() {
let v = this.value.replace(/\D/g, '');
this.value = v;
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" value="" />
Yes, it's the usual behaviour for ngModelChange but seems you need onkeyup event here to replace Non-digits. Something like-
function mobileChanged() {
var txtinput = document.getElementById("fname");
var x = txtinput.value.replace(/\D/g,'');
txtinput.value = x;
}
<input id ="fname" type='text' onkeyup="mobileChanged()">
See if you still have confusion: https://stackoverflow.com/a/46403258/1138192

if user input length = x , btn.click() function

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

if input field is not a number OR not empty replace with a number

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

press button and value increases in text box

So when the page loads the text box will contain a stored value. I want the user to press the '+' button and the value in the text box will increase by one. Im guessing this is done with JQuery...Any ideas on where to get started so far I have...
<input type="text" name="BoqTextBox" id="BoqTextBox" value="0" />
<input type="Button" value="+" onclick="AddOne(document.getElementById('BoqTextBox').value)" />
<script>
function Add(data) {
//so the current digit is passed to here, where I need to do some funky code
//where it increments the current digit by one and stores it in BoqTextBox - replacing the old digit.
//Also to note if the text box contains 124.54 for example and + is pressed
//then new value will be 125.54
}
</script>
Any assistance with this would be great.
Thank you
...something like data = data + 1, but then how do I return the value into the text box?
You can use jQuery's val() to fetch and set a value. In this case the code you need could look like this (demo):
<input type="text" name="BoqTextBox" id="BoqTextBox" value="0" />
<input type="Button" id='AddButton' value="+" />
<script>
$('#AddButton').on('click', function () {
var input = $('#BoqTextBox');
input.val(parseFloat(input.val()) + 1);
})
</script>
$('input[type="button"]').on('click', function() { // bind click event to button
$('#BoqTextBox').val(function() { // change input value using callback
return ++parseFloat( this.value, 10); // make value integer and increment 1
})
});
you are callin Addone function inline so that means your function should be AddOne()
try this
function AddOne(obj){
var value=parseFloat(obj) + 1;
$('#BoqTextBox').val(value);
}
$("#buttonId").click(function()
{
var txtBox = $("#boqtextbox");
if(!isNaN(txtBox.val()))
{
txtBox.val(parsFloat(txtBox.val())+1) ;
}else
{
//do validation or set it to 0
txtBox.val(0);
}|
});

Insert '-' every 5 characters as users type [like a product key] [duplicate]

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!';
}

Categories

Resources