Unable to Receive Selected Checkboxes PHP - javascript

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.

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]);

How to get a specific value from a form text field inside a loop?

I am busy with a school project that mainly focuses on showing data from a database. We build a map with Google Maps API so we could show markers with specific data when you click on them. The data tagged to the marker are self-written JavaScript variables. It all works but now comes my real problem. We also have an overview of al datasets were you can easily select any dataset. When a dataset is clicked you will be redirected to the page with the map and the specific data. My problem is that I need to convert the data I get from the database using PHP and MySQL to JavaScript variables that are equal to the variable from the map.
My idea was to create an invisible form where there are six text fields that are filled with the database rows (this part works), next I have to get the specific value of the text field that belongs to the clicked dataset. The only problem is that I am generating the overview of the datasets with a loop so data can be added to the database and the code doesn't need to be adjusted. But I don't know how to get the specific value.
I have tried several ways to do this including getElementbyClass (works but you always need to define the array number), getElementbyID (only grabs the first value because an ID can only be used once), getElementbyName (also only grabs the first value) and some stuff that has to do with jQuery: siblings, next, things that grab the closest value (but I got an empty value).
/ Code is below /
HTML & PHP:
<?php
$sql = "SELECT * FROM containers";
$result = mysqli_query($connectie, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) { ?>
<div class="Border">
<?php echo $row["container_address"]?>
<form class="senddataform">
<input type="text" name="addressField" id="addressField" value="
=$row['container_address']?>">
<input type="text" name="maxcontent" id="maxcontentField" value="<?
=$row['container_maxcontent']?>">
<input type="text" name="name" id="nameField" value="<?
=$row['container_name']?>">
<input type="text" name="beschikbaarheid" id="beschikbaarheidField"
value="<?=$row['container_beschikbaarheid']?>">
<input type="text" name="gebruikt" id="gebruiktField" value="<?
=$row['container_gebruikt']?>">
<input type="text" name="legingdagen" id="legingdagenField" value="<?
=$row['container_legingdagen']?>">
</form>
<?php } ?>
My empty JavaScript function:
function sendContainerData(){
}
JavaScript variables that need to be filled with the data:
var containerAddress =
var containerMaxcontent =
var containerName =
var containerBeschikbaarheid =
var containerGebruikt =
var containerLegingdagen =
You can think of it this way: Declare those variables that need to be filed with data as global variables. Then in a function, you can get the elements from the invisible text fields by class (which returns an array that that can be accessed by index). Now, since you know the order in which the invisible text fields are displayed apriori (from the PHP loop), you can assign the value of each text field to the correct variable. For example, the first text field value can be mapped to the correct variable, and so on. Something like this:
var containerAddress;
var containerMaxcontent;
var containerName;
var containerBeschikbaarheid;
var containerGebruikt;
var containerLegingdagen;
function sendContainerData(){
var values = document.getElementByClass('someclass'); //returns an array
//Now use your knowlege of the order of the textfields to map the values
containerMaxcontent = values[0].value; //maps maxcontent to maxcontent variable
containerName = values[1].values; //maps name text field to name variable
containerBeschikbaarheid = values[2];//
containerGebruikt = values[3]; //
containerLegingdagen = values[4];
}
Then you can use those variables as you wish. Note that you can do this for IDs too. Only you will need to make your IDs an array. All your IDs will look like this id="someID[]". Hope this is clear enough and it helps

Make an array with data linked to a select menu

(hopefully this problem hasn't been resolved yet) if so, I am sorry and please link me to the solution. (this is an exercise for the Java course I am attendind nowadays so I am quite novice with Javascript. )
I have a select menu with trip destinations. There are 4-5 destinations (Paris, London, Amsterdam, Berlin, New York..) For each destination there is a short description and a certain price.
So the exercise says: when someone clicks on an option from the select menu , the appropriate description has to appear in the textarea and the appropriate price in the text input. (it's some basic stuff).. I know how some html objects work, I just can't seem to find the best way to do this with select object. I did it with checkboxes via name attribute and a for loop. with radiobuttons as well.. but with select options I am stuck. I don't need the solution for my exercise, I just need a sample code but something I understand.
Ex:
Paris
etc
something like : for selected option [i], textarea.value = the description associated to each trip destination and text input.value = the price of the trip .
I don't want something like : if selectedIndex[0]---textarea.value = X
I need to do something like an Array of destinations.. trips[i] = new Array [] and fill the array of the trip array with the prices and the var's of the description strings.. (I hope I have been clear about everything I need .
Thank you all.
Define an object array where you make a key value mapping of each place and an index.
var array = [{'key': 0, 'value': 'Paris'},{'key': 1, 'value': 'London'},{'key': 2: 'value': 'Amsterdam'}...]
Loop through the array and populate your select options:
<select>
{array.map((each)=>{return (<option value= each.key></option>)})}
</select>
In your event handler, map the key to value in the array to get your text.
selectHandler(val){
let result = array.find((each)=>{return each.key === val});
var textarea = document.getElementById('textArea');
textarea.value = result.value;
}

How to detect an exist element in an array with one or more elements

Here is the code in Jsfiddle
It's a simple form to create a new form : label and it's input
I already did four validations :
if input is empty
if there in no label before adding an input
if the input id is not matched the label
But there is a new problem : if I enter an input id which already exist, it will add a second input for the same label,
For example :
I created two labels and their inputs
if I enter "a" in "input id" again, it will add a second input to label "a"
And if I add a same label again, then for adding the input is the same problem, it will add to both of them.
To avoid this problem, I think that I need to check : if the input value is matched any existing input id, so don't add the input, the same for label
I try to do this :
create an empty array
var inputExist = [];
push the id in this array every time I add an new input inputExist.push($('#input_id').val());
do a loop for in the else to detect if the input value matched any element in the array
for (var i = 0; i < inputExist.length; i++){
if($('#input_id').val() == inputExist[i]){}
}
Scince the if condiction is based on the loop, I have to put the if inside the loop, which means the else too, so that will cause the adding input order do array.length times, not good!
I have no idea how to separer the detection and the instruction followed.
Any ideas?
Create an array where you store the labels you already added (or the values);
var labelsArray = [];
var valuesArray = [];
Then when you handle the button click, add the following check:
var currentLabel = $('#lable_name').val();
if(labelsArray.indexOf(currentLabel) > -1){
return;
}
In alternative you can use the jQuery function:
$.inArray(currentLabel, labelsArray)
Do the same with the values and you will be able to avoid duplication.
In alternative you can use jQuery to search for an input

Javascript validate X number of fields in an HTML form

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.

Categories