Get input values of a form hidden in Jquery with PHP - javascript

I have a bit of a problem here (or big I actually don't know) I'm new with PHP and I want to know if is possible to get the values of a form input field with PHP that are appended with Jquery is an user choose the right option.
The thing is I'm getting all the values in all the input fields that are previously loaded on the page. All the values are required in order to submit the form, but the thing is that the fields that are appended in the form (with Jquery) when the user chooses and option of a select field aren't being processed by PHP and I can't access their values.
So basically: If the user doesn't select any number (0 by default) the fields don't appear and they are not required to fill in, although, if the user select "1 to 10" in the select input the amount of input fields appear and the NEED to be filled in to submit the form.. how can I achieve that?
Here is the code
This is the PHP code I have before the DOCTYPE in the php form page:
$errores = [];
$faltantes = [];
if (($_SERVER['REQUEST_METHOD'] == 'POST') && (isset($_POST['continue']))) :
$expected = ['nombres', 'apellidos', 'cedula_tipo', 'cedula_no', 'fecha_nacimiento', 'sexo', 'edad', 'civil', 'direccion', 'ciudad', 'pais', 'tel_hab', 'tel_cel', 'email', 'plan', 'pago', 'beneficiarios'];
$requeridos = ['nombres', 'apellidos', 'cedula_tipo', 'cedula_no', 'fecha_nacimiento', 'sexo', 'edad', 'civil', 'direccion', 'ciudad', 'pais', 'tel_hab', 'tel_cel', 'email', 'plan', 'pago', 'beneficiarios'];
require './includes/tdaform_process1test.php';
if (!$errores && !$faltantes) :
endif;
endif;
This is the form field where the user selects and based on his selection the other inputs appear:
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="POST" id="planilla_tda" name="planilla_tda">
<div class="bene-select">
<h4>Puedes agregar beneficiarios a tu plan.</h4>
<label for="beneficiarios">Cantidad de beneficiarios</label>
<select name="beneficiarios" id="beneficiariosCount">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
</div>
<div id="beneficiarios" class="beneficiarios"></div>
<button type="submit" class="btn-contacto" name="continue" value="submit">enviar planilla</button>
</form>
This is the DIV (that contains the input fields) that is appending when the user makes a selection other than "0":
<div class="beneficiario-wrap">
<label for="nombre_bene">Nombre y Apellido</label>
<input type="text" name="nombre_bene[]" value="">
<label for="cedulabene_no">Cedula beneficiario</label>
<div>
<select name="cedulabene_tipo">
<option value="Venezolano" selected>V </option>
<option value="Extranjero">E </option>
</select> <input type="text" name="cedulabene_no[]" value="" maxlength="8">
</div>
<label for="edad_bene">Edad beneficiario</label>
<input type="text" name="edad_bene[]" value="">
</div>
This is how I'm appending the input fields with Jquery:
const divToAppend = '<div class="beneficiario-wrap"><label for="nombre_bene">Nombre y Apellido</label><input type="text" name="nombre_bene" value=""><label for="nombre_bene">Cedula beneficiario</label><div><select name="cedulabene_tipo"><option value="Venezolano" selected>V </option><option value="Extranjero">E </option></select> <input type="text" name="cedulabene_no" value="" maxlength="8"></div><label for="edad_bene">Edad beneficiario</label><input type="text" name="edad_bene" value=""></div>';
let number = $('#beneficiarios').val();
$('#beneficiariosCount').on('change', function () {
$('#beneficiarios').html('');
number = $(this).val();
for (let i = 0; i < number; i++) {
$('#beneficiarios').append(divToAppend);
}
});
and this is how I'm looping through all the the fields and make them require with PHP:
$suspect = false;
$emailPattern = '/Content-type:|Bcc:|Cc:/i';
function isSuspect ($value, $emailPattern, &$suspect) {
if (is_array($value)) :
foreach ($value as $item) {
isSuspect($item, $emailPattern, $suspect);
}
else :
if (preg_match($emailPattern, $value)) {
$suspect = true;
}
endif;
}
isSuspect($_POST, $emailPattern, $suspect);
if (!$suspect) :
foreach ($_POST as $key => $value) {
$value = is_array($value) ? $value : trim($value);
if (empty($value) && in_array($key, $requeridos)) {
$faltantes[] = $key;
$$key = '';
} elseif (in_array($key, $expected)) {
$$key = $value;
}
}
endif;
As I said I'm really new with PHP and I came out with this approach with self-education. So, Please help!

Related

Unable to return value of dropdown value in PHP

I am trying to retrieve a dropdown value, but the value isn't being returned in PHP. It returns as empty. I have other dropdowns in the form, but the only difference between them and this one is that there is a function associated to it. Which the javascript actually returns.
Thanks for your help. Code for the dropdown is below.
function validateDays() {
var e = document.getElementById("age_category");
var age_category = e.options[e.selectedIndex].text;
if (age_category == "Sub-Junior") {
console.log("Success");
} else {
console.log("Not Sub-Junior");
}
}
<?php
if(isset($_POST['submit'])){
echo $age_category = $_POST['age_category']
}
?>
<form action="my_page.php" method="POST">
<div class="form-group">
<!-- AGE CATEGORY -->
<select class="form-control" name="age_category" id="age_category" onchange="validateDays();" required>
<option value="">Age Category</option>
<option value="Sub-Junior">Sub-Junior</option>
<option value="Junior">Junior</option>
<option value="Open">Open</option>
<option value="Master 1">Master 1</option>
<option value="Master 2">Master 2</option>
<option value="Master 3">Master 3</option>
<option value="Master 4">Master 4</option>
</select>
</div>
</form>
You trying get submit value:
$_POST['submit']
and You need age_category:
$_POST['age_category']
You are trying to check isset function on $_POST['submit'] but "submit" reference doesn't exists anywhere in your form.
First create a button or something else and name it "submit" and then submit your form.
Currently you are not submitting your form in your code
Problem solved. When I was checking to see if it was empty. I was actually assigning it to be empty.
So it looked like this
if($age_category = "")
instead of
if($age_category == "")

Select problems in IE9 - in other browsers it works perfectly

I have problems with this particular form, i need first to select a value and then to submit the form. Submit form works good, however the default selection value in all browsers is selected and it is Acceptable, except in IE where no default selection value is selected. In IE there is nothing selected by default.
How do I fix this?
Picture of the problem :
:
<select name="formQuality" id="formQuality" value="acceptable">
<option value="acceptable">Acceptable</option>
<option value="good">Good</option>
<option value="better">Better</option>
<option value="excellent">Excellent</option>
<option value="best">Best</option>
</select>
<?php
if(isset($_POST['SubmitButton'])){ //check if form was submitted
$input = $_POST['inputText']; //get input text
$varQuality = $_POST['formQuality'];
$message = "Success! You entered: ".$input;
}
?>
<br>
<form action="" method="post">
<h1>Choose Quality:</h1>
<?php
$thequa = htmlspecialchars($_POST['formQuality']);
?>
<select name="formQuality" id="formQuality" value="<?php echo $thequa;?>">
<option <?php if ($thequa1 == 'acceptable') { ?>selected="true" <?php }; ?> value="acceptable">Acceptable</option>
<option selected="true" value="acceptable">Acceptable</option>
<option <?php if ($_POST['formQuality'] == 'good') { ?>selected="true" <?php }; ?> value="good">Good</option>
<option <?php if ($_POST['formQuality'] == 'better') { ?>selected="true" <?php }; ?> value="better">Better</option>
<option <?php if ($_POST['formQuality'] == 'excelent') { ?>selected="true" <?php }; ?> value="excellent">Excellent</option>
<option <?php if ($_POST['formQuality'] == 'best') { ?>selected="true" <?php }; ?> value="best">Best</option>
</select>
<textarea name="inputText" cols="100" rows="20" style="border:solid 1px orange;"><?php echo $thetext;?></textarea>
<p>
<input type="submit" value="Rewrite" name="SubmitButton"/>
</form>
The intended way to preselect an option is setting the selected attribute on the option element, rather than adding a value attribute to the select field.
<select name="formQuality" id="formQuality">
<option value="acceptable" selected>Acceptable</option>
<option value="good">Good</option>
<option value="better">Better</option>
<option value="excellent">Excellent</option>
<option value="best">Best</option>
</select>
This produces the expected result in all browsers, including IE.
Use selected="selected"
Like,
<option value="My Default" selected="selected">
to make an option as default selected value. This works in all browsers.

Safari not reading required field

I created an option field and with it I set it to a required field and it works perfect on Chrome/internet explorer/Android's internet. However, when going to my site with Apple's safari on mobile, the required field does not stop the customer when trying to proceed and saying that is a required field.
<div class="productdetailquantity"><?php echo"<form action='./itemsadded.php?view_product=$product_id' method='POST'>"?>
<select class="productsize" name='size' required>
<option value=''>Select a Size</option>
<option value='Small'>Small</option>
<option value='Medium'>Medium</option>
<option value='Large'>Large</option>
<option value='XL'>XL</option>
</select>
Is there something else I have to add other than the html5 'required' field for this to make it work on Safari or why isn't this working?
If Safari does not support it, what is another way I can implement this field to be required?
UPDATE:
After figuring out it isn't supported, I tried doing some JS with it, but my message OR alert won't display. However, it doesn't allow the customer to move forward unless a size is picked, but I need the message to display so they know why.
<div class="productdetailquantity"><?php echo"<form action='./itemsadded.php?view_product=$product_id' method='POST' id='formID'>"?>
<select class="productsize" name='size' required><span id="sizeoptionMSG" style="margin-left:6px;color:darkred;"></span>
<option value='' id="sizeoption">Select a Size</option>
<option value='Small'>Small</option>
<option value='Medium'>Medium</option>
<option value='Large'>Large</option>
<option value='XL'>XL</option>
</select><br><br>
<select class="productquantity" name='quantity'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
<option value='6'>6</option>
<option value='7'>7</option>
<option value='8'>8</option>
<option value='9'>9</option>
<option value='10'>10</option>
</select>
</div><br><br>
<div class="productdetailaddbutton">
<?php
echo "<input type='hidden' name='product_id' value='$product_id' />
<input type='submit' class='addtocart' name='add_to_cart' value='Add to cart' />";
?>
<script>
var form = document.getElementById('formID'); // form has to have ID:
<form id="formID">
form.noValidate = true;
form.addEventListener('submit', function(event) { // listen for form submitting
if (!event.target.checkValidity()) {
event.preventDefault(); // dismiss the default functionality
document.getElementById('sizeoptionMSG').innerHTML = document.getElementById('sizeoption').value == '' ? 'Please, select a size' : ''; // Show message
document.getElementById('sizeoption').style.borderColor = document.getElementById('sizeoption').value == '' ? 'darkred' : ''; // color field's border
if (document.getElementById('sizeoption').value == '') document.getElementById('sizeoption').focus(); // Put cursor back to the field
alert('Please, select a size.'); // error message
}
}, false);
</script>
At this time, Safari does not support the "required" input attribute.
See here: http://www.w3schools.com/html/html_form_attributes.asp

submitting via jquery (smarty)

im using SMARTY and php4. (cant upgrade...)
i have two selects where i move contet which i get from database from one select to the other with buttons like this : |<<| |>>| using jquery.
Now my problem is submitting everything which is in the right select.
code im using so far to submit my right select. (select1 = left) (select2 = right)
function submitForm()
{
$('form').submit(function() {
$('#select2 option').each(function(i) {
$(this).attr("selected", "selected");
});
});
}
My right select:
<form method="POST" name="arbeitsplatz_werte">
<select style="width:285px;" id='select2' name='select2' size="20" multiple class='fr'>
{foreach item=tef4 from=$tef4_button_inhalte}
{html_options title=$tef4.VCARBPLATZ selected=$smarty.post.VCARBPLATZ values=$tef4.VCARBPLATZ output=$tef4.VCARBPLATZ|cat:" "|cat:$tef4.VCBEZEICHNUNG}
{/foreach}
</select>
</form>
in php:
$select_post = $_POST['select2'];
Now the problem is, when submitting, i only get the last row of my select2 content AND instead saving each row how intended like this
$select_post[0] = {W840-PG}
$select_post[1] = {W840-SN}
$select_post[2] = {W840-SZ}
$select_post[3] = {W840-VM}
.
.
.
it saves only the last row like this
$select_post[0] = {W}
$select_post[1] = {8}
$select_post[2] = {4}
$select_post[3] = {0}
$select_post[3] = {-}
$select_post[3] = {V}
$select_post[3] = {M}
generated select1 :
<div style="overflow:auto;"><select style="width:285px;" id='select1' name='select1' size="20" multiple class='fl'>
<option label="T4-100 TEF4-TS Gruppenleiter " value="T4-100">T4-100 TEF4-TS Gruppenleiter </option>
<option label="T4-101 TEF4-TS Fachgruppenleiter " value="T4-101">T4-101 TEF4-TS Fachgruppenleiter </option>
<option label="T4-102 TEF4-TPM Fachteamleiter " value="T4-102">T4-102 TEF4-TPM Fachteamleiter </option>
<option label="T4-103 TEF4-TS Fachteamleiter Mechanik Im " value="T4-103">T4-103 TEF4-TS Fachteamleiter Mechanik Im </option>
</select></div>
generated select2:
<div><select style="width:285px;" id='select2' name='select2' size="20" multiple class='fr'>
<option label="W840-PG W840-Phasengeber instands. Gr.59 Treppte" value="W840-PG">W840-PG W840-Phasengeber instands. Gr.59 Treppte</option>
<option label="W840-SN W840-Stanzen WZ-Instands. Gr.20 Eller" value="W840-SN">W840-SN W840-Stanzen WZ-Instands. Gr.20 Eller</option>
<option label="W840-SZ W840-Spritzen WZ-Instands. Gr.60 Porkert" value="W840-SZ">W840-SZ W840-Spritzen WZ-Instands. Gr.60 Porkert</option>
<option label="W840-VM W840-Messen - Gruppe 99 Rist" value="W840-VM">W840-VM W840-Messen - Gruppe 99 Rist</option>
</select></div>
someone knows where im screwing up ? :X
Problem solved..
the name of the select2 should be "select2[]"! like this he submits an array..
<select style="width:285px;" id='select2' name='select2[]' size="20" multiple class='fr'>

div inside form not being 'seen'

I have a div inside my form which is filled with a field based on the value of the select box above it. This field always comes back as 'null' when submitted, I put a div around other parts of the form to test if it was in fact the div itself and each field with a div around it kept coming back as 'null'.
<form>
<span id="writenode"></span>
<input type="button" value="Add language" onClick="addlanguage()" >
<input type="submit" value="Submit" >
</form>
<!--This div below is called every time I want to add a new 'instance' of this form
this div works fine, its when i add a div inside that one I get 'null'-->
<div id="readnode" style="display: none">
<select name="rank">
<option disabled="disabled" selected="selected">Rating</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
<option value="0">0</option>
</select>
<select name="time">
<option disabled="disabled" selected="selected">Time</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
<option value="0">0</option>
</select>
<input type="button" value="X"
onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />
</div>
So the code above works fine its when i add a div inside i get 'null' like below;
<form>
<span id="writenode"></span>
<input type="button" value="Add language" onClick="addlanguage()" >
<input type="submit" value="Submit" >
</form>
<!--This div below is called every time I want to add a new 'instance' of this form
this div works fine, its when i add a div inside that one I get 'null'-->
<div id="readnode" style="display: none">
<select name="rank">
<option disabled="disabled" selected="selected">Rating</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
<option value="0">0</option>
</select>
<div id='testdiv'>
<select name="time">
<option disabled="disabled" selected="selected">Time</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
<option value="0">0</option>
</select>
</div>
<input type="button" value="X"
onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />
</div>
Whats my best way around this? and how would I go about doing it?
EDIT: The Div 'readnode' is called and placed inside the form when needed, replacing the div 'writenode' which is seen inside the form above. This div works perfectly fine. When i add another div (testdiv) inside the 'readnode' any fields placed inside the new div (testdiv) always come back as null when using $_get.
EDIT2:
Function that puts the readnode in place of the writenode,
<script type="text/javascript">
/* Set the counter that will increase every time
the user adds a new language*/
var counter = 0;
function addlanguage()
{
// Ask the user for input
var language = prompt("Language Name","");
if (language == "" || language == null)
{
alert("Please enter a language.");
}
else
{
counter++;
// Find the element to be copied
var newNode = document.getElementById('readnode').cloneNode(true);
newNode.id = '';
newNode.style.display = 'block';
var newField = newNode.childNodes;
// Give all fields a unique value
for (var i=0;i<newField.length;i++)
{
var theName = newField[i].name;
var theId = newField[i].id;
if (theName)
{
newField[i].name = theName + counter;
}
if (theId == "languagename")
{
// Change the field to the user input
newField[i].innerHTML = language;
}
if (theName == "lang")
{
// Replace the hidden field with the correct language
newField[i].value = language;
}
}
// Insert the elements
var insertHere = document.getElementById('writenode');
insertHere.parentNode.insertBefore(newNode,insertHere);
}
}
</script>
and this is the php;
<?php
if ($_GET["time1"] == null)
{ ?>
<form>
<span id="writenode"></span>
<input type="button" value="Add language" onClick="addlanguage()" >
<input type="submit" value="Submit" >
</form>
<?php
}
else
{
$final = 0;
$i = 1;
while($final == 0)
{
$gettime = "time" . $i;
$getRank = "rank" . $i;
$time = $_GET[$gettime];
$rank = $_GET[$getRank];
if ($language == "")
{
$final = 1;
}
if ($final == 0)
{
// Show the user the input
echo("<p>Your <strong>$time</strong> is <strong>$rank</strong>.</p>");
}
$i++;
}
} ?>
When you put it inside a div, it's no longer part of newNode.childNodes, so you never get to set the name properly. You'll have to check childs of childs or use jQuery to simplify things.
for (var i=0;i<newField.length;i++)
{
var subField = newField.childNodes;
for (var i=0;i<subField.length;i++) {
var theName = subField[i].name;
var theId = subField[i].id;
// ...
}
}

Categories