最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Auto insert colon while entering mac address after each 2 digit - Stack Overflow

programmeradmin2浏览0评论

I want to auto insert colon after every 2 digit in html inputbox using Java Script or jquery.

i pressed

00 then automatically insert colon like 00:

keep on continue up to 5 times like

00:00:00:00:00:00

I want to auto insert colon after every 2 digit in html inputbox using Java Script or jquery.

i pressed

00 then automatically insert colon like 00:

keep on continue up to 5 times like

00:00:00:00:00:00

Share Improve this question asked Apr 23, 2013 at 11:24 Maddy ChavdaMaddy Chavda 5916 gold badges11 silver badges20 bronze badges 3
  • Google "jquery mask plugin" and you'll find many plugins to do this. – Barmar Commented Apr 23, 2013 at 11:26
  • Thanks but it does not meet my requirement.... – Maddy Chavda Commented Apr 23, 2013 at 12:33
  • What have you tried? Stackoverflow isn't "Hey do this for me" it's "Hey I'm having trouble with this, what am I doing wrong?" – Colin DeClue Commented Apr 23, 2013 at 16:02
Add a comment  | 

7 Answers 7

Reset to default 13

Try this

<div id="dialog-message" title="Enter MAC address">
    <input id="macAddress" type="text" maxlength="17"></input>
</div>

var macAddress = $("#macAddress");

$(function () {
    $("#dialog-message").dialog({
        modal: true,
        buttons: {
            Ok: function () {
                $(this).dialog("close");
                alert("MAc address entered: " + macAddress.val());
            }
        }
    });
});

function formatMAC(e) {
    var r = /([a-f0-9]{2})([a-f0-9]{2})/i,
        str = e.target.value.replace(/[^a-f0-9]/ig, "");

    while (r.test(str)) {
        str = str.replace(r, '$1' + ':' + '$2');
    }

    e.target.value = str.slice(0, 17);
};

macAddress.on("keyup", formatMAC);

on jsfiddle

An here is the same thing in pure javascript without the jquery bells and whistles.

<input id="macAddress" type="text" maxlength="17"></input>

var macAddress = document.getElementById("macAddress");

function formatMAC(e) {
    var r = /([a-f0-9]{2})([a-f0-9]{2})/i,
        str = e.target.value.replace(/[^a-f0-9]/ig, "");

    while (r.test(str)) {
        str = str.replace(r, '$1' + ':' + '$2');
    }

    e.target.value = str.slice(0, 17);
};

macAddress.addEventListener("keyup", formatMAC, false);

on jsfiddle

You can use modulus to do that

you can try something like this

eg:

try this:

var length = 1;
$("#input").focusin(function (evt) {

    $(this).keypress(function () {
        var content = $(this).val();
        var content1 = content.replace(/\:/g, '');
        length = content1.length;
        if(((length % 2) == 0) && length < 10 && length > 1){
            $('#input').val($('#input').val() + ':');
        }    
    });    
});

http://jsfiddle.net/3NLDL/1/

This my version:

$('#MACADDRESS').keyup(function (e) {
  var r = /([a-f0-9]{2})/i;
  var str = e.target.value.replace(/[^a-f0-9:]/ig, "");
  if (e.keyCode != 8 && r.test(str.slice(-2))) {
    str = str.concat(':')
  }
  e.target.value = str.slice(0, 17);
});

It adds also ":" every two chars.

IngD

Improved this answer. The answer had a lot of flaws.

  1. Variable names that didnt make sense
  2. Messy code
  3. Outdated methods

Here's a demo.

$("#mac").on("keyup", function(event) {

  var limitField = $(this).val().trim().length;
  var limit = "17";

  if (event.keyCode != 8) {
      var mac_value = $(this).val().trim().concat(':');
      switch(limitField) {
          case 2:
          case 5:
          case 8:
          case 11:
          case 14:
              $("#mac").val(mac_value);
          break;
      }
   }
   if (limitField > limit) {
       $("#mac").val($(this).val().trim().substring(0, limit));
   }
});

This will limit the maximum characters to 17 and remove every character exceeding the limit. It will also add a colon : after every second character.

I am using this and working for me:

<input type="text" id="macaddress" onkeyup="doInsert(this)" maxlength="17"/>

<script type="text/javascript">
function doInsert(ctl)
{
    vInit = ctl.value;
    ctl.value = ctl.value.replace(/[^a-f0-9:]/ig, "");
    //ctl.value = ctl.value.replace(/:\s*$/, "");
    vCurrent = ctl.value;
    if(vInit != vCurrent)
        return false;   

    var v = ctl.value;
    var l = v.length;
    var lMax = 17;

    if(l >= lMax)
    {
        return false;
    }

    if(l >= 2 && l < lMax)
    {
        var v1 = v;     
        /* Removing all ':' to calculate get actaul text */
        while(!(v1.indexOf(":") < 0)) { // Better use RegEx
            v1 = v1.replace(":", "");           console.log('v1:'+v1);
        }

        /* Insert ':' after ever 2 chars */     
        var arrv1 = v1.match(/.{1,2}/g); // ["ab", "dc","a"]        
        ctl.value = arrv1.join(":");
    }
}
</script>

If anyone finds there way here, I found a lot of issues with the above answers, so I'm adding my own here. My criteria was as follows:

  • Able to spam (type quickly) letters and numbers and still insert colons in the correct positions
  • No phantom characters (some answers a letter would show and then disappear when it got spliced)
  • Able to backspace at any position (some answers, backspacing would ruin the formatting)
  • Reduced complexity
  • No regex
  • Does not exceed 17 characters

Originally I wrote this with Vue, but I'll provide a jquery version here.

$("#mac-input").on("keydown", function(event) {
  const BACKSPACE_KEY = 8
  const COLON_KEY = 186
  const _colonPositions = [2, 5, 8, 11, 14]
  const _newValue = $(this).val().trim()
  const _currentPosition = _newValue.length
  if (event.keyCode === COLON_KEY) {
    event.preventDefault()
  }
  if (event.keyCode !== BACKSPACE_KEY) {
    if (_colonPositions.some(position => position === _currentPosition)) {
      $("#mac-input").val(_newValue.concat(':'))
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="mac-input" maxlength="17" />

Mayur Please refer my example

http://jsfiddle.net/X5r8r/1167/

<input type="text" id="ip_address"/>

$("#ip_address").live("keyup", function(event) {
    var limitField = $(this).val().trim().length;
    var limit = "14"    
    if (event.keyCode != 8) {
      if (limitField == 2) {
          var fax_value = $(this).val().trim().concat(':');
        $("#ip_address").val(fax_value);
      } else if (limitField == 5) {
          var fax_value = $(this).val().trim().concat(':');
        $("#ip_address").val(fax_value);
      }else if (limitField == 8) {
          var fax_value = $(this).val().trim().concat(':');
        $("#ip_address").val(fax_value);
      }else if (limitField == 11) {
          var fax_value = $(this).val().trim().concat(':');
        $("#ip_address").val(fax_value);
      }
    }
    if (limitField > limit) {
        $("#ip_address").val($(this).val().trim().substring(0, limit));
    }
});
发布评论

评论列表(0)

  1. 暂无评论