Yasar Mahmood
Yasar Mahmood

Reputation: 48

allow people to only alter certain values in an input JavaScript

I have the following code

<input id="startDate "type="text" name="courseDate" value="MM/YYYY" />

I was wondering how I could use JavaScript to ensure that a user can only edit the "MM" and "YYYY" in the textbox.

Thanks Y

Upvotes: 1

Views: 84

Answers (5)

AnotherDeveloper
AnotherDeveloper

Reputation: 1272

Check out this jsfiddle below. It sounds similar to what you are trying to do:

http://jsfiddle.net/SO_AMK/SEXAj/

$("#date").mask("99/99/9999");

This is using the jQuery library.

Here is an example of the implementation:

<script type="text/javascript">//<![CDATA[ 
$(window).load(function(){
$("#date").mask("99/99/9999");
});//]]>  
</script>

Upvotes: 0

brso05
brso05

Reputation: 13232

You can do this with some javascript code like this (here is working fiddle):

function test1(e, input)
{
    var key = e.keyCode || e.charCode;
    console.log(key);
    if( key == 8 || key == 46 )
    {
        e.preventDefault();
        e.stopPropagation();
        setCursorPosition(input, (getCursorPosition(input) - 1));
        return false;
    }
}
function test(e, input)
{
    console.log("test");
    e.preventDefault();
    e.stopPropagation();
    var tempString = input.value;
    var cursorPosition = getCursorPosition(input);
    if(cursorPosition != 2)
    {
        tempString = "";
        for(var i = 0; i < input.value.length; i++)
        {
            if(cursorPosition != i)
            {
                tempString += input.value.charAt(i);            
            }
            else
            {
                var keynum;

                if(window.event){ // IE					
            	    keynum = e.keyCode;
                } else if(e.which){ // Netscape/Firefox/Opera					
            		keynum = e.which;
                }
                tempString += String.fromCharCode(keynum);
            }
        }
    }
    input.value = tempString;
    if(cursorPosition == 1)
    {
        setCursorPosition(input, (cursorPosition + 2));
    }
    else
    {
        setCursorPosition(input, (cursorPosition + 1));
    }
}
function getCursorPosition (oField) {

  // Initialize
  var iCaretPos = 0;

  // IE Support
  if (document.selection) {

    // Set focus on the element
    oField.focus ();

    // To get cursor position, get empty selection range
    var oSel = document.selection.createRange ();

    // Move selection start to 0 position
    oSel.moveStart ('character', -oField.value.length);

    // The caret position is selection length
    iCaretPos = oSel.text.length;
  }

  // Firefox support
  else if (oField.selectionStart || oField.selectionStart == '0')
    iCaretPos = oField.selectionStart;

  // Return results
  return (iCaretPos);
}

function setCursorPosition(elem, caretPos) {
    if(elem != null) {
        if(elem.createTextRange) {
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        }
        else {
            if(elem.selectionStart) {
                elem.focus();
                elem.setSelectionRange(caretPos, caretPos);
            }
            else
                elem.focus();
        }
    }
}
<input id="startDate "type="text" onkeydown="test1(event, this);" onkeypress="test(event, this);" name="courseDate" value="MM/YYYY" />

Some functions were taken from other posts:

here here here here

Upvotes: 0

Hayden Schiff
Hayden Schiff

Reputation: 3330

Here's some pseudocode outlining the process you'd want to use:

// save the initial value of the field so we know what the year is supposed to be set to
var initValue = document.getElementById("startDate").value;
var initValueSplit = initValue.split("/");

document.getElementById("startDate").onkeyup = function() {
    // get the value of whatever the user has entered
    var newValue = document.getElementById("startDate").value;
    // split the new value into an array, where 0th element is MM and 1st element is YYYY
    var newValueSplit = newValue.split("/");
    // rewrite the value of the field, using the user's version of the month and the saved version of the year
    var fixedValue = newValueSplit[0] + "/" + initValueSplit[1];
    // change the value of the field to fixedValue
    document.getElementById("startDate").value = fixedValue;
}

This will change the value of YYYY back to the original/starting value any time the user tries to change it.

Upvotes: 0

Razem
Razem

Reputation: 1441

It's not a good idea. Users can always disable JavaScript and you would have to deal with browser compatibility to get cursor position etc. It's much better to have two inputs with the dash between them (and maybe style them to look as one using wrapper):

<div id="startDate">
  <input id="startMonth" type="text" name="courseMonth" value="MM">/<input id="startYear" type="text" name="courseYear" value="YYYY">
</div>

Also it's usually better to have month (and maybe also the year) in select, not in text input. But that's not necessary.

Upvotes: 1

ImmortalPC
ImmortalPC

Reputation: 1690

Use html5 date input:

<input type="date" max="2012-06-25" min="2011-08-13" name="the_date">

http://www.alsacreations.com/xmedia/tuto/html5/elements-de-formulaire/input-type-date.php

Upvotes: 0

Related Questions