0

How to erase a element in html tag without changing other content ?

I am developing a simple calculator using only HTML. When a wrong number is entered like 827 when the button is pressed it should erase 7 and should show 82. How could I do it ? Thanks in advance.

25th Jul 2017, 6:04 PM
G.S.N.V. Suraj
G.S.N.V. Suraj - avatar
2 Antworten
+ 12
number = number.replace(/.$/,"");
25th Jul 2017, 6:42 PM
Valen.H. ~
Valen.H. ~ - avatar
+ 6
Assuming the wrong number is entered by user in an <input> element, and that you'll want to delete last character entered, the safer way (as you cannot easily know if cursor is at end of text field) is: <input type="text" id="myField" onchange="verif();"> <script> var old_value, field; // global variables window.onload = function() { // initialize the global variables field = document.getElementById('myField'); old_value = field.value; }; function verif(self) { /* verification code goes here and will be called each time the <input> value is modified */ if (!isValid(field.value) { // assuming a function returning true if valid value field.value = old_value; // undo the last user change if invalid value } else { old_value = field.value; } // save last user updated value if valid } </script> This is the simplest implementation... you can improve it and handle that stuff in a way where you can avoid global variables, even avoid the 'id' attribute as well as assign a function to event listener only dynamically (at run-time) to avoid surcharging your html code with event listener attributes ;)
26th Jul 2017, 7:41 AM
visph
visph - avatar