Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    New to the CF scene
    Join Date
    Aug 2013
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Checking if a button exists

    Hi folks,

    I have a .js file that is invoked by a few .jsp pages. What I need to do in this particular .js file is to invoke a certain function only if the 'save' button is present in the .jsp page. How do I check if the the button exists? Currently in the .js file the button is refered to this way: $('button[id=save]')

    How do I check if such a button exists? Hope someone can advise. Thanks

  • #2
    The fat guy next door VIPStephan's Avatar
    Join Date
    Jan 2006
    Location
    Halle (Saale), Germany
    Posts
    8,777
    Thanks
    6
    Thanked 1,021 Times in 994 Posts
    First of all, you should use the ID selector to address elements by ID. That means the button should be referenced with $('#save') or, if there might be other elements with such an ID $('button#save').

    Then, to check if an element exists you do this
    Code:
    if($('#save').length) {
      …
    }

  • #3
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,399
    Thanks
    11
    Thanked 595 Times in 575 Posts
    Quote Originally Posted by VIPStephan View Post
    or, if there might be other elements with such an ID $('button#save').
    did you try that snip? i'm pretty sure jquery only grabs one element if you use "#" in the selector, but the OP's attrib-syntax should work just fine for multiple IDs...

    to make that a condition, just check the length:

    Code:
    if( $('button[id=save]').length ){
      alert("save button there");
    }
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.6, IE11:9.1, IE9:3.1, IE10:3.0, FF:17.2, CH:46, SF:11.4, NON-MOUSE:38%

  • #4
    The fat guy next door VIPStephan's Avatar
    Join Date
    Jan 2006
    Location
    Halle (Saale), Germany
    Posts
    8,777
    Thanks
    6
    Thanked 1,021 Times in 994 Posts
    Quote Originally Posted by rnd me View Post
    i'm pretty sure jquery only grabs one element if you use "#" in the selector
    Of course. Multiple IDs in one document aren’t allowed anyway. But I assumed the script is referenced in multiple documents and in one page there might be a div with the same ID as a button in another. But you only want to execute the script if the button exists. Makes sense?

  • #5
    New to the CF scene
    Join Date
    Aug 2013
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thanks guys, managed to solve it based on the info given by you all. Thanks once again.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •