Is it possible to select multiple text boxes to output one same alert instead of selecting one at a time?Get selected text from a drop-down list (select box) using jQueryEliminating warning in HTMLConsistency Combo boxif statement for three checkboxes javascriptjQuery using variables so one function performs multiple tasksSelecting the last value from the dropdown and disable it for other dropdownsAny solution to select the dropdown value rather than first indexGrid with divs that have varying heights and widths [Sass, CSS, ReactJS]How to understand isEqualNode() in JavaScriptHow to retrieve data from dynamically created table in html using python cgi
How can Paypal know my card is being used in another account?
What do you call a flexible diving platform?
Summoning A Technology Based Demon
What container to use to store developer concentrate?
Sci-fi change: Too much or Not enough
Dual-national, returning to US the day the US Passport expires; can he check in with airline on Dutch passport but reenter with expiring US passport?
Golden Guardian removed before death related trigger
Why is it "on the inside" and not "in the inside"?
How can I say in Russian "I am not afraid to write anything"?
Does Wolfram Mathworld make a mistake describing a discrete probability distribution with a probability density function?
How could Nomadic scholars effectively memorize libraries worth of information
Why didn’t Christianity spread southwards from Ethiopia in the Middle Ages?
How did the SysRq key get onto modern keyboards if it's rarely used?
(3 of 11: Akari) What is Pyramid Cult's Favorite Car?
Is this photo showing a woman standing in the nude before teenagers real?
Move the outer key inward in an association
Exploiting the delay when a festival ticket is scanned
Name These Animals
ECDSA: Why is SigningKey shorter than VerifyingKey
How do I use JSON.generator to generate an unnamed array?
Why is it considered acid rain with pH <5.6?
How did the Axis intend to hold the Caucasus?
Why does the Eurostar not show youth pricing?
Will this creature from Curse of Strahd reappear after being banished?
Is it possible to select multiple text boxes to output one same alert instead of selecting one at a time?
Get selected text from a drop-down list (select box) using jQueryEliminating warning in HTMLConsistency Combo boxif statement for three checkboxes javascriptjQuery using variables so one function performs multiple tasksSelecting the last value from the dropdown and disable it for other dropdownsAny solution to select the dropdown value rather than first indexGrid with divs that have varying heights and widths [Sass, CSS, ReactJS]How to understand isEqualNode() in JavaScriptHow to retrieve data from dynamically created table in html using python cgi
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
so this isn't really a problem rather a question if it's possible to shorten some code
My current code works although I feel it's too long and could maybe be done in a better way. Basically, I want to know if there's a way to select multiple elements to output the same alert instead of making a new if for every element, here's the code:
function newAdd() {
if (document.getElementById("box1").value == "")
alert('Please define an Object!')
return false;
if (document.getElementById("box2").value == "")
alert('Please define an Object!')
return false;
if (document.getElementById("box3").value == "")
alert('Please define an Object!')
return false;
if (document.getElementById("box4").value == "")
alert('Please define a Time!')
return false;
if (document.getElementById("box5").value == "")
alert('Please define a Time!')
return false;
if (document.getElementById("box6").value == "")
alert('Please define a Time!')
return false;
if (document.getElementById("box7").value == "")
alert('Please define a Name!')
return false;
if (document.getElementById("box4").value.length == 1)
alert('Please define a valid Time!')
return false;
if (document.getElementById("box5").value.length == 1)
alert('Please define a valid Time!')
return false;
if (document.getElementById("box6").value.length == 1)
alert('Please define a valid Time!')
return false;
if (document.getElementById("box6").value.length == 2)
alert('Please define a valid Time! If last digit is unknown type 0.')
return false;
I've tried ("box1, box2, box3") and that doesn't work, and getElementsByClassName wouldn't work because I wouldn't want to select the whole class in which all the text boxes are in.
If you noticed above I'm trying to select 3 text boxes at a time, only the last one is an exception.
The alerts are the same for the first three, the next three, and the last one though is only one.
If there isn't a more compact way to do this I guess I'll just live with it, but it just seems there's always a better way of doing it.
javascript
add a comment |
so this isn't really a problem rather a question if it's possible to shorten some code
My current code works although I feel it's too long and could maybe be done in a better way. Basically, I want to know if there's a way to select multiple elements to output the same alert instead of making a new if for every element, here's the code:
function newAdd() {
if (document.getElementById("box1").value == "")
alert('Please define an Object!')
return false;
if (document.getElementById("box2").value == "")
alert('Please define an Object!')
return false;
if (document.getElementById("box3").value == "")
alert('Please define an Object!')
return false;
if (document.getElementById("box4").value == "")
alert('Please define a Time!')
return false;
if (document.getElementById("box5").value == "")
alert('Please define a Time!')
return false;
if (document.getElementById("box6").value == "")
alert('Please define a Time!')
return false;
if (document.getElementById("box7").value == "")
alert('Please define a Name!')
return false;
if (document.getElementById("box4").value.length == 1)
alert('Please define a valid Time!')
return false;
if (document.getElementById("box5").value.length == 1)
alert('Please define a valid Time!')
return false;
if (document.getElementById("box6").value.length == 1)
alert('Please define a valid Time!')
return false;
if (document.getElementById("box6").value.length == 2)
alert('Please define a valid Time! If last digit is unknown type 0.')
return false;
I've tried ("box1, box2, box3") and that doesn't work, and getElementsByClassName wouldn't work because I wouldn't want to select the whole class in which all the text boxes are in.
If you noticed above I'm trying to select 3 text boxes at a time, only the last one is an exception.
The alerts are the same for the first three, the next three, and the last one though is only one.
If there isn't a more compact way to do this I guess I'll just live with it, but it just seems there's always a better way of doing it.
javascript
you can get an array of elements withgetElementsByClassName
and assigning an identical class and loop through all elements implementing your logic.
– FedeSc
Mar 26 at 19:52
@FedeSc "and getElementsByClassName wouldn't work because I wouldn't want to select the whole class in which all the text boxes are in." I'm only trying to select in a range of 3 boxes at a time
– William Brand
Mar 26 at 19:59
add a comment |
so this isn't really a problem rather a question if it's possible to shorten some code
My current code works although I feel it's too long and could maybe be done in a better way. Basically, I want to know if there's a way to select multiple elements to output the same alert instead of making a new if for every element, here's the code:
function newAdd() {
if (document.getElementById("box1").value == "")
alert('Please define an Object!')
return false;
if (document.getElementById("box2").value == "")
alert('Please define an Object!')
return false;
if (document.getElementById("box3").value == "")
alert('Please define an Object!')
return false;
if (document.getElementById("box4").value == "")
alert('Please define a Time!')
return false;
if (document.getElementById("box5").value == "")
alert('Please define a Time!')
return false;
if (document.getElementById("box6").value == "")
alert('Please define a Time!')
return false;
if (document.getElementById("box7").value == "")
alert('Please define a Name!')
return false;
if (document.getElementById("box4").value.length == 1)
alert('Please define a valid Time!')
return false;
if (document.getElementById("box5").value.length == 1)
alert('Please define a valid Time!')
return false;
if (document.getElementById("box6").value.length == 1)
alert('Please define a valid Time!')
return false;
if (document.getElementById("box6").value.length == 2)
alert('Please define a valid Time! If last digit is unknown type 0.')
return false;
I've tried ("box1, box2, box3") and that doesn't work, and getElementsByClassName wouldn't work because I wouldn't want to select the whole class in which all the text boxes are in.
If you noticed above I'm trying to select 3 text boxes at a time, only the last one is an exception.
The alerts are the same for the first three, the next three, and the last one though is only one.
If there isn't a more compact way to do this I guess I'll just live with it, but it just seems there's always a better way of doing it.
javascript
so this isn't really a problem rather a question if it's possible to shorten some code
My current code works although I feel it's too long and could maybe be done in a better way. Basically, I want to know if there's a way to select multiple elements to output the same alert instead of making a new if for every element, here's the code:
function newAdd() {
if (document.getElementById("box1").value == "")
alert('Please define an Object!')
return false;
if (document.getElementById("box2").value == "")
alert('Please define an Object!')
return false;
if (document.getElementById("box3").value == "")
alert('Please define an Object!')
return false;
if (document.getElementById("box4").value == "")
alert('Please define a Time!')
return false;
if (document.getElementById("box5").value == "")
alert('Please define a Time!')
return false;
if (document.getElementById("box6").value == "")
alert('Please define a Time!')
return false;
if (document.getElementById("box7").value == "")
alert('Please define a Name!')
return false;
if (document.getElementById("box4").value.length == 1)
alert('Please define a valid Time!')
return false;
if (document.getElementById("box5").value.length == 1)
alert('Please define a valid Time!')
return false;
if (document.getElementById("box6").value.length == 1)
alert('Please define a valid Time!')
return false;
if (document.getElementById("box6").value.length == 2)
alert('Please define a valid Time! If last digit is unknown type 0.')
return false;
I've tried ("box1, box2, box3") and that doesn't work, and getElementsByClassName wouldn't work because I wouldn't want to select the whole class in which all the text boxes are in.
If you noticed above I'm trying to select 3 text boxes at a time, only the last one is an exception.
The alerts are the same for the first three, the next three, and the last one though is only one.
If there isn't a more compact way to do this I guess I'll just live with it, but it just seems there's always a better way of doing it.
javascript
javascript
edited Mar 26 at 19:48
showdev
21.8k14 gold badges37 silver badges57 bronze badges
21.8k14 gold badges37 silver badges57 bronze badges
asked Mar 26 at 19:44
William BrandWilliam Brand
96 bronze badges
96 bronze badges
you can get an array of elements withgetElementsByClassName
and assigning an identical class and loop through all elements implementing your logic.
– FedeSc
Mar 26 at 19:52
@FedeSc "and getElementsByClassName wouldn't work because I wouldn't want to select the whole class in which all the text boxes are in." I'm only trying to select in a range of 3 boxes at a time
– William Brand
Mar 26 at 19:59
add a comment |
you can get an array of elements withgetElementsByClassName
and assigning an identical class and loop through all elements implementing your logic.
– FedeSc
Mar 26 at 19:52
@FedeSc "and getElementsByClassName wouldn't work because I wouldn't want to select the whole class in which all the text boxes are in." I'm only trying to select in a range of 3 boxes at a time
– William Brand
Mar 26 at 19:59
you can get an array of elements with
getElementsByClassName
and assigning an identical class and loop through all elements implementing your logic.– FedeSc
Mar 26 at 19:52
you can get an array of elements with
getElementsByClassName
and assigning an identical class and loop through all elements implementing your logic.– FedeSc
Mar 26 at 19:52
@FedeSc "and getElementsByClassName wouldn't work because I wouldn't want to select the whole class in which all the text boxes are in." I'm only trying to select in a range of 3 boxes at a time
– William Brand
Mar 26 at 19:59
@FedeSc "and getElementsByClassName wouldn't work because I wouldn't want to select the whole class in which all the text boxes are in." I'm only trying to select in a range of 3 boxes at a time
– William Brand
Mar 26 at 19:59
add a comment |
2 Answers
2
active
oldest
votes
create an array of id's names and loop through it with one function.
var ids = ["one", "two", "three"];
ids.forEach((elem) =>
if (document.getElementById(elem).getAttribute("value") == "")
alert('value empty');
)
<div id="one" value="">
one
</div>
<div id="two" value="2">
two
</div>
<div id="three" value="3">
three
</div>
add a comment |
I'm in danger of commandeering your question a bit here, but here goes.
It's possible to output the same alert for multiple different fields, but I don't think that's actually what you want. If you output the same alert for each one, the user won't know which of these fields has a mistake in it. They won't like that.
It's also possible to shorten your code quite a bit, but I don't think fewer lines is what you really want either. I think what you really want is code that makes your intention clear and avoids needless repetition.
The solution I've written is actually slightly longer than yours, and it's harder to understand at first blush, but I think it does a better job at revealing the underlying structure of the work this task is doing. Once you understand the pattern it's easier to see how to change or extend it without introducing bugs. Anything that could be done differently for each input is written once for each input, and anything that needs to be handled the same for all of them is only written once.
(Your submitted code was written in ES2015, but I've written my response in the ES2016 dialect of Javascript because I'm more used to writing it and it allows for a cleaner syntax. If for whatever reason you can't or don't want to use ES2016, I've also posted an ES2015 version below.)
The structure is as follows:
- We define some "testers" which are functions that run on a string and try to detect a validation problem (empty, invalid, etc.). If they detect the problem they were built to detect, they return
true
, otherwisefalse
. - We define a function to turn a tester into a validator. A validator takes the same input, but if a problem is detected, it returns a complaint string, otherwise
undefined
. To call the function that turns a tester into a validator, the caller needs to provide a tester and a complaint string to use if the validation fails. - We define an object that maps element IDs to an array of validators that apply to those elements. The pattern from step 2 lets us reuse the empty-string validator on every input, even though different inputs will have different complaints if they are empty.
- We loop over the IDs in the object. For each ID, we get the value for the corresponding input. We get the list of validators for the ID and run each of them on the value. If any of them come back with a complaint string, we alter the user with that complaint string and return. Otherwise we keep going until the loop ends.
ES2016:
function newAdd()
const nonEmptyTester = value => value === "";
const validTimeTester = value => value.length === 1;
const validDifferentTimeTester = value => value.length === 2;
const makeValidator = (tester, failureMessage) => value => tester(value) ? failureMessage : undefined;
const toValidate =
box1: [makeValidator(nonEmptyTester, "Please define an Object!")],
box2: [makeValidator(nonEmptyTester, "Please define an Object!")],
box3: [makeValidator(nonEmptyTester, "Please define an Object!")],
box4: [
makeValidator(nonEmptyTester, "Please define a Time!"),
makeValidator(validTimeTester, "Please define a valid Time!")
],
box5: [
makeValidator(nonEmptyTester, "Please define a Time!"),
makeValidator(validTimeTester, "Please define a valid Time!")
],
box6: [
makeValidator(nonEmptyTester, "Please define a Time!"),
makeValidator(validTimeTester, "Please define a valid Time!"),
makeValidator(validDifferentTimeTester, "Please define a valid Time! If last digit is unknown type 0.")
],
box7: [validator(nonEmptyTester, "Please define a Name!")]
;
for (let id in toValidate)
const element = document.getElementById(id);
const value = element.value;
const problems = toValidate[id].map(validator => validator(value));
const firstProblemIfAny = problems.find(problem => problem !== undefined);
if (firstProblemIfAny !== undefined)
alert(firstProblemIfAny);
return false;
return true;
ES2015:
function newAdd()
function nonEmptyTester(value)
return value === "";
;
function validTimeTester(value)
return value.length === 1;
;
function validDifferentTimeTester(value)
return value.length === 2;
;
function makeValidator(tester, failureMessage)
return function (value)
return tester(value) ? failureMessage : undefined;
;
;
var toValidate =
box1: [makeValidator(nonEmptyTester, "Please define an Object!")],
box2: [makeValidator(nonEmptyTester, "Please define an Object!")],
box3: [makeValidator(nonEmptyTester, "Please define an Object!")],
box4: [makeValidator(nonEmptyTester, "Please define a Time!"), makeValidator(validTimeTester, "Please define a valid Time!")],
box5: [makeValidator(nonEmptyTester, "Please define a Time!"), makeValidator(validTimeTester, "Please define a valid Time!")],
box6: [makeValidator(nonEmptyTester, "Please define a Time!"), makeValidator(validTimeTester, "Please define a valid Time!"), makeValidator(validDifferentTimeTester, "Please define a valid Time! If last digit is unknown type 0.")],
box7: [validator(nonEmptyTester, "Please define a Name!")]
;
for (var id in toValidate)
var element = document.getElementById(id);
var value = element.value;
var problems = toValidate[id].map(function (validator)
return validator(value);
);
var firstProblemIfAny = problems.find(function (problem)
return problem !== undefined;
);
if (firstProblemIfAny !== undefined)
alert(firstProblemIfAny);
return false;
return true;
I hope you'll agree that even though this is more code, it's more readable. The object shows exactly what form validation you're doing with much less cruft, and it's immediately obvious where to go to change certain behaviour. For example:
- The testers handle the exact logic for what's acceptable for a certain type of input.
- The validator object handles exactly which testers apply to which element, and how the elements complain if their requirements are not met.
- The loop at the end defines what to do if a complaint is found. For example, you might want to print the complaint to an element on the screen instead of calling
alert
. Now this would require a change in only one place!
Finally, if you're sure you want to reuse the complaint strings across elements, you could do something like this:
var objectValidator = makeValidator(nonEmptyTester, "Please fill in all fields!");
var toValidate =
id1: [objectValidator],
id2: [objectValidator],
...
;
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55365153%2fis-it-possible-to-select-multiple-text-boxes-to-output-one-same-alert-instead-of%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
create an array of id's names and loop through it with one function.
var ids = ["one", "two", "three"];
ids.forEach((elem) =>
if (document.getElementById(elem).getAttribute("value") == "")
alert('value empty');
)
<div id="one" value="">
one
</div>
<div id="two" value="2">
two
</div>
<div id="three" value="3">
three
</div>
add a comment |
create an array of id's names and loop through it with one function.
var ids = ["one", "two", "three"];
ids.forEach((elem) =>
if (document.getElementById(elem).getAttribute("value") == "")
alert('value empty');
)
<div id="one" value="">
one
</div>
<div id="two" value="2">
two
</div>
<div id="three" value="3">
three
</div>
add a comment |
create an array of id's names and loop through it with one function.
var ids = ["one", "two", "three"];
ids.forEach((elem) =>
if (document.getElementById(elem).getAttribute("value") == "")
alert('value empty');
)
<div id="one" value="">
one
</div>
<div id="two" value="2">
two
</div>
<div id="three" value="3">
three
</div>
create an array of id's names and loop through it with one function.
var ids = ["one", "two", "three"];
ids.forEach((elem) =>
if (document.getElementById(elem).getAttribute("value") == "")
alert('value empty');
)
<div id="one" value="">
one
</div>
<div id="two" value="2">
two
</div>
<div id="three" value="3">
three
</div>
var ids = ["one", "two", "three"];
ids.forEach((elem) =>
if (document.getElementById(elem).getAttribute("value") == "")
alert('value empty');
)
<div id="one" value="">
one
</div>
<div id="two" value="2">
two
</div>
<div id="three" value="3">
three
</div>
var ids = ["one", "two", "three"];
ids.forEach((elem) =>
if (document.getElementById(elem).getAttribute("value") == "")
alert('value empty');
)
<div id="one" value="">
one
</div>
<div id="two" value="2">
two
</div>
<div id="three" value="3">
three
</div>
answered Mar 26 at 20:28
Oren ShaharOren Shahar
112 bronze badges
112 bronze badges
add a comment |
add a comment |
I'm in danger of commandeering your question a bit here, but here goes.
It's possible to output the same alert for multiple different fields, but I don't think that's actually what you want. If you output the same alert for each one, the user won't know which of these fields has a mistake in it. They won't like that.
It's also possible to shorten your code quite a bit, but I don't think fewer lines is what you really want either. I think what you really want is code that makes your intention clear and avoids needless repetition.
The solution I've written is actually slightly longer than yours, and it's harder to understand at first blush, but I think it does a better job at revealing the underlying structure of the work this task is doing. Once you understand the pattern it's easier to see how to change or extend it without introducing bugs. Anything that could be done differently for each input is written once for each input, and anything that needs to be handled the same for all of them is only written once.
(Your submitted code was written in ES2015, but I've written my response in the ES2016 dialect of Javascript because I'm more used to writing it and it allows for a cleaner syntax. If for whatever reason you can't or don't want to use ES2016, I've also posted an ES2015 version below.)
The structure is as follows:
- We define some "testers" which are functions that run on a string and try to detect a validation problem (empty, invalid, etc.). If they detect the problem they were built to detect, they return
true
, otherwisefalse
. - We define a function to turn a tester into a validator. A validator takes the same input, but if a problem is detected, it returns a complaint string, otherwise
undefined
. To call the function that turns a tester into a validator, the caller needs to provide a tester and a complaint string to use if the validation fails. - We define an object that maps element IDs to an array of validators that apply to those elements. The pattern from step 2 lets us reuse the empty-string validator on every input, even though different inputs will have different complaints if they are empty.
- We loop over the IDs in the object. For each ID, we get the value for the corresponding input. We get the list of validators for the ID and run each of them on the value. If any of them come back with a complaint string, we alter the user with that complaint string and return. Otherwise we keep going until the loop ends.
ES2016:
function newAdd()
const nonEmptyTester = value => value === "";
const validTimeTester = value => value.length === 1;
const validDifferentTimeTester = value => value.length === 2;
const makeValidator = (tester, failureMessage) => value => tester(value) ? failureMessage : undefined;
const toValidate =
box1: [makeValidator(nonEmptyTester, "Please define an Object!")],
box2: [makeValidator(nonEmptyTester, "Please define an Object!")],
box3: [makeValidator(nonEmptyTester, "Please define an Object!")],
box4: [
makeValidator(nonEmptyTester, "Please define a Time!"),
makeValidator(validTimeTester, "Please define a valid Time!")
],
box5: [
makeValidator(nonEmptyTester, "Please define a Time!"),
makeValidator(validTimeTester, "Please define a valid Time!")
],
box6: [
makeValidator(nonEmptyTester, "Please define a Time!"),
makeValidator(validTimeTester, "Please define a valid Time!"),
makeValidator(validDifferentTimeTester, "Please define a valid Time! If last digit is unknown type 0.")
],
box7: [validator(nonEmptyTester, "Please define a Name!")]
;
for (let id in toValidate)
const element = document.getElementById(id);
const value = element.value;
const problems = toValidate[id].map(validator => validator(value));
const firstProblemIfAny = problems.find(problem => problem !== undefined);
if (firstProblemIfAny !== undefined)
alert(firstProblemIfAny);
return false;
return true;
ES2015:
function newAdd()
function nonEmptyTester(value)
return value === "";
;
function validTimeTester(value)
return value.length === 1;
;
function validDifferentTimeTester(value)
return value.length === 2;
;
function makeValidator(tester, failureMessage)
return function (value)
return tester(value) ? failureMessage : undefined;
;
;
var toValidate =
box1: [makeValidator(nonEmptyTester, "Please define an Object!")],
box2: [makeValidator(nonEmptyTester, "Please define an Object!")],
box3: [makeValidator(nonEmptyTester, "Please define an Object!")],
box4: [makeValidator(nonEmptyTester, "Please define a Time!"), makeValidator(validTimeTester, "Please define a valid Time!")],
box5: [makeValidator(nonEmptyTester, "Please define a Time!"), makeValidator(validTimeTester, "Please define a valid Time!")],
box6: [makeValidator(nonEmptyTester, "Please define a Time!"), makeValidator(validTimeTester, "Please define a valid Time!"), makeValidator(validDifferentTimeTester, "Please define a valid Time! If last digit is unknown type 0.")],
box7: [validator(nonEmptyTester, "Please define a Name!")]
;
for (var id in toValidate)
var element = document.getElementById(id);
var value = element.value;
var problems = toValidate[id].map(function (validator)
return validator(value);
);
var firstProblemIfAny = problems.find(function (problem)
return problem !== undefined;
);
if (firstProblemIfAny !== undefined)
alert(firstProblemIfAny);
return false;
return true;
I hope you'll agree that even though this is more code, it's more readable. The object shows exactly what form validation you're doing with much less cruft, and it's immediately obvious where to go to change certain behaviour. For example:
- The testers handle the exact logic for what's acceptable for a certain type of input.
- The validator object handles exactly which testers apply to which element, and how the elements complain if their requirements are not met.
- The loop at the end defines what to do if a complaint is found. For example, you might want to print the complaint to an element on the screen instead of calling
alert
. Now this would require a change in only one place!
Finally, if you're sure you want to reuse the complaint strings across elements, you could do something like this:
var objectValidator = makeValidator(nonEmptyTester, "Please fill in all fields!");
var toValidate =
id1: [objectValidator],
id2: [objectValidator],
...
;
add a comment |
I'm in danger of commandeering your question a bit here, but here goes.
It's possible to output the same alert for multiple different fields, but I don't think that's actually what you want. If you output the same alert for each one, the user won't know which of these fields has a mistake in it. They won't like that.
It's also possible to shorten your code quite a bit, but I don't think fewer lines is what you really want either. I think what you really want is code that makes your intention clear and avoids needless repetition.
The solution I've written is actually slightly longer than yours, and it's harder to understand at first blush, but I think it does a better job at revealing the underlying structure of the work this task is doing. Once you understand the pattern it's easier to see how to change or extend it without introducing bugs. Anything that could be done differently for each input is written once for each input, and anything that needs to be handled the same for all of them is only written once.
(Your submitted code was written in ES2015, but I've written my response in the ES2016 dialect of Javascript because I'm more used to writing it and it allows for a cleaner syntax. If for whatever reason you can't or don't want to use ES2016, I've also posted an ES2015 version below.)
The structure is as follows:
- We define some "testers" which are functions that run on a string and try to detect a validation problem (empty, invalid, etc.). If they detect the problem they were built to detect, they return
true
, otherwisefalse
. - We define a function to turn a tester into a validator. A validator takes the same input, but if a problem is detected, it returns a complaint string, otherwise
undefined
. To call the function that turns a tester into a validator, the caller needs to provide a tester and a complaint string to use if the validation fails. - We define an object that maps element IDs to an array of validators that apply to those elements. The pattern from step 2 lets us reuse the empty-string validator on every input, even though different inputs will have different complaints if they are empty.
- We loop over the IDs in the object. For each ID, we get the value for the corresponding input. We get the list of validators for the ID and run each of them on the value. If any of them come back with a complaint string, we alter the user with that complaint string and return. Otherwise we keep going until the loop ends.
ES2016:
function newAdd()
const nonEmptyTester = value => value === "";
const validTimeTester = value => value.length === 1;
const validDifferentTimeTester = value => value.length === 2;
const makeValidator = (tester, failureMessage) => value => tester(value) ? failureMessage : undefined;
const toValidate =
box1: [makeValidator(nonEmptyTester, "Please define an Object!")],
box2: [makeValidator(nonEmptyTester, "Please define an Object!")],
box3: [makeValidator(nonEmptyTester, "Please define an Object!")],
box4: [
makeValidator(nonEmptyTester, "Please define a Time!"),
makeValidator(validTimeTester, "Please define a valid Time!")
],
box5: [
makeValidator(nonEmptyTester, "Please define a Time!"),
makeValidator(validTimeTester, "Please define a valid Time!")
],
box6: [
makeValidator(nonEmptyTester, "Please define a Time!"),
makeValidator(validTimeTester, "Please define a valid Time!"),
makeValidator(validDifferentTimeTester, "Please define a valid Time! If last digit is unknown type 0.")
],
box7: [validator(nonEmptyTester, "Please define a Name!")]
;
for (let id in toValidate)
const element = document.getElementById(id);
const value = element.value;
const problems = toValidate[id].map(validator => validator(value));
const firstProblemIfAny = problems.find(problem => problem !== undefined);
if (firstProblemIfAny !== undefined)
alert(firstProblemIfAny);
return false;
return true;
ES2015:
function newAdd()
function nonEmptyTester(value)
return value === "";
;
function validTimeTester(value)
return value.length === 1;
;
function validDifferentTimeTester(value)
return value.length === 2;
;
function makeValidator(tester, failureMessage)
return function (value)
return tester(value) ? failureMessage : undefined;
;
;
var toValidate =
box1: [makeValidator(nonEmptyTester, "Please define an Object!")],
box2: [makeValidator(nonEmptyTester, "Please define an Object!")],
box3: [makeValidator(nonEmptyTester, "Please define an Object!")],
box4: [makeValidator(nonEmptyTester, "Please define a Time!"), makeValidator(validTimeTester, "Please define a valid Time!")],
box5: [makeValidator(nonEmptyTester, "Please define a Time!"), makeValidator(validTimeTester, "Please define a valid Time!")],
box6: [makeValidator(nonEmptyTester, "Please define a Time!"), makeValidator(validTimeTester, "Please define a valid Time!"), makeValidator(validDifferentTimeTester, "Please define a valid Time! If last digit is unknown type 0.")],
box7: [validator(nonEmptyTester, "Please define a Name!")]
;
for (var id in toValidate)
var element = document.getElementById(id);
var value = element.value;
var problems = toValidate[id].map(function (validator)
return validator(value);
);
var firstProblemIfAny = problems.find(function (problem)
return problem !== undefined;
);
if (firstProblemIfAny !== undefined)
alert(firstProblemIfAny);
return false;
return true;
I hope you'll agree that even though this is more code, it's more readable. The object shows exactly what form validation you're doing with much less cruft, and it's immediately obvious where to go to change certain behaviour. For example:
- The testers handle the exact logic for what's acceptable for a certain type of input.
- The validator object handles exactly which testers apply to which element, and how the elements complain if their requirements are not met.
- The loop at the end defines what to do if a complaint is found. For example, you might want to print the complaint to an element on the screen instead of calling
alert
. Now this would require a change in only one place!
Finally, if you're sure you want to reuse the complaint strings across elements, you could do something like this:
var objectValidator = makeValidator(nonEmptyTester, "Please fill in all fields!");
var toValidate =
id1: [objectValidator],
id2: [objectValidator],
...
;
add a comment |
I'm in danger of commandeering your question a bit here, but here goes.
It's possible to output the same alert for multiple different fields, but I don't think that's actually what you want. If you output the same alert for each one, the user won't know which of these fields has a mistake in it. They won't like that.
It's also possible to shorten your code quite a bit, but I don't think fewer lines is what you really want either. I think what you really want is code that makes your intention clear and avoids needless repetition.
The solution I've written is actually slightly longer than yours, and it's harder to understand at first blush, but I think it does a better job at revealing the underlying structure of the work this task is doing. Once you understand the pattern it's easier to see how to change or extend it without introducing bugs. Anything that could be done differently for each input is written once for each input, and anything that needs to be handled the same for all of them is only written once.
(Your submitted code was written in ES2015, but I've written my response in the ES2016 dialect of Javascript because I'm more used to writing it and it allows for a cleaner syntax. If for whatever reason you can't or don't want to use ES2016, I've also posted an ES2015 version below.)
The structure is as follows:
- We define some "testers" which are functions that run on a string and try to detect a validation problem (empty, invalid, etc.). If they detect the problem they were built to detect, they return
true
, otherwisefalse
. - We define a function to turn a tester into a validator. A validator takes the same input, but if a problem is detected, it returns a complaint string, otherwise
undefined
. To call the function that turns a tester into a validator, the caller needs to provide a tester and a complaint string to use if the validation fails. - We define an object that maps element IDs to an array of validators that apply to those elements. The pattern from step 2 lets us reuse the empty-string validator on every input, even though different inputs will have different complaints if they are empty.
- We loop over the IDs in the object. For each ID, we get the value for the corresponding input. We get the list of validators for the ID and run each of them on the value. If any of them come back with a complaint string, we alter the user with that complaint string and return. Otherwise we keep going until the loop ends.
ES2016:
function newAdd()
const nonEmptyTester = value => value === "";
const validTimeTester = value => value.length === 1;
const validDifferentTimeTester = value => value.length === 2;
const makeValidator = (tester, failureMessage) => value => tester(value) ? failureMessage : undefined;
const toValidate =
box1: [makeValidator(nonEmptyTester, "Please define an Object!")],
box2: [makeValidator(nonEmptyTester, "Please define an Object!")],
box3: [makeValidator(nonEmptyTester, "Please define an Object!")],
box4: [
makeValidator(nonEmptyTester, "Please define a Time!"),
makeValidator(validTimeTester, "Please define a valid Time!")
],
box5: [
makeValidator(nonEmptyTester, "Please define a Time!"),
makeValidator(validTimeTester, "Please define a valid Time!")
],
box6: [
makeValidator(nonEmptyTester, "Please define a Time!"),
makeValidator(validTimeTester, "Please define a valid Time!"),
makeValidator(validDifferentTimeTester, "Please define a valid Time! If last digit is unknown type 0.")
],
box7: [validator(nonEmptyTester, "Please define a Name!")]
;
for (let id in toValidate)
const element = document.getElementById(id);
const value = element.value;
const problems = toValidate[id].map(validator => validator(value));
const firstProblemIfAny = problems.find(problem => problem !== undefined);
if (firstProblemIfAny !== undefined)
alert(firstProblemIfAny);
return false;
return true;
ES2015:
function newAdd()
function nonEmptyTester(value)
return value === "";
;
function validTimeTester(value)
return value.length === 1;
;
function validDifferentTimeTester(value)
return value.length === 2;
;
function makeValidator(tester, failureMessage)
return function (value)
return tester(value) ? failureMessage : undefined;
;
;
var toValidate =
box1: [makeValidator(nonEmptyTester, "Please define an Object!")],
box2: [makeValidator(nonEmptyTester, "Please define an Object!")],
box3: [makeValidator(nonEmptyTester, "Please define an Object!")],
box4: [makeValidator(nonEmptyTester, "Please define a Time!"), makeValidator(validTimeTester, "Please define a valid Time!")],
box5: [makeValidator(nonEmptyTester, "Please define a Time!"), makeValidator(validTimeTester, "Please define a valid Time!")],
box6: [makeValidator(nonEmptyTester, "Please define a Time!"), makeValidator(validTimeTester, "Please define a valid Time!"), makeValidator(validDifferentTimeTester, "Please define a valid Time! If last digit is unknown type 0.")],
box7: [validator(nonEmptyTester, "Please define a Name!")]
;
for (var id in toValidate)
var element = document.getElementById(id);
var value = element.value;
var problems = toValidate[id].map(function (validator)
return validator(value);
);
var firstProblemIfAny = problems.find(function (problem)
return problem !== undefined;
);
if (firstProblemIfAny !== undefined)
alert(firstProblemIfAny);
return false;
return true;
I hope you'll agree that even though this is more code, it's more readable. The object shows exactly what form validation you're doing with much less cruft, and it's immediately obvious where to go to change certain behaviour. For example:
- The testers handle the exact logic for what's acceptable for a certain type of input.
- The validator object handles exactly which testers apply to which element, and how the elements complain if their requirements are not met.
- The loop at the end defines what to do if a complaint is found. For example, you might want to print the complaint to an element on the screen instead of calling
alert
. Now this would require a change in only one place!
Finally, if you're sure you want to reuse the complaint strings across elements, you could do something like this:
var objectValidator = makeValidator(nonEmptyTester, "Please fill in all fields!");
var toValidate =
id1: [objectValidator],
id2: [objectValidator],
...
;
I'm in danger of commandeering your question a bit here, but here goes.
It's possible to output the same alert for multiple different fields, but I don't think that's actually what you want. If you output the same alert for each one, the user won't know which of these fields has a mistake in it. They won't like that.
It's also possible to shorten your code quite a bit, but I don't think fewer lines is what you really want either. I think what you really want is code that makes your intention clear and avoids needless repetition.
The solution I've written is actually slightly longer than yours, and it's harder to understand at first blush, but I think it does a better job at revealing the underlying structure of the work this task is doing. Once you understand the pattern it's easier to see how to change or extend it without introducing bugs. Anything that could be done differently for each input is written once for each input, and anything that needs to be handled the same for all of them is only written once.
(Your submitted code was written in ES2015, but I've written my response in the ES2016 dialect of Javascript because I'm more used to writing it and it allows for a cleaner syntax. If for whatever reason you can't or don't want to use ES2016, I've also posted an ES2015 version below.)
The structure is as follows:
- We define some "testers" which are functions that run on a string and try to detect a validation problem (empty, invalid, etc.). If they detect the problem they were built to detect, they return
true
, otherwisefalse
. - We define a function to turn a tester into a validator. A validator takes the same input, but if a problem is detected, it returns a complaint string, otherwise
undefined
. To call the function that turns a tester into a validator, the caller needs to provide a tester and a complaint string to use if the validation fails. - We define an object that maps element IDs to an array of validators that apply to those elements. The pattern from step 2 lets us reuse the empty-string validator on every input, even though different inputs will have different complaints if they are empty.
- We loop over the IDs in the object. For each ID, we get the value for the corresponding input. We get the list of validators for the ID and run each of them on the value. If any of them come back with a complaint string, we alter the user with that complaint string and return. Otherwise we keep going until the loop ends.
ES2016:
function newAdd()
const nonEmptyTester = value => value === "";
const validTimeTester = value => value.length === 1;
const validDifferentTimeTester = value => value.length === 2;
const makeValidator = (tester, failureMessage) => value => tester(value) ? failureMessage : undefined;
const toValidate =
box1: [makeValidator(nonEmptyTester, "Please define an Object!")],
box2: [makeValidator(nonEmptyTester, "Please define an Object!")],
box3: [makeValidator(nonEmptyTester, "Please define an Object!")],
box4: [
makeValidator(nonEmptyTester, "Please define a Time!"),
makeValidator(validTimeTester, "Please define a valid Time!")
],
box5: [
makeValidator(nonEmptyTester, "Please define a Time!"),
makeValidator(validTimeTester, "Please define a valid Time!")
],
box6: [
makeValidator(nonEmptyTester, "Please define a Time!"),
makeValidator(validTimeTester, "Please define a valid Time!"),
makeValidator(validDifferentTimeTester, "Please define a valid Time! If last digit is unknown type 0.")
],
box7: [validator(nonEmptyTester, "Please define a Name!")]
;
for (let id in toValidate)
const element = document.getElementById(id);
const value = element.value;
const problems = toValidate[id].map(validator => validator(value));
const firstProblemIfAny = problems.find(problem => problem !== undefined);
if (firstProblemIfAny !== undefined)
alert(firstProblemIfAny);
return false;
return true;
ES2015:
function newAdd()
function nonEmptyTester(value)
return value === "";
;
function validTimeTester(value)
return value.length === 1;
;
function validDifferentTimeTester(value)
return value.length === 2;
;
function makeValidator(tester, failureMessage)
return function (value)
return tester(value) ? failureMessage : undefined;
;
;
var toValidate =
box1: [makeValidator(nonEmptyTester, "Please define an Object!")],
box2: [makeValidator(nonEmptyTester, "Please define an Object!")],
box3: [makeValidator(nonEmptyTester, "Please define an Object!")],
box4: [makeValidator(nonEmptyTester, "Please define a Time!"), makeValidator(validTimeTester, "Please define a valid Time!")],
box5: [makeValidator(nonEmptyTester, "Please define a Time!"), makeValidator(validTimeTester, "Please define a valid Time!")],
box6: [makeValidator(nonEmptyTester, "Please define a Time!"), makeValidator(validTimeTester, "Please define a valid Time!"), makeValidator(validDifferentTimeTester, "Please define a valid Time! If last digit is unknown type 0.")],
box7: [validator(nonEmptyTester, "Please define a Name!")]
;
for (var id in toValidate)
var element = document.getElementById(id);
var value = element.value;
var problems = toValidate[id].map(function (validator)
return validator(value);
);
var firstProblemIfAny = problems.find(function (problem)
return problem !== undefined;
);
if (firstProblemIfAny !== undefined)
alert(firstProblemIfAny);
return false;
return true;
I hope you'll agree that even though this is more code, it's more readable. The object shows exactly what form validation you're doing with much less cruft, and it's immediately obvious where to go to change certain behaviour. For example:
- The testers handle the exact logic for what's acceptable for a certain type of input.
- The validator object handles exactly which testers apply to which element, and how the elements complain if their requirements are not met.
- The loop at the end defines what to do if a complaint is found. For example, you might want to print the complaint to an element on the screen instead of calling
alert
. Now this would require a change in only one place!
Finally, if you're sure you want to reuse the complaint strings across elements, you could do something like this:
var objectValidator = makeValidator(nonEmptyTester, "Please fill in all fields!");
var toValidate =
id1: [objectValidator],
id2: [objectValidator],
...
;
answered Mar 26 at 21:26
Mattias MartensMattias Martens
4885 silver badges8 bronze badges
4885 silver badges8 bronze badges
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55365153%2fis-it-possible-to-select-multiple-text-boxes-to-output-one-same-alert-instead-of%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
you can get an array of elements with
getElementsByClassName
and assigning an identical class and loop through all elements implementing your logic.– FedeSc
Mar 26 at 19:52
@FedeSc "and getElementsByClassName wouldn't work because I wouldn't want to select the whole class in which all the text boxes are in." I'm only trying to select in a range of 3 boxes at a time
– William Brand
Mar 26 at 19:59