1

I have a form with 2 fields. When all fields' values are filled, I need to display/show the Register button in hide stage. I am using jquery but it is not working. Where did I make a mistake?

   <apex:page standardController="pop__c">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script>
      var $ = jQuery.noConflict();
  (function() {
 // alert('hi);
  $('form > input').keyup(function() {

    var empty = false;
    $('form > input').each(function() {
        if ($(this).val() == '') {
            empty = true;
        }
    });

    if (empty) {

        $('input[id*=register]').attr('disabled', 'true');
    } else {
        $('input[id*=register]').removeAttr('disabled');
    }
  });
})()
  </script>

 <apex:form >

 FirstName:<apex:inputField value="{!pop__c.Name}" id="nid"/><br/>
 LastName:<apex:inputField value="{!pop__c.LastName__c}" id="fid"/>
 <apex:commandButton value="REGISTER" action="{!SAVE}"  disabled="true" id="register"/>
 </apex:form>
 </apex:page>
dphil
  • 6,185
  • 2
  • 36
  • 71
Sathya
  • 1,203
  • 3
  • 25
  • 53

1 Answers1

3

You can debug code like this by adding console.log as described in How do I start to debug my own Visualforce/JavaScript?.

A key thing with jQuery is to add the event handlers (such as keyup) after the Document Object Model (DOM) is constructed and the common pattern for that is to use the ready function. Your JavaScript was failing to add the keyup handler because at the time it ran the input elements were not in the DOM.

Your element matching of "form > input" only looks for input elements immediately inside form elements and Visualforce adds other elements in between. Using CSS classes is clearer and safer.

As well as changing the disabled attribute, to make the button's appearance change you have to add and remove the btnDisabled class.

This works:

<apex:page standardController="Account">    
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
(function() {
var j$ = jQuery.noConflict();
j$(document).ready(function() {
    j$('input.prerequisite').keyup(function() {
        console.log('keyup');
        var empty = false;
        j$('input.prerequisite').each(function() {
            if (j$(this).val() == '') empty = true;
        });
        if (empty) {
            j$('input[id*=register]').attr('disabled', 'true').addClass('btnDisabled')
        } else {
            j$('input[id*=register]').removeAttr('disabled').removeClass('btnDisabled')
        }
    });
});
})()
</script>              
    <apex:form>
       FirstName:<br/>
       <apex:inputField styleClass="prerequisite" value="{!Account.Name}" id="nid"/><br/>
       LastName:<br/>
       <apex:inputField styleClass="prerequisite" value="{!Account.Site}" id="fid"/><br/>
       <apex:commandButton value="REGISTER" action="{!SAVE}" disabled="true" id="register"/>
    </apex:form>
</apex:page>
Keith C
  • 135,775
  • 26
  • 201
  • 437