grey out submit button until form filled out

2019-03-27 15:26发布

I have the following form:

 <form action="http://www.tahara.es/contact/subscribe.php" method="post" id="subscribe" name="subscribe">
      <input type="hidden" name="action" value="subscribe">
      <label>NAME:</label>
      <input type="text" name="name" class="Textbox" id="sub_first_name">
      <label>EMAIL:</label>
      <input type="text" name="email" class="Textbox" id="sub_email">
      <input type="submit" name="button" id="button" value="Subscribe" />

I would like to grey out the submit button until both fields in the form have been filled out. I guess jquery would do the trick?

How can I do this, and where should I place the script?

3条回答
我欲成王,谁敢阻挡
2楼-- · 2019-03-27 15:37

If you are a beginner of javascript, a better option would be

Add HTML as follows

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
   First name: <input type="text" name="fname">
   <input type="submit" value="Submit">
</form>

Now add validateForm() as

function validateForm() {
   // Validate all fields in the form
   return true; // if all form entries are valid. else return false
}

Note: This will not grey-out the submit button. But in this case submit will work only if all the entries are valid.

查看更多
再贱就再见
3楼-- · 2019-03-27 15:51

The script would go in the <head></head> of your document. Like so.

<script type="text/javascript" src="yourpath"></script>

One way would be to match the values of the inputs and then remove the grayed out class from your button if the values aren't still the same as the default. Here is a demo.

HTML

<input type="text" value="some text" class="text-input">
<input attr="" type="submit" value="submit" class="submit">

CSS

.disabled {opacity:.2;}

jQuery

if ($('.text-input').val() == "some text" ) {
    $('.submit').addClass('disabled');    
}

http://jsfiddle.net/APGmy/11/

查看更多
Emotional °昔
4楼-- · 2019-03-27 15:58

Jquery would do that. On the .keyup event have jquery check if both field's lengths are > 0 and change the button to be disabled or not.

$('#yourButton').button("disable");​​​​​​​​​​​​​

$('.fields').bind('keyup', function() { 
var nameLength = $("#sub_first_name").length;
var emailLength = $("#sub_email").length;

if (nameLength > 0 && emailLength > 0)
{
   $('#yourButton').button("enable");​​​​​​​​​​​​​
}

} );
查看更多
登录 后发表回答