Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write js function to get input value when click button

Tags:

javascript

i have several class="items" that include input and button, and i want to click button and identify whether siblings input has value or not.

function onClick(elem) {
  var $this = elem.tagName;
  var val = $this.siblings('input[type=text]').val();
  if (val == '') {
    console.log('no input');
  } else {
    console.log(val);
  }
}
<div class="items">
  <input type="" name="" id="keywordSearch1" placeholder="">
  <button onclick="onClick()">button1</button>
</div>
<div class="items">
  <input type="" name="" id="keywordSearch2" placeholder="">
  <button onclick="onClick()">button2</button>
</div>
<div class="items">
  <input type="" name="" id="keywordSearch3" placeholder="">
  <button onclick="onClick()">button3</button>
</div>
like image 212
annoytw Avatar asked Sep 13 '26 22:09

annoytw


1 Answers

Pass object this to the function and get the previous element with previousElementSibling from that element.

Please Note: val() is jQuery method, the equivalent JavaScript property is value

function onClick($this) {
  var val = $this.previousElementSibling.value;
  if(val == ''){
      console.log('no input');
  }else{
     console.log(val);
  }
}
<div class="items">
    <input type="" name="" id="keywordSearch1" placeholder="">
    <button onclick="onClick(this)">Search 1</button>
</div>
<div class="items">
    <input type="" name="" id="keywordSearch2" placeholder="">
    <button onclick="onClick(this)">Search 3</button>
</div>
<div class="items">
    <input type="" name="" id="keywordSearch3" placeholder="">
    <button onclick="onClick(this)">Search 3</button>
</div>
like image 197
Mamun Avatar answered Sep 15 '26 11:09

Mamun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!