Search code examples
javascriptphphtmlformsvalidation

How to enable HTML validation for a disabled HTML input text field


How can I enable HTML validation for a disabled HTML input text field?

Here is my code:

<!--
<?php
my php code here...
?>
-->


<!DOCTYPE HTML>
<form action="">
    
<select name="0" required="" >
    <option name="1" value="1"> 1 </option>
    <option name="2" value="2"> 2 </option>
</select><br>  
<!--choosing or changing above select box will assign value to input box "5" (using javascript and php db)-->    
    
<input name="3" type="text" required="" ><br>
<input name="4" type="text" disabled="" ><br>
<input name="5" type="text" required="" disabled=""><br>
<input type="submit" >
</form>
</html>
 <!-- i want to force user to choose select box before submiting form -->   

I want the input field "5" to not be empty, and I don't want the user to edit the field manually, either.

Instead, when the user selects or chooses an item in dropbox, my JS and PHP will automatically assign a value to input field "5".

If the user submits the form without selecting an item from the dropbox, the dropbox value will be the default value, but since user hasn't clicked the dropbox, the JS will not work and no value will be assigned to input field "5", so the form will post empty or no value for input field "5".

Since input field "5" is set to disabled="", HTML validation is not working

JSFiddle demo (click the submit button to see that input field "5" is not validating)


Solution

  • You can add the option "Select" to the dropbox(name="0") as below mentioned code. so that you can validate the dropbox.

    <select name="0" required= >
      <option name="1" value="">Select</option>
      <option name="1" value="1"> 1 </option>
      <option name="2" value="2"> 2 </option>
    </select>
    

    Or you can add the default value to the input(name="4") as like below.

    <input name="5" type="text" required="" disabled="" value="1"><br>