How to pick up input before the button?

Asked

Viewed 88 times

1

I have some input of the 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 take the value of input above it.

How to do?

1 answer

2


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>
<input type="text" />
<button>inserir</button>
<input type="text" />
<button>inserir</button>
<input type="text" />
<button>inserir</button>
<input type="text" />
<button>inserir</button>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.