Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

disable textbox using javascript

As the title says, i am, trying to disable textbox when i open the file

<form name='registration' action="registration.php" method="post" onSubmit="return formValidation();">
    <table>
        <tr>
            <td>FirstName:</td>     
            <td><input type = "Text" name = "firstname" id="1"></p></td>
        </tr>
    </table>
</form>

and I try ti disable it using the following javascript code:

function formValidation() {
    var fn = document.registration.firstname;
    if(fname_validation(fn)) {}
    document.getElementById("1").disabled = true;
}

function fname_validation(fn) {
    var fn_len = fn.value.length;
    var fn_char = /^[A-Za-z]+$/;
    if (fn_len == 0) {
        alert("first name cannot empty");
        return false;
    }
    if (!fn.value.match(fn_char)) {
        alert("first name must enter alphabet only");
        return false;
    } else {
        return true;
    }
}

Why the text box still does not disable?

like image 560
Asker Avatar asked May 29 '26 10:05

Asker


1 Answers

Right now, the function that make your input disabled is called on form submit. So, your input will be disabled only when you submit your form... probably too late.

If you want to disable your input from start, your input should look like this

<input type="Text" name="firstname" id="firstname" disabled="disabled" />

Or if you want to disable it with javascript, you have to execute it on load. Something like this:

window.onload = function() {
  document.getElementById('firstname').disabled = true;
};
like image 86
service-paradis Avatar answered May 31 '26 22:05

service-paradis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!