There is a small functionality, now when you click on a field, the input id of this field will be displayed.
But I also added another third field here, via dropDownList on yii2.
And the problem is that the id here is not in the input, but in the select.
How can I fix the javascript so that if there is undefined id in the input, then the id is taken from the select?
$('.form-group input').each(function() {
let input = $(this);
$(this).closest('.range').find('.it').each(function() {
$(this).on('click', function () {
console.log(input.attr('id'));
})
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="range">
<div class="form-group">
<input type="hidden" name="field1" id="field1" value="">
</div>
<span class="it" data-value="1">click</span>
<span class="it" data-value="2">click</span>
</div>
<br>
<div class="range">
<div class="form-group">
<input type="hidden" name="field2" id="field2" value="">
</div>
<span class="it" data-value="1">click</span>
<span class="it" data-value="2">click</span>
</div>
<br>
<div class="range">
<div class="form-group">
<input type="hidden" name="field3" value="" disabled="">
<select id="field3" class="d-none" name="field3[]" disabled="" multiple="" size="4" style="display: none">
<option value="1">$0-20</option>
</select>
</div>
<span class="it" data-value="1">click</span>
<span class="it" data-value="2">click</span>
</div>
2
Answers
Get the select element from the
range
container when the input has no id:Either you can check to see if an input
Or you can only select inputs with an id