I have example html code like this :
<select id="label_1">
<option></option>
</select>
<select id="item_1">
<option></option>
</select>
<select id="label_2">
<option></option>
</select>
<select id="item_2">
<option></option>
</select>
How do I make a jquery code to match the label and item id with the same number ?
if($("#label_" [/[0-9] $/]) == $("#item_" [/[0-9] $/])) {
//do something
}
CodePudding user response:
You can find all the label elements first and then iterate them to find the matching item elements
$("select[id^='label_']").each((_, label) => {
const idSuffix = label.id.split("_").pop();
const item = $(`#item_${idSuffix}`);
// now you have both `label` and `item`
});
The vanilla JS version isn't much different
document.querySelectorAll("select[id^='label_']").forEach((label) => {
const idSuffix = label.id.split("_").pop();
const item = document.getElementById(`item_${idSuffix}`);
// now you have both `label` and `item`
});
CodePudding user response:
If you want to do one time : return false
$.each($("select[id^= 'label_']"), function(){
let num = this.id.replace('label_', '')
let equal = $(this).value === $("#item_" num).value
if(equal) {
// do something
// if you want to run one times ( return false)
return false
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="label_1">
<option value="1" selected>1</option>
</select>
<select id="item_1">
<option value="1" selected>1</option>
</select>
<select id="label_2">
<option value="2" selected>2</option>
</select>
<select id="item_2">
<option value="2" selected>2</option>
</select>