How to capture the id of an html input with JS

0

What I want to do is the following:

I have an input:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="5" name="">
<input type="button"  onclick="x();">

I want to capture the value of the id of that input

<script type="text/javascript">
    function x(){
    var id2 = $("#5").id();
    alert(id2);
}
</script>

That does not work, I hope you can help me.

    
asked by Andres Rodriguez 05.12.2018 в 20:39
source

3 answers

3

You could do it without jQuery too, I'll leave you 2 ways:

document.getElementById('boton-js')
        .addEventListener('click', (e) => {
          var input = document.getElementById('5');
          console.log(input.id);
        });

$('#boton-jquery').click((e) => {
  var input = $('#5');
  console.log(input.attr('id'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="5">
<button id="boton-js">Probar</button>
<button id="boton-jquery">Probar (jQuery)</button>

Basically the way to do it in jQuery is through the function attr that serves to extract the properties, such as the id, of the selected element.

    
answered by 05.12.2018 / 20:46
source
0

the answer would be like this:

<script type="text/javascript">
    function x(){
    var id2 = $("#5").val();
    alert(id2);
}
</script>

Greetings.

    
answered by 05.12.2018 в 20:46
0

The jquery method that returns the ID of an element is attr (), so the code of your function should look like this:

<script type="text/javascript">
      function x(){
          var id2 = $("#5").attr('id');
          alert(id2);
      }
 </script>

The attr () method returns the value of the passed attribute as a parameter for the first element that matches the selector specified in the call to the method.

Example:

<p id="parrafo">párrafo</p>

El ID del párrafo es: <div></div>

<script>
    var idParrafo = $( "p" ).attr( "id" );
    $( "div" ).text( idParrafo );
</script>
    
answered by 05.12.2018 в 20:54