Javascript validate X number of fields in an HTML form - javascript

I have a form, that has about 10 text entries (user, address, email etc;)
and about 50+ entries that are quantity entries (users select 2x of this item, 5x of this item).
Now I inherited this form from someone else (now its my duty to keep it up to date, when the customer requests it).
I don't want to re-write it all, but I would like to add validation for the quantity fields.
Now the quantity fields are all named different things (b1,c55,d,12)
Basically I would like to write a script (but don't know how to search for this, or accomplish this) JS side, that would ignore the tags I know (user, address, email etc;) but check if the others are numbers (either empty - not selected, or 1-99)

Apply a class to the elements (my code uses a class check) like so:
<input type="text" name="b1" class="check" />
and the following jQuery code, which will only check those elements with the check class.
$('#myformid').submit(function(){
$(':input.check').each(function(){
field = $(this);
valInt = parseInt(field.val()); // value as an integer
if (isNaN(valInt) || (valInt < 1 || valInt > 99)) // displays an error if the val is < 1 or > 99
alert('Error in the field ' + field.attr('name') + ': must be number from 1-99'); // change this to whatever you want the form to do if there's an error
});
});
Basically what this does is the following: when the form is submitted, it goes through every field you'd like it to (denoted :input.class to catch each field with the correct class) and checks if it's (a) a number, and (b) less than 1 or greater than 99. If it's a number and is outside the range, it alerts the user of an error. You can change the alert() notification to whatever error management you'd like your form to have.

Related

How do we declare multiple choice answers (from gform) in one cell (gsheet response) as separate values in an array? (GAS)

Hi Helpful Contributors,
I have a gform where user can select more than 1 answer. In response sheet, we will see the multiple answers will be printed in one cell of a column separated by comma. For that matter, I have some calculation to do on each answer. So, I was thinking to declare each input separated by comma as an array value so that I can then refer each value by it's index number in that array. Is this possible?
Below is my code that I tried but when I tried to refer back to that array on index[0], the output is still all the values in that same cell, so I think all are still kept as 1 value of array.
function mytest(){
var sheet=SpreadsheetApp.getActiveSheet();
var input=[];
var extraitem=sheet.getRange(lastorder,77).getValue(); //this cell keeps the multiple answers : "Change of address, Change of mobile no., Change of vehicle type, Change of license type"
input.push(extraitem.split(','));
Logger.log("myinput :"+input[0]); // check the value in position 0 is the first among the multiple answers
}
Please correct my code. Thank you in advance.
The issue with your code is that you push an array extraitem.split(',') into another array input=[]. As a result, input[0] is the full array extraitem.split(',').
To get the first element of the extraitem.split(',') array you can do Logger.log(input[0][0]) or (preferably) simply ignore the push part:
function mytest(){
var sheet=SpreadsheetApp.getActiveSheet();
var extraitem=sheet.getRange(lastorder,77).getValue();
var input= extraitem.split(',');
Logger.log("myinput :"+input[0]);
}
Demonstration:
const extraitem = "Change of address, Change of mobile no., Change of vehicle type, Change of license type";
const input = extraitem.split(',');
console.log("myinput :" + input[0]);

AngularJS not finding values in array

I have a AngularJS app developed.
On a view I have a list of items - each with its own set of radio buttons. The list and buttons are built at run-time from an API call.
Both the list and radio buttons can be of any length e.g. list item 1 might contain 3 radio buttons while list item n might contain 2 radio buttons.
When the user selects a radio button I fire a ng-click method that sends both the list ID as well as the radio button ID to the controller.
The view looks as follows and I have tested this and the values are being sent to the controller.
<label class="radio-button" ng-repeat="option in checkItemDescription.options">
<input type="radio" name="option_question_id_{{checkItemDescription.fleetcheckitemid}}"
ng-model="checkItemDescription.selected_id"
ng-click="doSomething(checkItemDescription.fleetcheckitemid, option.fleetcheckid)"
ng-value="option.fleetcheckid">
<div class="radio-button__checkmark"></div>
Description: {{option.checkvaluedesc}}
</label>
In my doSomething() method i am trying to see if either the checkItemDescription.fleetcheckitemid or the option.fleetcheckid id is in a existing array.
I use indexOf() method to compare the values but the method does not seem to work - even though console.log() shows values are sent to the controller.
Below is my doSomething() method.
$scope.doSomething = function(fleetCheckItemID, fleetCheckID)
{
if ( $scope.initialFleetCheckIssueItemIDArray.indexOf(fleetCheckItemID))
{
console.log("Yeah!"); // Never gets to here even though logs show values exist
}
else
{
console.log("Ah!"); // Always get here
}
}
What I need to do is to to create a JSON object with the list item ID, radio button ID and some other values e.g. date/time based on the user selection to send to my Database.
Is this the best way to do it or is there a better way?
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
-referenced from MDN.
so if your element is first in the collection then indexOf would return 0 which would result in the execution of else block so change your if condition like this.
if ( $scope.initialFleetCheckIssueItemIDArray.indexOf(fleetCheckItemID) != -1 )
{
//element found, do stuff here.
}
else
{
//element does not found, else stuff here.
}

Mongodb: check value equality in any document

I have a form on my site where users can enter a number into the subNum field. When the user submits the form, I want to check if the value they've entered already exists as a value in any existing document. This is all done in javascript/meteor
All form data gets put into an object like this:
participantObject = {
subNum: parseInt(number)
}
This object then gets inserted as a document into the Participants collection
When the submit button is clicked, I need to check whether the number they've entered has already been entered (i.e. exists as the value for subNum in any document). If so, prevent form submit and show an error
I'm trying the check with something like this:
var existingSubs = Participants.find(
{subNum: {$eq: participantObject.subNum}}
).count();
console.log(existingSubs);
I am hoping that the above will find me all documents where subNum is equal to the value entered (participantObject.subNum), and console log the count of the number of matching documents
The problem is that in the console log I see Unrecognized operator: $eq
Am I using the equality operator incorrectly?
Is there a more efficient way to perform a check like this?
You can omit $eq operator:
var existingSubs = Participants.find(
{subNum: participantObject.subNum}
).count();

Unable to Receive Selected Checkboxes PHP

I have two separate group boxes like so:
<form id = "query" method = "post" action = "search.php">
<input type = "checkbox" name = "col_list[]" value = "cheese">cheese</input>
<input type = "checkbox" name = "col_list[]" value = "tomatoes">tomatoes</input>
<input type = "checkbox" name = "col_order[]" value = "italian">italian</input>
<input type = "checkbox" name = "col_order[]" value = "wheat">wheat</input>
<input id = "submit" name = "submit" type = "submit" value = "submit" display = "inline></input>
</form>
These group boxes will change depending upon a value selected from a drop-down menu above it (done in javascript). For example, if the value of sandwich is selected, then these two group boxes will be displayed, however, if the value of pizza was selected, there would be a group box with various toppings and another with the types of crust. I can post that code if needed
In my PHP code, I have:
$columns = $_POST["col_list"];
$order = $_POST["col_order"];
I attempt to print both of the arrays, yet I am always met with a screen that takes forever to load, followed by my "error" message that found both the arrays to be empty (I simply used the empty(var) method).
If I select any amount of top boxes, but no boxes on the separate group, then my code is fine and I have all of the selected values of the first group. However, if I compound onto that and select any amount from the second group, the problem ensues.
I have no idea as to why they would be empty. Any thoughts?
Naming two checkbox with the same name parameter is a mistake... probably if one col_list array has some elements, the other is empty... so the $_POST will return a empty array.
Try naming your checkboxes with differente names and change your javascript
try this:
if (is_array($_POST['col_list'])) {
foreach($_POST['col_list'] as $result) {
...
}
}
Edit: Duplicate name fields are permissible in PHP. Thanks to Quentin for pointing this out.
The name field of the input tag is used as the key for POST and GET queries. You need to match them exactly, like:
$columns = $_POST["col_list[]"];
$order = $_POST["col_order[]"];
Unless there is some crazy array syntax that nobody told me about...
Also, I would refrain from using the same value for the name field for multiple fields as it has to choose one of them to send and you may not like which field it sends to you. Instead, try disabling/removing the component when your form's submit method is called, or simply assign all your input fields with unique names.

How to delete selected checkbox rows in an Oracle APEX Classic Report using Ajax

Within Oracle APEX v4.2.2, I have a simple classic report that has as a first column, a checkbox f50 setup attached to the table's ID column, which will allow a user to check all or specific rows and remove these records from the report/table.
An example report might be something like:
ID Col2 Col3 Col4
----------------------------
1 10 20 30
2 5 8 9
3 92 88 12
4 1 2 44
5 95 77 88
The requirement I am after is that I want to perform this whole process of checking the IDs and the removal of these records done without having to submit the whole page but would like it done via an AJAX method using apex.process.server if possible.
UPDATE: Just a bit more background on this requirement based on the report I am attempting to hook this apex.process.server checkbox IDs, i.e.:
ID Report Column above within Report Attributes heading looks like this:
<input type="checkbox" label="Select Code" onclick="$f_CheckFirstColumn(this)" />
Drilling down into this ID column under HTML Expression is the following:
<input type="checkbox" #ID# value="#ID#" name="f50" id="f50_#ROWNUM#"/>
Region Source:
SELECT A.ID,
A.REQ_NO COL2,
A.CODE_ID||apex_item.hidden(20, A.CODE_ID)||apex_item.hidden(30, A.ID) COL3,
GROUP_VALUE COL4
FROM MY_TABLE A
WHERE A.REQ_NO = :REQ_NO
I believe inorder to have APEX store the values within the apex_application.g_f50.countarray of the IDs to be removed, the page needs to be submitted.
Using apex.process.server, can the ids, as they are checked, be passed as a JavaScript array to an on demand process that will then use these ids to perform the required delete operation?
How can I achieve the above via an AJAX means (no page refresh at all)?
Given this query for a report
select
"EMPNO",
"ENAME",
apex_item.checkbox2(2, 0) check1,
apex_item.checkbox2(3, 0) check2,
apex_item.checkbox2(4, 0) check3
from EMP
With EMPNO set to "Hidden" - so it'll generate a hidden input item appended to the last column.
To update a certain record you'll need a PK and a value to update the row with. That is why I'm using EMPNO. I'll pass that to the on-demand process.
function selectorToArray(pSelector){
function getVal(pNd){
switch ( pNd.nodeName ) {
case "INPUT":
switch ( pNd.type ) {
case "checkbox":
return $(pNd).prop("checked");
break;
default:
return $(pNd).val();
};
break;
default:
return $(pNd).val()
};
};
var lArray = [];
$(pSelector).each(function(){
lArray.push(getVal(this));
});
return lArray;
};
The function selectorToArray will fetch the values for the given selector to an array and get the value. As you might know, you can pass values to a process with x01, x02, ... But there are also arrays: f01, f02,...
With the following code you can send values over to the ondemand process:
function sendCheckboxes(){
var lf01 = [], lf02 = [], lf03 = [], lf04 = [];
lf01 = selectorToArray("input[name=f01]");
lf02 = selectorToArray("input[name=f02]");
lf03 = selectorToArray("input[name=f03]");
lf04 = selectorToArray("input[name=f04]");
apex.server.process("PROCESS_CHECKBOXES", {f01: lf01, f02: lf02, f03: lf03, f04: lf04});
};
You can use those just like you would otherwise: loop over them:
DECLARE
l_pk VARCHAR2(30);
l_check1 VARCHAR2(30);
l_check2 VARCHAR2(30);
l_check3 VARCHAR2(30);
BEGIN
-- f01: PK
-- f02: checkbox values column1
FOR i IN 1..apex_application.g_f01.count
LOOP
l_pk := apex_application.g_f01(i);
l_check1 := apex_application.g_f02(i);
l_check2 := apex_application.g_f03(i);
l_check3 := apex_application.g_f04(i);
apex_debug.message('Record with PK '||l_pk||': check1? '||NVL(l_check1, 'NO')||': check2? '||NVL(l_check2, 'NO')||': check3? '||NVL(l_check3, 'NO'));
END LOOP;
END;
In your code, there are 3 item arrays: f20, f30 and f50. f30 holds the row PK value, while f50 is used for the checkbox.
Don't be fooled by the array naming. Apex itself uses the f## arrays for submission, true enough. And your items with name f50 will indeed be in array g_f50 on page submit.
You can however also use arrays f01 to f20 (don't think it goes up to 50) for ajax calls! They're a great addition to the variables x01-x20!
When using the arrays to send a bulk of values to your process, instead of one-by-one, I think it's most useful to not just send an array of PK values, with a position-matched array of values to interact with. This isn't as valuable when you use a report without pagination though, but still. With pagination, the idea is that you don't really know what set of data was just interacted with. Of 100 records, 10 rows were presented. Of those 10 rows, 6 were checked on render, and on submit only 5 are. Which ones are checked and which ones are unchecked. Knowing which 5 are checked doesn't mean you know the unchecked ones.
When you include a PK column however, you'll always have those 10 rows and you're able to identify clearly which records has been checked or unchecked.
For instance, 10 records in your report will (=should!) mean that 10 values are put in an array (eg l_f01) with the PK value and 10 more values are put in another array (eg l_f02) with eg a checked indicator. So when passing those on to the on-demand process, you'll be able to loop over array f01 reliably, and fetch the checked or unchecked indicator from array f02 with your current index variable used for f01.
Plainly put, you're building up 2 arrays with this sort of value set:
f01 - IDs | f02 - checkeds
----------|---------------
4520 | false
4521 | true
4527 | false
4561 | true
4578 | true

Categories