-4

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

4
  • 3
    Please google your title and tell me what comes up Commented Apr 9, 2015 at 20:45
  • possible duplicate of Programmatically click a button using jquery Commented Apr 9, 2015 at 20:46
  • Not really a duplicate. The problem/solution here involves selector syntax. Commented Apr 9, 2015 at 20:49
  • Youre right, didn't read enough Commented Apr 9, 2015 at 20:52

6 Answers 6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Incidentally, the OP's selector .btn btn-primary doesn't reference a class named "btn-primary" due to the lack of a preceding dot.
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()

Comments

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>

Comments

1

See the following:

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

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

Hope that helps

Comments

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
 });

2 Comments

That's really not necessary, plus it doesn't show the OP what he was doing incorrectly.
@j08691 may I learn what OP stands for ? I shared just incase he may not be aware of this.
0
$( window ).load(function() { $(".btn-primary").trigger('click'); });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.