문제

I have several input fields that should have only numbers as valid input, so after search the SO, I got the following js code to allow only number to be input to a text field which is working quite well.

function onlyNumbers(evt) {
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;
    key = String.fromCharCode( key );
    var regex = /[0-9]|\./;
    if( !regex.test(key) ) {
        theEvent.returnValue = false;
        if(theEvent.preventDefault) theEvent.preventDefault();

        // the corresponding span to make it visible here
        // What code to put here ?

    }
}

The corresponding html is

<input type="text" id="age1" onkeypress="onlyNumbers(event)" />
<input type="text" id="mobileNo" onkeypress="onlyNumbers(event)" />

Now, I have a hidden span after each such input text, which I would like to display as soon as a invalid character is typed ? As there are many such fields

e.g. age1, age2, mobileNo, each one has it's own sibling span. So, when age1 input is wrong it's corresponding error message span should get displayed.

Here is the minimal complete html code for reference

<form method="POST" action="action.php">
    ...
<li>Age of person 1 :
    <input type="text" id="age1" onkeypress="onlyNumbers(event)" />
    <span class="error_msg age1"> Only numbers please </span> 
</li>
<li>Age of person 2 :
    <input type="text" id="age2" onkeypress="onlyNumbers(event)" />
    <span class="error_msg age2"> Only numbers please </span> 
</li>
<li>
    <input type="text" id="mobileNo" onkeypress="onlyNumbers(event)" />
    <span class="error_msg mobileNo"> Only numbers please </span> 
</li>
...
</form>

How to get the reference of the element from which the onlyNumbers() function was called? And how to make the corresponding span visible? Any ideas ?

도움이 되었습니까?

해결책

 var fld = theEvent.target || theEvent.srcElement;

Here you can access ID or sibling node

If you instead or as well pass (this) you have your field

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top