Miqdad Ali
Miqdad Ali

Reputation: 6147

JQuery or Javascript Input IP address mask

I have used jquery masked input plugin as per stackoverflow question

Input box for changing IP Address

but It didn't worked for me .

I have used it like $("input").mask("9?99.9?99.9?99.9?99", {placeholder:" "});

This demo (http://jsfiddle.net/3F2gM/3/ ) i found in previous question , but it didnt works

Upvotes: 2

Views: 25810

Answers (7)

Алексей
Алексей

Reputation: 31

function getChar(event) {
    if (event.which == null) {
        if (event.keyCode < 32) return null;
        return String.fromCharCode(event.keyCode)
    }

    if (event.which != 0 && event.charCode != 0) {
        if (event.which < 32) return null; 
        return String.fromCharCode(event.which); 
    }
    return null; 
}



function maskIP(e){
    let key = getChar(e);
    
    
    if((!((key >= 0 && key <= 9) || key == '.'))  || this.value.length >= 15) e.preventDefault();
    if (this.value.indexOf('.') == -1){
        if (this.value.length >= 3 && key != '.') {
            e.preventDefault();    
        }
    }
    else{
        if(this.value.lastIndexOf('.') == this.value.length - 1 && key == '.') {
            e.preventDefault(); 
        }
        if ((this.value.length - this.value.lastIndexOf('.') > 3 && key != '.') || (key == '.' && this.value.split(".").length - 1 >= 3)) {
            e.preventDefault();    
        }
    }
}


serch = document.getElementById("#id of your element"); //can use others
serch.addEventListener('keypress', maskIP);

Upvotes: 0

Rashad Aliyev
Rashad Aliyev

Reputation: 57

it works in my case.

var ip_options = { 
    translation: { 'Z': { pattern: /[0-9]/, optional: true } },
    onKeyPress: function(cep, event, currentField, options) {
        if(cep) {
            var ipArray = cep.split(".");
            for (i in ipArray){
                if(ipArray[i] != "" && parseInt(ipArray[i]) > 255){
                    ipArray[i] =  '255';
                }
            }
            var resultingValue = ipArray.join(".");
            $(currentField).val(resultingValue);
        }
    }
};

$('.ip_address').mask("0ZZ.0ZZ.0ZZ.0ZZ", ip_options);

Upvotes: 0

t_m27
t_m27

Reputation: 133

Joel Valdivia's answer doesn't make sure that each item in the ip array <= 255, and will824's answer doesn't allow for < 3 digits for an item.

Here is a complete example based on their answers that meets both criteria.

var options =  { 
    onKeyPress: function(text, event, currentField, options){
                    if (text){
                        var ipArray = text.split(".");
                        var lastValue = ipArray[ipArray.length-1];
                        if(lastValue != "" && parseInt(lastValue) > 255){
                            ipArray[ipArray.length-1] = '255';
                            var resultingValue = ipArray.join(".");
                            currentField.text(resultingValue).val(resultingValue);
                        }
                    }             
                },
    translation: {
            'Z': {
                pattern: /[0-9]/, optional: true
            }
    }
};

$(".ipaddr").mask("0ZZ.0ZZ.0ZZ.0ZZ", options);

Upvotes: 0

Joel Valdivia
Joel Valdivia

Reputation: 61

It worked for me this way:

First, I added jquery-mask in the html:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.10/jquery.mask.js"></script>

Then I typed the text field with the class .ip_address:

<label>ip:</label> <input class="ip_address" type="text" name="ip">

by last:

$('.ip_address').mask('0ZZ.0ZZ.0ZZ.0ZZ', { translation: { 'Z': { pattern: /[0-9]/, optional: true } } });

Upvotes: 6

sasi
sasi

Reputation: 534

This may help you:-
I have 4 input fields, each of its border was hided. Only the parent of the input field has the border, which will make it to look like a single text box. After that, allow the user to enter only 3 characters by using maxLength, once the user reached the maximum length, focus on to next field.
The code follows:- Link

HTML

<div>    
<input type="text" maxlength="3" class="onlythree" />.    
<input type="text" maxlength="3" class="onlythree" />.    
<input type="text" maxlength="3" class="onlythree" />.    
<input type="text" maxlength="3" class="onlythree" />    
</div> 

CSS

.onlythree{    
width: 50px;    
border: 0;    
}    
div{    
border: 1px solid gray;    
display: inline-block;    
}  

JS

$(".onlythree").keyup(function () {    
if (this.value.length == this.maxLength) {    
$(this).next('.onlythree').focus();    
}    
});  

Upvotes: 4

vakorovin
vakorovin

Reputation: 11

I solved the problem differently. In the above example, the only change is the last octet, I change everything, because for quick commissioning can enter numbers greater than 255. In addition, when viewed through firebug, the value is set in the input, and the displayed text is the same as the user enters.

HTML

<input type="text" name="vpn_ip" class="mask-ipv4" value="">

Java Script

var options =  { 
    onChange: function(cep, event, currentField, options){
        if(cep){
            var ipArray = cep.split(".");
            for (i in ipArray){
                if(ipArray[i] != "" && parseInt(ipArray[i]) > 255){
                    ipArray[i] =  '255';
                }
            }
            var resultingValue = ipArray.join(".");
            $(currentField).val(resultingValue);
        }
    }
};

$('.mask-ipv4').mask("000.000.000.000", options);

Upvotes: 1

will824
will824

Reputation: 2244

Actually I needed something similar to what you needed and what I did was to contact Igor Escobar, the author of Jquery Mask Plugin. There is not a complete built in way to do it yet, so he directed me to one option this could be accomplished and here I share the result:.

HTML

<input type="text" id="networkSectionIpAddress" class="ip_address" >

Javascript:

var options =  { 
            onKeyPress: function(cep, event, currentField, options){
//            console.log('An key was pressed!:', cep, ' event: ', event,'currentField: ', currentField, ' options: ', options);
                if(cep){
                  var ipArray = cep.split(".");
                  var lastValue = ipArray[ipArray.length-1];
                  if(lastValue != "" && parseInt(lastValue) > 255){
                      ipArray[ipArray.length-1] =  '255';
                      var resultingValue = ipArray.join(".");
                      currentField.attr('value',resultingValue);
                  }
            }             
        }};

        $('.ip_address').mask("000.000.000.000", options);

I hope this information is helpful for those using this great JQuery Mask plugin :)

Upvotes: 3

Related Questions