if input has reached 7 digits, stop the function - javascript

So basically I have a button .button, which adds a number to my input #number everytime it's pressed.
Now, when I already have 7 digits in my input #number, I want the function to like 'stop working'.
Here is my code (works fine):
function nrtwo(hello){
var das = $(hello).html();
var tempNum = $("#number").val();
$("#number").val(tempNum + '' + das);
tempNum = null;
};
$(".button").click(function(){
nrtwo(this);
});
I was thinking of something like this?
if ($("#number").attr('maxlength') == '7') {
return false;
}
Thanks for the help.

Try this .length it is a Number and unblind click event when you reach 7 digits :
Working jsFiddle
$(".button").click(function(){
if ($("#number").val().length == 7) {
$(this).unbind('click');
return false;
}else{
nrtwo(this);
}
});

You need to handle this scenario in the click event itself. Please see the following example:
$(".button").click(function(){
if ($("#number").val().length <= 7) {
nrtwo(this);
}
});
This will only call the nrtwo method only when the input's length is less than or equals to 7.

If you are handling numbers only, you can also check the numeric value before adding to it.
$('#add').click(function() {
var value = parseInt($('#output').val());
if(value <= 999999) {
$('#output').val(value + 1);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="add">Add</button>
<input type="text" id="output" value="999995" />

$('#number').keypress(function(event){
var n = $(this).val();
if(n.length == 7){
event.preventDefault(); //stop character from entering input
}
if(event.which != 8 && isNaN(String.fromCharCode(event.which))){
event.preventDefault(); //stop character from entering input
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<input id="number"/>

One method is to use .length property.
Please try this:
if ($("#number").val().length == '7') {
return false;
}
$('#add').click(function() {
if ($("input").val().length != '7') {
$('input').val(parseInt($('input').val())+1);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" value="999998"/>
<button type="button" id="add">Add</button>

Related

If input maxlength is reached do something

I have a maxlength of 11 for an input field. I would like to perform a jQuery function when the maxlength has been met and the user keeps trying to type, so instead of it not doing anything, it'd show a message.
Please could you give me some pointers?
Thanks in advance!
Try this: IT will alert a message when the user hits 11 characters.
$("input").on("keyup",function() {
var maxLength = $(this).attr("maxlength");
if(maxLength == $(this).val().length) {
alert("You can't write more than " + maxLength +" chacters")
}
})
Demo
$("input").on("keyup",function() {
var maxLength = $(this).attr("maxlength");
if(maxLength == $(this).val().length) {
alert("You can't write more than " + maxLength +" chacters")
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input maxlength="11" />
try this code
$(document).ready(function() {
$("#text").keypress(function(e) {
var length = this.value.length;
if (length >= 11) {
e.preventDefault();
alert("not allow more than 11 character");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text">
You are looking for something like:
$("input").keypress(function(e){
if(e.target.value.length==11){
alert("maxlength reached");
}
});
Obviously change to use the correct selector and alert/modal popup.
$(document).ready(function(){
$("input").keyup(function(){
var a = $(this).val().length;
if(a >= 11){
$(this).attr('maxlength','11')
alert("not allowed")
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input>
If you add the $(document) it will find all the inputs with maxlength attribute, even if you have created them after loading the page.
$(document).on("input keypress", "input[maxlength]", function (e) {
var $input = $(e.currentTarget);
if ($input.val().length >= $input.attr("maxlength")) {
alert("Max length reached")
}
});
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<input>

Check the length of the number entered in a textbox

I want to write in text box and check if is integer and less than 16 numbers. I have the following JavaScript codes.
<script type="text/javascript">
function doCheck(field) {
if (isNaN(document.getElementById(field).value)) {
alert('this is not a number');
document.getElementById(field).focus();
document.getElementById(field).select();
return false;
}
else {
return true;
}
}
</script>
<form method="post" action="" onsubmit="return doCheck('number');">
national id=<input type="text" name="nat" id="number">
<input type="submit" name="submit">
</form>
document.getElementById(field).value.length
you can find the length of string inside the text box using this
function doCheck(field) {
var len = document.getElementById("number").val().length;
if(parse.Int(document.getElementById(field).value) && len < 16) {
return true;
}
else {
alert('your alert');
document.getElementById(field).focus();
document.getElementById(field).select();
return false;
}
}
be sure you parse it as an integer.
function doCheck(field) {
var input_value = document.getElementById(field).value;
if(isNaN(input_value) || parseInt(input_value,10) != input_value || input_value.length < 16) {
alert('this is not a number');
document.getElementById(field).focus();
document.getElementById(field).select();
return false;
}
else{
return true;
}
}
isNAN() checks whether a number is an illegal number of any type, not only integer. So you have to use something else there, a regular expressions maybe.
To get the length of the field you can simply use:
document.getElementById(field).value.length

How to change the value of an active text input using Javascript?

I am trying to make a form with a date input.
However, this input is in date format, and I would like to change the value while the control is still active.
Here is the full code :
// Javascript code
function add_value()
{
var dataoriginale = document.getElementById("fin_mater").value;
if(document.getElementById("fin_mater").value.length = 2)
{
document.getElementById("fin_mater").value=dataoriginale+'-';
}
else if(document.getElementById("fin_mater").value.length = 5)
{
document.getElementById("fin_mater").value=dataoriginale+'-';
}
}
<!-- Code of the input -->
<input id="fin_mater" type="text" onchange="add_value();" name="fin_mater" maxlength="10" placeholder="DD-MM-YYYY"/>
But this is only updating the text when you exit of the control, and I would like to know how to run this javascript function while the control is still active.
Thanks.
You need to use onkeyup.
<input id="fin_mater" type="text" onkeyup="add_value();" name="fin_mater" maxlength="10" placeholder="DD-MM-YYYY"/>
From the docs
Execute a JavaScript when a user releases a key
Also in your if your are using =, you should be using ==
...
if(document.getElementById("fin_mater").value.length == 2)//==
...
else if(document.getElementById("fin_mater").value.length == 5)
...
First let's make the code smell more like the "javascript" :)
// Javascript code
function $(id) {
return document.getElementById(id);
}
function add_value(event) {
var dataOriginale = $("fin_mater").value,
len = dataOriginale.length,
key = event.keyCode || event.charCode;
// Allow BACKSPACE and DEL
if (key === 8 || key === 46) {
return true;
}
if(len === 2 || len === 5) {
$("fin_mater").value = dataOriginale + '-';
}
return false;
}
<!-- Code of the input -->
<input id="fin_mater" type="text" onKeyUp="add_value(event);" name="fin_mater" maxlength="10" placeholder="DD-MM-YYYY"/>
If you want to append the "-" automatically when you input numbers, you can listen on the "onKeyUp" event of the text box rather than the "onchange".
PS: You can use the key code to limit only numbers input and also do some validations.
You can use keypress():
$(document).ready(function()
{
$( "#fin_mater" ).keypress(function() {
var dataoriginale = document.getElementById("fin_mater").value;
if(document.getElementById("fin_mater").value.length == 2)
{
document.getElementById("fin_mater").value=dataoriginale+'-';
}
else if(document.getElementById("fin_mater").value.length == 5)
{
document.getElementById("fin_mater").value=dataoriginale+'-';
}
});
});
Fiddle
With some of your help and some documentation, I finally went to this, that works perfectly on every browser that supports javascript.
$(document).ready(function(event)
{
$( "#fin_mater" ).keypress(function(event) {
var dataoriginale = document.getElementById("fin_mater").value;
if(event.keyCode != 8)
{
if(document.getElementById("fin_mater").value.length == 2)
{
document.getElementById("fin_mater").value=dataoriginale+'-';
}
else if(document.getElementById("fin_mater").value.length == 5)
{
document.getElementById("fin_mater").value=dataoriginale+'-';
}
}
});
});
Thanks everyone !

html input field set range

What is the most efficient way to set the range for an input-field to -100.0 to 100.0? I would like to check every character. Other characters than -,0,1,2,3,4,5,6,7,8,9 and . are not allowed. Values without floating point, e.g. 78, are also possible.
UPDATE
I need a solution for IE, so html5 solution with type="range" or type="number" are useless for me.
The only code I have is the input field:
<input type="text" id="zahlenwert" value="" />
The question is: Do I have to check every character with onKeydown() or is there a smarter way?
Here is what you are looking for:
http://jeroenvanwarmerdam.nl/content/resources/javascript/jquery/spincontrol/jquery-spincontrol-1.0.zip
And here is example:
http://jeroenvanwarmerdam.nl/content/resources/javascript/jquery/spincontrol/jquery-spincontrol.html?x=31&y=10
Integration:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="jquery-numeric.js"></script>
<script type="text/javascript" src="jquery-number-selector.js"></script>
<script type="text/javascript" src="jquery-spincontrol-support.js"></script>
<script type="text/javascript" src="jquery-spincontrol.js"></script>
<!-- SpinControl definition -->
<script type="text/javascript">
(function($) {
$(function() {
$(":number").addClass("number").spinControl({ folder: "images/" });
});
})(jQuery);
</script>
Here is your body html code:
<input type="number" max="10" min="-10" step="0.5" />
I'm partly guessing at your requirements but if you're just trying to restrict the input value to a number within a specific range you could use HTML5's range input type:
<input type="range" name="myrange" min="-100" max="100">
Or use JavaScript to validate the value like in this demo fiddle:
document.getElementById('test').onchange = isNumber;
function isNumber(){
var val = this.value;
var aNumber = !isNaN(val);
var aNumberNotOverOneHundred = (Math.abs(parseFloat(val, 10)) <= 100);
alert((aNumber && aNumberNotOverOneHundred)?"Yarp":"Narp");
}
Or use input pattern attribute to validate against a regex pattern.
This is the solution I wanted:
$(document).ready(function() {
$("input#zahlenwert").keyup(function(){
var zahlenwert= $("input#zahlenwert").val();
var status = 0;
for(i=zahlenwert.length;i>0;i--){
if(status==0){
if(zahlenwert.length == 0){
}
else if(zahlenwert.length == 1 && zahlenwert.match(/^(-|[0-9]) /)!=null){
status = 1;
console.log("zahlenwert ok");
}
else if(zahlenwert.length == 2 && zahlenwert.match(/^(-[0-9]|[0-9],|[1-9][0-9])/)!=null){
status = 1;
console.log("zahlenwert ok");
}
else if(zahlenwert.length == 3 && zahlenwert.match(/^(-[1-9][0-9]|[0-9],[0-9]|100|[1-9][0-9],|-[0-9],)/)!=null){
status = 1;
console.log("zahlenwert ok");
}
else if(zahlenwert.length == 4 && zahlenwert.match(/^(-100|100,|[1-9][0-9],[0-9]|-[0-9],[0-9]|-[1-9][0-9],)/)!=null){
status = 1;
console.log("zahlenwert ok");
}
else if(zahlenwert.length == 5 && zahlenwert.match(/^(100,0|-100,|-[1-9][0-9],[0-9])/)!=null){
status = 1;
console.log("zahlenwert ok");
}
else if(zahlenwert.length == 6 && zahlenwert.match(/^-100,0/)!=null){
status = 1;
console.log("zahlenwert ok");
}
else{
zahlenwert = zahlenwert.substring(0,zahlenwert.length-1);
$("input#zahlenwert").val(zahlenwert);
console.log("Error!!!");
}
}
}
});
});

If input box contains certain number of characters

<input type="text"/> <button>Go</button>
<div id="example">
</div>
How can I .append "Blah" in #example if input contains 5 characters when button is clicked, and .append "Other" if it doesn't?
var example = $('#example'); //get example div
var input = $('input').get(0); //get first input in the set of inputs
$('button').click(function(){ //bind click handlers to (any) button
var value = input.value; //get the (first) input's value
if(value.length === 5){ //check the value
example.append('Blah');
} else {
example.append('Other');
}
});
$('button').click(function() {
var $example = $('#example');
if ($('input').val().length == 5) {
$example.append('Blah');
} else {
$example.append('Other');
}
});
http://jsfiddle.net/zerkms/cks45/
$(function(){
$('button').click(function(){
if($('input').val().length == 5){
$('#example').append('blah');
}else{
$('#example').append('Other');
}
});
});
Pure JS way
var butt = document.getElementsByTagName("button")[0],
input = document.getElementsByTagName("input")[0],
example = document.getElementById("example");
butt.onclick = function(){
if(input.value.length == 5){
example.textContent += "blah";
}else{
example.textContent += "other";
}
}
​
Live Demo
​
$('button').on('click',function() {
$('#example').text(
$('#example').text() +
($('input[type=text]').val().length==5?'Blah':'Other')
);
} );
If you didn't want to use jquery you could do...
HTML
<input id="input1" type="text"/> <button onclick="go('input1')">Go</button>
<div id="example">
</div>
JavaScript
function go(inputId){
document.getElementById("example").innerHTML += document.getElementById(inputId).value.length === 5 ? "bla" : "other";
}
This involved changing the HTML to include an id for the input and an onclick event handler for the button.

Categories

Resources