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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With