-3

I created an input field (text) on a website with the default value "DE". Now i'm having the following problem.

<input type="text" id="iban" value="DE" />

When the user clicks in the textbox the default value "DE" should not be deleted and the user should only add numbers after the default value in the textbox. So i'm searching for a js function which makes the default value of a textbox as readonly. The user should not delete the default value.

If this is possible, how does it work?

proud
  • 53
  • 2
  • 8
  • I don't want that the value will be deleted on focus. I'm searching for a function where i can mark a part of a textbox as read only. And yes i searched for it, but I didn't found a solution for this. – proud Apr 24 '13 at 07:01
  • Thx, i will try this Danny Beckett. – proud Apr 24 '13 at 07:04

3 Answers3

5

You can't make a part of the value as read-only... But if you want to use a simple solution (without javascript) you could use two inputs :

<input type="text" id="iban-prefix" value="DE" readonly/><input type="text" id="iban-value"/>

Arrange them using css and just concat the two values in your sever side.

OR :

A javascript solution : on your form use the "onsubmit" event to call a javascript function to check if the "DE" prefix is present in the value entered by the user and if not, add the "DE" prefix.

Hope this helps !

Antoine
  • 548
  • 4
  • 13
2

There is no need to use JavaScript. Simple HTML and CSS will do the job just fine.

Move DE into a <span> to the left of your <input>:

<span class="iban">DE</span><input type="text" id="iban" />

Then position the <span> inside the <input>:

span.iban
{
    position: relative;
}

input#iban
{
    margin-left: -25px;
    padding-left: 25px;
}

The above code produces:

Here's a JSFiddle.

Danny Beckett
  • 20,529
  • 24
  • 107
  • 134
-2

You can try this jQuery:

$(document).ready(function() {
    $("#iban").keydown(function(event) {

            if (event.keyCode < 48 || event.keyCode > 57 || event.keyCode == 46 || event.keyCode == 8) {
                event.preventDefault(); 
            }   

    });
});

I found it here: https://snipt.net/GerryEng/jquery-making-textfield-only-accept-numeric-values/

EDIT: And modify it to prevent backspace and delete keys.

A working fiddle

Hope it helps!

Arkana
  • 2,831
  • 20
  • 35