简体   繁体   中英

Disable form fields until a previous field has been filled with JavaScript

Using JavaScript; can we set the other textfield to be dependent to the first or previous textfield?

For example, if we have a first name and surname field, I want to disable the surname field until a value has been entered for first name.

I made a fiddle you can look at: http://jsfiddle.net/phillipkregg/7bkrn/2/

It's not perfect, but it will give you something to play around and practice with. If you leave the "First Name" field without filling it out, it locks the "Last Name" field.

If you want to use JQuery, this is one way to do the javascript:

 $(document).ready(function() {

     $("#first_name_field").focus();

     var error_message = "Please add first name.";

      $("#first_name_field").blur(function() {
          if ($(this).val() != '')
          {
              $("#surname_field").removeAttr("disabled");    
              $("#message").html("");      
          }
     else {              
              $("#surname_field").attr("disabled", "disabled");  
              $("#message").append(error_message);      
          }         

      });
 });​

If you plan to use validations (which you should) than you should look at a plugin called JQuery Validation - http://docs.jquery.com/Plugins/Validation

I just made a quick one here to show you one way to do it.

try with this code.

<input type="text" name="fname" id="fname" onkeyup="check()" />
<input type="text" name="lname" id="lname" disabled="disabled"  />

JavaSCript

function check() {
if(document.getElementById('fname').value != "")
    document.getElementById('lname').disabled = false;
else
    document.getElementById('lname').disabled = true;
}

Already. You can use "readonly" property of "input" html tag and "onChange" event (for example) with JavaScript. This is only client side functionality. Don't use php for this purposes).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM