I have a form with five input statements with the id ending with a sequential number like:
<input id="phone1" type="text" value="1111111111">
<input id="phone2" type="text" value="">
<input id="phone3" type="text" value="3333333333">
<input id="phone4" type="text" value="4444444444">
<input id="phone5" type="text" value="">
I attempted the following:
const nmbr = [1, 2, 3, 4, 5];
$.each(nmbr, function(index, value){
var phn = $("#phone" value)
if !(phn.val()) {
console.log('phone number missing');
}
});
How would I step through these id's to get the value of the non-blank phone numbers.
CodePudding user response:
Use a class instead and then loop through the input
and check if value is non empty
const inputs = document.querySelectorAll('.ipt');
for (const ipt of inputs) {
if (ipt.value !== "") {
console.log(ipt.value);
}
}
<input id="phone1" type="text" value="1111111111">
<input id="phone2" type="text" value="">
<input id="phone3" type="text" value="3333333333">
<input id="phone4" type="text" value="4444444444">
<input id="phone5" type="text" value="">
CodePudding user response:
In Below Code document.querySelectorAll('[id^="phone"]') will select all the ids with phone prefix.
const data = document.querySelectorAll('[id^="phone"]');
console.log(data);
for (const dt of data) {
if (dt.value !== "") {
console.log(dt.value);
}
}
<input id="phone1" type="text" value="1111111111">
<input id="phone2" type="text" value="">
<input id="phone3" type="text" value="3333333333">
<input id="phone4" type="text" value="4444444444">
<input id="phone5" type="text" value="">