Jumabek Alikhanov
Jumabek Alikhanov

Reputation: 2383

DOM element doesn't display

I am new in Javascript and I am trying to test following code

<html>
  <head>
  <script src="jquery/jquery.min.js">
  </head>
<body>
  <input type="button" value="Click button">
  <script type="text/javascript">
  $(function(){
    $('input')[0].on('click',function(){
      alert('button clicked');
    });  
   });
  </script>
</body>
</html>

but when i open this html file in browser the button doesn't display

Upvotes: 2

Views: 187

Answers (4)

ebiv
ebiv

Reputation: 325

Adding the <!DOCTYPE html> is better when you continue developing.

Upvotes: 0

Hulk1991
Hulk1991

Reputation: 3163

To avoid these kind of confusions, try to separate like below,

In HTML:

<html>
  <head>
  <script src="jquery/jquery.min.js"></script>
  <script src="main.js"></script>
  </head>
 <body>
   <input type="button" value="Click button">
 </body>
</html>

In main.js

$(function(){ $('input').on('click',function(){ alert('button clicked'); });
});

For Demo

Upvotes: 0

Satpal
Satpal

Reputation: 133423

Problems

  1. Script block must be closed which you missed.
  2. Use $('input') instead of $('input')[0], When you use $('input')[0] you get DOM element which doesn't have click method.

Use

<html>
  <head>
  <script src="jquery/jquery.min.js"></script>
  </head>
<body>
  <input type="button" value="Click button">
  <script type="text/javascript">
  $(function(){
    $('input').on('click',function(){
      alert('button clicked');
    });  
   });
  </script>
</body>
</html>

Upvotes: 0

MrCode
MrCode

Reputation: 64536

Script tags require a closing tag, which you've omitted:

<script src="jquery/jquery.min.js"></script>
                                   ^ close

By leaving it open, the browser is treating everything after the script tag as the script content.

Also your $('input')[0] isn't right. That is getting the DOM element of the input, which has no jQuery wrapper and no .on() function. If you are trying to match just the first input then:

$('input').first().on('click',function(){

Upvotes: 5

Related Questions