I have these two functions to test if, on my form, a section of 4 rows of elements, each with 4 text boxes and two radio buttons, is "complete."
Complete being 1-3 rows are fully filled, and the rest are empty, or all 4 rows are fully filled and none are empty.
If row 1 is not fully filled and the rest are empty, it is not complete.
If row 1 is fully filled and row 2 is not, it is not complete, and so on.
Right now these functions are saying the form is complete when at least 1 row is fully filled, regardless if the rest are not fully filled.
Are there any errors in this code? I've tried many different fixes and none seem to work - I'm wondering if my logic is off.
function lineIsComplete(i) {
let lastName = document.getElementById("txtChildsPlacementChild" + i + "LastName");
let firstName = document.getElementById("txtChildsPlacementChild" + i + "FirstName");
let caseNumber = document.getElementById("txtChildsPlacementChild" + i + "CaseNumber");
let birthDate = document.getElementById("txtChildsPlacementChild" + i + "BirthDate");
let apprehended = document.getElementById("rdoChildsPlacementChild" + i + "StatusApprehended");
let remainHome = document.getElementById("rdoChildsPlacementChild" + i + "StatusWillRemainInTheHome");
if (lastName != '' && firstName != '' && caseNumber != '' && birthDate != '' &&
(apprehended.checked || remainHome.checked)) {
return true;
} else if (i != 1 && lastName == '' && firstName == '' && caseNumber == '' && birthDate == '' &&
(!apprehended.checked || !remainHome.checked)) {
return true;
}
return false;
}
function section4Complete() {
for (let i=1; i++; i<=4) {
if (!lineIsComplete(i)) {
return false;
} else {
continue;
}
}
return true;
}
Thanks.
Related
I have some code that filters an array based on search queries. This works fine but I want to run a function if there are no matches to any/one of the filters.
Filter Code:
function filter() {
let filters = "";
let checkboxDiv = document.getElementById("checkboxes");
let inputs = checkboxDiv.getElementsByTagName("input");
let postcode = document.getElementById("postcodeInput").value;
let suburb = document.getElementById("suburbInput").value;
suburb = suburb.charAt(0).toUpperCase() + suburb.slice(1);
let capacity = document.getElementById("capacityInput").value;
let results = Object.keys(halls);
results.filter(key => {
if (postcode == halls[key]['Location'][3]['Postcode'] && suburb == "") {filters += "Postcode "; return true;}
if (suburb == halls[key]['Location'][1]['Suburb'] && postcode == "") {filters += "Suburb "; return true;};
if (capacity <= halls[key]['Room'][0]['Standing Capacity'] && capacity != "") {filters += "Capacity ";return true;}
return false
}).forEach(key => filterAll([halls[key]]));
}
How might I 'catch' the filter statement if it returns false and run a function?
In english:
If user inputs a suburb, and there are no suburbs that match that, run function.
Thanks in advance :)
I have five input fields. When you delete the content from, let say first, that first input field is populated with input field 2, and the input field 5 is then empty. Again, if you delete the content from the first input field, the content from second goes into the first, and now you have input field four and five empty. And I need that five input field to disappear, to have left only one empty input field. And then again if the third and fourth element are empty, forth should disappear, and so on till there is only first input field left. So, I solve this with hard coded values:
if ((document.getElementsByClassName('requestRightsTitle4')[0].value == '')
&& (document.getElementsByClassName('requestRightsEmail4')[0].value == ''))
{
displayInputField('none', 5);
}
if (
(document.getElementsByClassName('requestRightsTitle3')[0].value == '')
&& (document.getElementsByClassName('requestRightsEmail3')[0].value == '')
&& (document.getElementsByClassName('requestRightsTitle4')[0].value == '')
&& (document.getElementsByClassName('requestRightsEmail4')[0].value == '')
)
{
displayInputField('none', 4);
}
if (
(document.getElementsByClassName('requestRightsTitle2')[0].value == '')
&& (document.getElementsByClassName('requestRightsEmail2')[0].value == '')
&& (document.getElementsByClassName('requestRightsTitle3')[0].value == '')
&& (document.getElementsByClassName('requestRightsEmail3')[0].value == '')
&& (document.getElementsByClassName('requestRightsTitle4')[0].value == '')
&& (document.getElementsByClassName('requestRightsEmail4')[0].value == '')
)
{
displayInputField('none', 3);
}
And now I would like to shorten this code like a real programmer but I don't have the time (sending me to another project) or skills to do so. But I would really like to learn how would that be possible, something like:
for (let i = 0; i < 5; i++) {
if (document.getElementsByClassName('requestRightsTitle' + i)[0].value == ''
&& document.getElementsByClassName('requestRightsEmail' + i)[0].value == '')
displayInputField('none', (i+1));
}
You can set up a listener on all your input fields. If a field is emptied, shift all remaining values to the left and determine which fields need to be displayed (i.e. all fields that have a value and the first empty field).
Here's a complete standalone snippet:
const action = (inputs) => {
const listener = () => {
const values = inputs.map(input => input.value).filter(v => v);
inputs.forEach((input, i) => {
input.value = values[i] || '';
input.style.display = values[i] || !i || values[i - 1] ? '' : 'none';
});
};
inputs.forEach((input, i) => input.addEventListener('input', listener));
};
action([...document.querySelectorAll('input')]);
<input value="One">
<input value="Two">
<input value="Three">
<input value="Four">
<input value="Five">
Better to use querySelector when you only want to select the first element. I'd make an object with the value of each element, and then check the object values:
const valsAreEmpty = ...vals => vals.every(val => val === '');
const vals = [
'requestRightsEmail2',
'requestRightsEmail3',
'requestRightsEmail4',
'requestRightsTitle2',
'requestRightsTitle3',
'requestRightsTitle4',
].map(classStr => document.querySelector('.' + classStr).value);
if (valsAreEmpty(
vals.requestRightsTitle4,
vals.requestRightsEmail4
)) {
displayInputField('none', 5);
}
if (valsAreEmpty(
vals.requestRightsTitle3,
vals.requestRightsEmail3,
vals.requestRightsTitle4,
vals.requestRightsEmail4
)) {
displayInputField('none', 4);
}
// etc
If there are even more Email# and Title# elements, you might use a loop to create the vals instead.
Some remarks :
it looks like you are using html classes to identify single elements in your page
you can use html classes more generically :
<input class="requestRightsTitle" />
<input class="requestRightsEmail" />
<input class="requestRightsTitle" />
<input class="requestRightsEmail" />
<input class="requestRightsTitle" />
<input class="requestRightsEmail" />
<input class="requestRightsTitle" />
<input class="requestRightsEmail" />
On the javascript side : document.getElementsByClassName('requestRightsEmail') will give you a useful array :
let emailInputs = document.getElementsByClassName('requestRightsEmail');
emailInputs[0].value = ...
emailInputs[1].value = ...
emailInputs[2].value = ...
...
// note : this array will be 0-indexed.
// emailInputs[0] will match your 'requestRightsEmail1'
This will probably help you on the css side too.
then you can more easily build and scan arrays of values
e.g :
let titles = document.getElementsByClassName('requestRightsTitle')
.map( e => e.value )
let emails = document.getElementsByClassName('requestRightsEmail')
.map( e => e.value )
// as said above : '3' matches 'requestRights4'
if (titles[3] == '' && emails[3] == '') {
displayInputField('none', 5);
}
if ( titles[2] == '' && emails[2] == ''
&& titles[3] == '' && emails[3] == '') {
displayInputField('none', 4);
}
you can then more easily put this in a loop
a final note, on what your sample does, and how you can rewrite it :
if requestRightsEmail3 is not empty, you already know that all the tests which include requestRightsEmail3 will return false.
So another way to look at your loop is :
if i is not empty, stop here, otherwise, show those extra fields :
for (let i = 3; i >= 1; i--) { // <- decreasing loop
// if one field contains something, stop here :
if (emails[i] != '' || titles[i] != '') {
break;
}
// otherwise : call your displayInputFields
displayInputField('none', i);
}
$(".my-input").each(function () {
var theSelectBoxContainer = $(this).parent().next();
var theSelectBoxValue = theSelectBoxContainer.dxSelectBox('instance').option('value');
var txtvalue = $(this).val();
if (txtvalue != "" && txtvalue!=" ") {
if (i)
field += " and ";
field = field + "'" + $(this).val() + "'";
i++;
}
});
Above my jQuery code. With this code, I overwrite the values entered in the TextBoxes. But I do not want textboxes to be written when null characters are entered. But it is written. I check with if, but it is not. Where is the error?
You can use $.trim(txtvalue) which will validate empty, null and undefined.
Or you can also use:
if (txtvalue === undefined || txtvalue === null) {
// show error messages..
} else {
//execute this code..
}
I am trying to make a form validate where there are radio buttons and textarea. I want nothing to be left empty i.e the form should be completely filled. I have done the radio buttons part of validation where if a user does not select a radio button he will get an error for that particular question. you can see the code here for detailed code.
Please help me out. I am not getting error for textarea.
Just add another check for textarea
function RadioValidator() {
var ShowAlert = '';
var AllFormElements = window.document.getElementById("FormID").elements;
for (i = 0; i < AllFormElements.length; i++) {
var name = AllFormElements[i].name;
if (AllFormElements[i].type == 'radio') {
....
} else if (AllFormElements[i].type == 'textarea') {
if (AllFormElements[i].value == '') {
ShowAlert += name + ' textarea must be filled\n';
}
}
}
if (ShowAlert !== '') {
alert(ShowAlert);
return false;
} else {
return true;
}
}
you didn't write any validation for 'textarea' block. I have updated it with one textarea... add rest validations.
function RadioValidator()
{
var ShowAlert = '';
var AllFormElements = window.document.getElementById("FormID").elements;
for (i = 0; i < AllFormElements.length; i++)
{
if (AllFormElements[i].type == 'radio')
{
var ThisRadio = AllFormElements[i].name;
var ThisChecked = 'No';
var AllRadioOptions = document.getElementsByName(ThisRadio);
var problem_desc = document.getElementById("problem_desc");
for (x = 0; x < AllRadioOptions.length; x++)
{
if (AllRadioOptions[x].checked && ThisChecked === 'No' && problem_desc.value === "")
{
ThisChecked = 'Yes';
break;
}
}
var AlreadySearched = ShowAlert.indexOf(ThisRadio);
if (ThisChecked == 'No' && AlreadySearched == -1 && problem_desc.value === "")
{
ShowAlert = ShowAlert + ThisRadio + ' option must be selected\n';
}
}else if(AllFormElements[i].type =='textarea')
{
// add your rest of text area validations here
var problem_desc_1 = document.getElementById("problem_desc");
if(problem_desc_1.value === "")
{
ShowAlert = ShowAlert + '"Services (Please Specify)" can not be blank. \n';
}
}
}
if (ShowAlert !== '')
{
alert(ShowAlert);
return false;
}
else
{
return true;
}
}
You need to add a check for textarea as well
In your javascript check you have only added a condition for type radio.
check for textarea type as well and add error if the value is blank.
I really don't know what the issue is here. As far as I can see, the code is simple and should work fine.
var Prices="";
for (var PriceCount = 1; PriceCount <= 120; PriceCount++) {
var CurrentPrice = "Price" + PriceCount;
if (prevDoc.getElementById(CurrentPrice).value != null) {
if (Prices == "") {
Prices = prevDoc.getElementById(CurrentPrice).value;
} else {
Prices += "," + prevDoc.getElementById(CurrentPrice).value;
}
} else {
break;
}
}
There could be up to 120 hidden inputs on the form. The moment we check for an input that doesn't exist the loop should break. My test page has two input elements that get pulled. On the third (the null) I get this error in firebug:
prevDoc.getElementById(CurrentPrice) is null
if (prevDoc.getElementById(CurrentPrice).value != null) {
Yes it is null...that's what the check is for ಠ_ಠ
Does any one know what I'm doing wrong? This seems like it should be really straight forward.
EDIT:
for clarity's sake, prevDoc=window.opener.document
if (prevDoc.getElementById(CurrentPrice).value != null) {
can be expanded to:
var element = prevDoc.getElementById(CurrentPrice);
var value = element.value; /* element is null, but you're accessing .value */
if (value != null) {
value is never null.
If it is not filled in, the value would be "" or a length of zero.
If the element does not exist, you would check for the existence of the element.
var CurrentPrice = "Price" + PriceCount;
var elem = prevDoc.getElementById(CurrentPrice);
if (elem && elem.value != null) {
I think it should be:
var Prices="";
for (var PriceCount = 1; PriceCount <= 120; PriceCount++) {
var CurrentPriceId = "Price" + PriceCount,
CurrentPrice = prevDoc.getElementById(CurrentPriceId);
if (CurrentPrice != null) {
Prices = (Prices == "") ? CurrentPrice.value : (Prices + "," + CurrentPrice.value);
}
else break;
}
Try
if (prevDoc.getElementById(CurrentPrice) !== null)