Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery :visible does not find the element

I have a page where I have an text input at certain screen sizes which changes to a select at other screen sizes.

THE CHALLENGE

I want to be able to get the value of the input or select on keyup or change without having to duplicate the code - so I give the elements the same ID, knowing they will never be visible at the same time, and choose to find the element using: e.g. #ID:visible - code below

$('#test:visible').on('keyup change', function(){
	alert($(this).val());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div style="display: none">
	<input id="test">
</div>
<select id="test">
	<option value="10">10</option>
	<option value="20">20</option>
</select>

THE PROBLEM

This simply doesn't work. I have read the jQuery visible-selector page and it seems that I'm doing things the right way, but the alert simply does not fire.

Am I misunderstanding how this works?

like image 279
StudioTime Avatar asked May 20 '26 23:05

StudioTime


1 Answers

so I give the elements the same ID, knowing they will never be visible at the same time

Unfortunately, that's not how it works. You can't duplicate id attributes within the scope of the same document regardless of the elements being visible or not. You need to use classes to group multiple elements together:

$('.test:visible').on('keyup change', function(){
    alert($(this).val());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div style="display: none">
    <input class="test">
</div>
<select class="test">
    <option value="10">10</option>
    <option value="20">20</option>
</select>
like image 148
Rory McCrossan Avatar answered May 23 '26 13:05

Rory McCrossan



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!