Not working Event onClick jQuery [closed]

0

I have the click event generated with jQuery, which is being defined within ready , for some reason within ready does not work, but outside, yes.

Code:

$(function(){
    $('#id').on("click", function(){ ..algo.. } ); // No funciona

    var aux = document.getElementById("id");
    console.log(aux); // es Null aun estando en el documento
});

// $('#id').on("click", function(){ ..algo.. } );  Si funciona

Jquery version: 2.2.3

    
asked by Islam Linarez 31.01.2018 в 19:26
source

3 answers

0

The code works well, as you can see in the test below.

Although generally, the values are used within the scope of the function that generates a specific event, such as the click of a button. There are very rare cases in which you need to use the data in a general way within the DOM. Also keep in mind that by not indicating what you want from the element, what you get is the element itself. Generally what you are looking for a button type element or input is its id , or value , or text that is written on it.

As for function , you are applying the correct way, since document.ready has been declared obsolete since jQuery 3.

$(function() {

  $('#btnTest').on("click", function() {
    alert("Estamos en el ámbito del click, generalmente los valores se usan aquí");
  });
  var inputTest = document.getElementById("ibxTest").value;
  var buttonTest = document.getElementById("btnTest");
  console.log(inputTest);
  console.log(buttonTest);
  console.log(buttonTest.id);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="ibxTest" value="Test" />
<button id="btnTest">Click para probar</button>
    
answered by 31.01.2018 / 23:27
source
0

Dear, it would be nice to know in which part of your javascript document you are placing the code, or if it is in the same view, to know if you placed it in the document $ (document) .ready (), however, What I do sometimes when I want to add a listener to a button, link, label, etc., is only to put what is inside its function. That is:

 <script>
       $('#id').on("click", function(){ ..algo.. } );
 </script>

Note that it is not within an anonymous function, but within the script tags.

    
answered by 31.01.2018 в 19:38
0

 $(document).ready(function(){
    $("button").click(function(){
        $("p").slideToggle();
    });
});

That's how it works for me

    
answered by 31.01.2018 в 19:43