jQuery button click fails to work

Tell us what’s happening:
I am working on my project and trying to use jQuery to make a simple alert box when the button is clicked.

However, this doesn’t work and I don’t get what I am doing wrong.

I imported jquery in code pen using google online source and used the codepen editor import function itself. Did not help.
The only thing i can think of is the double name but if i change this the button: button element gets conflicted and stops to work.

Your code so far


<script > src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<script>
  $(document).ready(function(){
    <!--code goes bellow here-->
  $("button button1).click(function(){
  alert("The paragraph was clicked.");
});
       <!--code goes above here-->
    });
  
</script>


Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36.

@KittyKora
selectors here need to be closed with quote mark . Moreover button1 will not work here; if it’s a class or id make sure to use proper use of class and id selectors with jQuery- hope this will help you

1 Like

this wont work …
<script > src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
try this …

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<p>this is a sentence, not a paragraph!<p>
<script>
  $(document).ready(function(){
    <!--code goes bellow here-->
    $('p').click(function(){
     alert("The paragraph was clicked.");
    });
       <!--code goes above here-->
 })  
</script>
1 Like

What do you mean with: make sure to use proper use of class and id selectors with jQuery?
can u give an example
because if i add an id

  $("btn1").click(function(){
  alert("The paragraph was clicked.");
});

<button class="button button1" id ="btn1">Decrease</button>

it still fails to work

@KittyKora,

// way to work with a class
$('.my-class').click();

// way to work with an id
$('#my-id').click();

// way to work with elements
$('button').click()  

// or
$('a').click()

// see the above examples
// hope you'll get the main point 
1 Like