Martynas
Martynas

Reputation: 2565

Add text to <input> element but don't delete it

I have an <input> html element. The element is filled by default value. User should be able to append new text at the end of default text but could not delete default value. How could I solve this problem?

Upvotes: 2

Views: 3099

Answers (4)

JacobTheDev
JacobTheDev

Reputation: 18520

If you don't want to do some complex JS you could just use background images with some padding.

Upvotes: 0

jmakila
jmakila

Reputation: 41

You could also compare the input value to a regex pattern on keydown event. You can then deny the keypress, for instance a backspace, if the regex didn't match.

Upvotes: 0

Nick Beranek
Nick Beranek

Reputation: 2751

You can do this with JavaScript:

listen('load', window, init);

function init() {
  var test = document.getElementById('test');
  var val = test.value;
  listen('keydown', test, replaceVal);
  listen('keyup', test, replaceVal);
  function replaceVal() {
    tempVal = test.value;
    if (tempVal.indexOf(val) === -1) {
      tempVal = val;
      test.value = val;
    }
  }
}

function listen(event, elem, func) {
  if (elem.addEventListener) {
    elem.addEventListener(event, func, false);
  } else if (elem.attachEvent) {
    elem.attachEvent('on' + event, func);   
  }
}

I have set up a jsFiddle here: http://jsfiddle.net/sjfwz/

Upvotes: 3

Jignesh Rajput
Jignesh Rajput

Reputation: 3558

try this

script :

   <script type="text/javascript">
    function MyFunction() {

        document.getElementById('TextBox3').value = document.getElementById('defaultValue').value;

        //if asp:textbox control should be work below
        document.getElementById('<%=TextBox4.ClientID%>').value = document.getElementById('defaultValue').value;

    }

</script>
    }


<body onLoad="javascript:MyFunction();">
<input type="hidden" id="defaultValue" name="defaultValue" value="defaultValue"/>
<input type="text" id="TextBox3" />
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
</body>

Upvotes: 0

Related Questions