How to get the input before the button?

1

I have some input of text type followed by buttons :

<input type="text" />
<button>inserir</button>
<input type="text" />
<button>inserir</button>
<input type="text" />
<button>inserir</button>
<input type="text" />
<button>inserir</button>

I need, by pressing the button, to get the value of input above it.

How to do it?

    
asked by anonymous 24.01.2018 / 01:02

1 answer

3

You can use .prev that selects the previous element:

$("button").on("click", function(){
   var texto = $(this).prev().val();
   console.log(texto);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text" />
<button>inserir</button>
<input type="text" />
<button>inserir</button>
<input type="text" />
<button>inserir</button>
<input type="text" />
<button>inserir</button>
    
24.01.2018 / 01:27