-6

Here is the DOM :

<div class="form-actions">
<button class="btn btn-primary" type="submit">Save device</button>
</div>

I want to use Jquery to select the button and click on it? I tried using : jQuery(".btn btn-primary").click() which is not working

user3397379
  • 111
  • 1
  • 2
  • 6

6 Answers6

6

You are trying to select an element with both classes, therefore your selector should be .btn.btn-primary.

$('.btn.btn-primary').click();

You were trying to select a element with class .btn-primary that was a descendant of a .btn element.

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
  • 1
    Incidentally, the OP's selector `.btn btn-primary` doesn't reference a class named "btn-primary" due to the lack of a preceding dot. – showdev Apr 09 '15 at 20:44
3

Your selector is incorrect; because both classes are on the same element you need to separate them by . with no spaces:

jQuery(".btn.btn-primary").click()
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
3

You could use the jQuery trigger() method to trigger the behaviour of an existing event handler.

https://api.jquery.com/trigger/

example:

<button id='testButton'>Test</button>

<script>
$(function(){
   $('#testButton').on('click' , function(){
        alert("I've been clicked!");
   });

   //now on another event, in this case window resize, you could trigger
   //the behaviour of clicking the testButton?

  $( window ).resize(function() {
        $('#testButton').trigger( "click" );
  });

});

</script>
joronimo
  • 563
  • 5
  • 8
1

See the following:

https://api.jquery.com/trigger/

Use $(".btn-primary").trigger("click");

Hope that helps

TchiYuan
  • 4,258
  • 5
  • 28
  • 35
0

Just incase you did not learn yet, you can always define an Id for the button and use it this way:

<div class="form-actions">
  <button id="mybutton" class="btn btn-primary" type="submit">Save device</button>
</div>


 $('#mybutton').click(function(){
    //your code goes here
 });
renakre
  • 8,001
  • 5
  • 46
  • 99
0

$( window ).load(function() { $(".btn-primary").trigger('click'); });

Apurv Chaudhary
  • 1,672
  • 3
  • 30
  • 55