0

I am using jQuery Keyup function but its not working for me

<script type="text/javascript"> 
        $(document).ready(function() {
            jQuery.noConflict();
          $("firstName").keyup(function(){
             alert("first Name");
         });   

</script>

<apex:form id="PrimaryTab"> 
<div>
 <label for="inputdefault">First Name</label>
 <apex:inputField value="{!le.firstName}" styleClass="form-control id="firstName" required="true"/>
</div>
</apex:form>
  • Check browser console if you getting any jQuery errors – Reshma Jan 23 '17 at 8:13
6

You're using JQuery before declaring jQuery.noConflict();

Also, this statement replace the $ variable by jQuery.

And finally, as Rahul just said in his answer, Salesforce add a prefix to the ids declared on your VF page.

So you should use:

<script type="text/javascript"> 
        jQuery.noConflict();
        jQuery(document).ready(function() {
          jQuery("input[id$='firstName']").keyup(function(){
             alert("first Name");
         });   
        });

</script>
  • Ah didn't catch jQuery.noConflict(), thanks! – Raul Jan 23 '17 at 8:22
  • 1
    Another thing missing is closing ready function. – Raul Jan 23 '17 at 8:39
  • Yes you're right! I missed that. – Martin Lezer Jan 23 '17 at 8:41
  • I believe class selectors are much better performance than ends with selectors, fyi. – Adrian Larson Jan 23 '17 at 19:51
  • Hi @AdrianLarson. I didn't know that. But what bother me is that class selectors are designed to be applied on multiple elements. Ids are designed to be unique. – Martin Lezer Jan 24 '17 at 7:44
4

In Salesforce, for visualforce components the HTML Id gets generated dynamically.

So you have to use ends with selector or use a class which is cleaner.

In your example, Try replacing:

$("firstName")

With:

$("input[id$='firstName']")
// or with 
$("[id$='firstName']")

Your script should be:

<script type="text/javascript"> 
    var $j = jQuery.noConflict();
    $j(document).ready(function() {
        $j("firstName").keyup(function(){
            alert("first Name");
        });   
    });
</script>

Refer this documentation to learn proper of use of noConflict() method.


Issues with your code:

  1. Improper use of jQuery.noConflict() - thanks @Martin Lezer for identifying this.
  2. Missed closing ready function - This is why indentation matters!
  3. Accessing Visualforce component with starts with selector or use a CSS class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.