Why im not getting all the values from the select element? - javascript

I ran into a little problem, when i submit the form through JS i would like to get all of the values from the select element... I mean like for every user the value of the select element.
<?php foreach($users as $user) : ?>
<div>
<p><?php echo $user['user_first'].' '.$user['user_last']; ?></p>
<form action="" method="post">
<select name="user-state">
<option value="Je na hodine">Je na hodine</option>
<option value="Chýba">Chýba</option>
<option value="Meškanie">Meškanie</option>
</select>
<input type="input" name="user" value="">
</form>
</div>
<?php endforeach; ?>
JS:
document.getElementById('saveBtn').addEventListener('click', function(){
document.getElementById('dochadzka-form').submit(); });

If you want all the data on a single submit you need to wrap all inputs inside a single form. To get the data as an array in PHP after submitting you should format the name attribute like name="user-state[]".
Something like this should do the trick (untested):
<form action="" method="post">
<?php foreach($users as $user) : ?>
<fieldset>
<legend><?php echo $user['user_first'].' '.$user['user_last'] ?></legend>
<input name="user[]" value="<?php echo $user['id'] ?>" type="hidden">
<select name="user-state[]">
<option value="Je na hodine">Je na hodine</option>
<option value="Chýba">Chýba</option>
<option value="Meškanie">Meškanie</option>
</select>
</fieldset>
<?php endforeach; ?>
<button type="submit">Submit</button>
</form>
An example to illustrate how this works:
// This is only needed to show the form data in this example.
// If you only need the data in PHP you don't need any JavaScript.
var form = document.getElementById("dochadzka-form");
form.addEventListener("submit", function(event) {
var data = new URLSearchParams(new FormData(form)).toString();
console.log(data);
event.preventDefault(event);
});
<form action="" method="post" id="dochadzka-form">
<fieldset>
<legend>User 1</legend>
<input name="user[]" value="1" type="hidden">
<select name="user-state[]">
<option value="Je na hodine">Je na hodine</option>
<option value="Chýba">Chýba</option>
<option value="Meškanie">Meškanie</option>
</select>
</fieldset>
<fieldset>
<legend>User 2</legend>
<input name="user[]" value="2" type="hidden">
<select name="user-state[]">
<option value="Je na hodine">Je na hodine</option>
<option value="Chýba">Chýba</option>
<option value="Meškanie">Meškanie</option>
</select>
</fieldset>
<br>
<button type="submit">Submit</button> to show the form data
</form>

<form action="" method="post">
<?php $i = 0; foreach($users as $user) : ?>
<div>
<p><?php echo $user['user_first'].' '.$user['user_last']; ?></p>
<select name="user-state<?= $i?>">
<option value="Je na hodine">Je na hodine</option>
<option value="Chýba">Chýba</option>
<option value="Meškanie">Meškanie</option>
</select>
<input type="input" name="user<?= $i?>" value="">
</div>
<?php $i++; endforeach; ?>
</form>

Related

How to get each value individually from a form using ajax and PHP?

I'm trying to get each value individually so that then i could send it to my html file but i can't figure out how to get the values individually. Right now i only get the values by using an array but im not sure how to get all values individually.
HTML below
<form id="form" method="post" action="array.php">
<div class="form-row">
<div class="form-group col-md-3">
<label for="date">My Birthday is</label>
<input type="date" name="Date" class="form-control" id="date" placeholder="MM/DD/YY">
</div>
<div class="form-group col-md-3">
<label for="name">My Name is</label>
<input type="text" class="form-control" name="name" id="name" placeholder="My Name">
</div>
<div class="form-group col-md-3">
<label for="favColor">My Favorite Color is</label>
<select name="favColor" class="form-control" id="favColor">
<option selected>Choose</option>
<option value="Red">Red</option>
<option value="Blue">Blue</option>
<option value="Green">Green</option>
<option value="Yellow">Yellow</option>
<option value="Orange">Orange</option>
<option value="Pink">Pink</option>
<option value="Black">Black</option>
</select>
</div>
<div class="form-group col-md-3">
<label for="sign">My Sign</label>
<select name="sign" class="form-control" id="sign">
<option selected>Choose</option>
<option value="Aries">Aries</option>
<option value="Taurus">Taurus</option>
<option value="Gemini">Gemini</option>
<option value="Cancer">Cancer</option>
<option value="Virgo">Virgo</option>
<option value="Libra">Libra</option>
<option value="Scorpio">Scorpio</option>
<option value="Sagittarius">Sagittarius</option>
<option value="Capricorn">Capricorn</option>
<option value="Aquarius">Aquarius</option>
<option value="Pisces">Pisces</option>
</select>
</div>
Ajax code below
$(document).ready(function(){
$('#form').on('submit', function (e){
e.preventDefault();
var formData = $(this).serialize();
$.ajax({
type: "POST",
url: 'array.php',
data: {formData: formData},
success: function(data){
//what to do here
//alert("data saved: "+ data);
$('#test').append(data);
}
})
});
});
PHP Below
$data = ' ';
foreach($_POST as $key => $value){
echo $data .= " $key = $value ;";
}
The form is posted to 'formData'.
$formData = $_POST['formData'];
$name = $formData['name'];
$favColor = $formData['favColor'];
I don't know exactly what you want to do. But, if you want to access the form data without accessing directly the array, you could use the function extract.
Using your code as an example, you can access the indexes as variables.
<?php
extract($_POST['formData']);
// both echos will show the same information
echo $_POST['formData']['date'];
echo $date;
// both echos will show the same information
echo $_POST['formData']['name'];
echo $name;
// both echos will show the same information
echo $_POST['formData']['favColor'];
echo $favColor;
//both echos will show the same information
echo $_POST['formData']['sign'];
echo $sign;
?>
In this example, both echos will show the same information as a result of extract function.
If you want more information about the extract function, please see php's documentation.

want to make these php function work inside this html echo [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
this is php document, when building this form i want to use that forech function to build the dropdown menu... as im inside the (HTML) it doesnt work... anyone has a clue how to make it work?
echo <<<HTML
<form method="post" class="form">
<label for="datafalta">Data da falta</label>
<input id="datafalta" type="date" value="{$dateToday}" name="datafalta"/>
<label for="alunofalta">Selecionar aluno</label>
<select name="aluno">
<option value="0" selected></option>
foreach ($calfaltas as $a) {
<option value="1">$a->nome</option>
}
</select><br /><br />
<input type="submit" name="enviar" value="Enviar">
</form>
HTML;
You cannot mix html and php as you are. For a start you are missing such simple parts like '' around strings.
<?php
echo '
<html>
<form method="post" class="form">
<label for="datafalta">Data da falta</label>
<input id="datafalta" type="date" value="' . $dateToday . '" name="datafalta"/>
<label for="alunofalta">Selecionar aluno</label>
<select name="aluno">
<option value="0" selected></option>';
foreach ($calfaltas as $a) {
echo '
<option value="1">' . $a->nome . '</option>';
}
echo '
</select><br /><br />
<input type="submit" name="enviar" value="Enviar">
</form>
<html>';
This should work:
<?php
echo"<form method='post' class='form'>
<label for='datafalta'>Data da falta</label>
<input id='datafalta' type='date' value='{$dateToday}' name='datafalta'/>
<label for='alunofalta'>Selecionar aluno</label>
<select name='aluno'>
<option value='0' selected></option>
";
foreach ($calfaltas as $a) {
echo " <option value='1'>$a->nome</option>";
}
echo"
</select><br /><br />
<input type='submit' name='enviar' value='Enviar'>
</form>";
?>
Instead of putting the foreach loop inside the heredoc output....create all the options in variable and output that variable in the middle of the string
$options='';
foreach ($calfaltas as $a) {
$options.='<option value="'.$a->someProperty.'">'.$a->nome.'</option>';
}
echo <<<HTML
<form method="post" class="form">
<label for="datafalta">Data da falta</label>
<input id="datafalta" type="date" value="{$dateToday}" name="datafalta"/>
<label for="alunofalta">Selecionar aluno</label>
<select name="aluno">
<option value="0" selected></option>
$options
</select><br /><br />
<input type="submit" name="enviar" value="Enviar">
</form>
HTML;
note you need to fix value of the <option> tag to reflect proper data in array
Break your heredoc in two parts with the foreach in the middle :
<?php
echo <<<HTML
<form method="post" class="form">
<label for="datafalta">Data da falta</label>
<input id="datafalta" type="date" value="{$dateToday}" name="datafalta"/>
<label for="alunofalta">Selecionar aluno</label>
<select name="aluno">
<option value="0" selected></option>
HTML;
foreach ($calfaltas as $a) {
echo "<option value='{$a->id}'>{$a->nome}</option>";
}
echo <<<HTML
</select><br /><br />
<input type="submit" name="enviar" value="Enviar">
</form>
HTML;
?>

Enable button when select option in PHP using Javascript

I tried some code from other topics to resolve my problem here but I still don't manage to get what I want..
I need a button to goes enable when the user select one of the item in a select option and goes to disable when the users re-select the default select..
<script text="text/javascript">
$(document).ready(function(){
$('#select_resa').change(function(){
var val = $('#select_resa').val();
alert(val);
if (val == '') {
$('#supprimer_resa_button').attr('disabled', 'disabled');
}else{
$('#supprimer_resa_button').removeAttr('disabled');
}
});
});
</script>
<form method="post" action="modif_resa.php?" id="modif_resa">
<h2>Modifier/Supprimer un reservation</h2>
<?php if(isset($erreur)) echo '<p style="font-style:italic;font-size:0.8em;text-align:center;color:red;margin-bottom:5px;">'.$erreur.'</p>'; ?>
<label for="salle"><strong>Choisissez une reservation</strong></label>
<select id="select_resa" name="select_resa">
<option value="" id="select" name="select">--Selectionnez--</option>
<option value=""></option>
<option value="2">salut</option>
<?php
if(!empty($liste_reservations)){
for($i=0;$i<count($liste_reservations);$i++){
echo '<option "title="'.$liste_reservations[$i]['RS_NOM'].'" value="'.$liste_reservations[$i]['RS_NOM'].'" '.(isset($SALLE) && $SALLE==$liste_reservations[$i]['RS_ID']?'selected="selected"':'').'>'.$liste_reservations[$i]['RS_NOM'].'</option>';
}
}
?>
</select>
<br/><br/>
<label for="s_date"> Modifier la date de fin</label>
<input type="text" value="<?php if(isset($RS_DATE)) echo $RS_DATE;?>" name="s_date" id="s_date" maxlength="10" size="10"/>
<img src="/Libs/calendar/calendar_small.png" alt="Calendrier" style="vertical-align:middle; border:0;" title="Calendrier" />
<br/><br/>
<span class="valider">
<input type="submit" name="valider" value="<?php echo TXT_VALIDER; ?>" />
</span>
<br/><br/>
<div style="text-align:center; margin-top: 50px;">
<input id="supprimer_resa_button" disabled="disabled" type="submit" name="supprimer_resa_button" style="font-size: 15px; width: auto; height:auto; font-weight:bold;" value="<?php echo TXT_SUPPRIMER_RESA; ?>" />
</div>
</form>
My Submit button is enable in any case here...
Where am I wrong ?
Please check this:
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script text="text/javascript">
$(document).ready(function(){
$('#select_resa').change(function(){
var val = $('#select_resa').val();
if (val == '') {
$('#supprimer_resa_button').attr('disabled', 'disabled');
}else{
$('#supprimer_resa_button').removeAttr('disabled');
}
});
});
</script>
<form method="post" action="modif_resa.php?" id="modif_resa">
<h2>Modifier/Supprimer un reservation</h2>
<?php if(isset($erreur)) echo '<p style="font-style:italic;font-size:0.8em;text-align:center;color:red;margin-bottom:5px;">'.$erreur.'</p>'; ?>
<label for="salle"><strong>Choisissez une reservation</strong></label>
<select id="select_resa" name="select_resa">
<option value="" id="select" name="select">--Selectionnez--</option>
<option value="1">abc</option>
<option value="2">def</option>
<option value="3">ghi</option>
<?php
if(!empty($liste_reservations)){
for($i=0;$i<count($liste_reservations);$i++){
echo '<option "title="'.$liste_reservations[$i]['RS_NOM'].'" value="'.$liste_reservations[$i]['RS_ID'].'" '.(isset($SALLE) && $SALLE==$liste_reservations[$i]['RS_ID']?'selected="selected"':'').'>'.$liste_reservations[$i]['RS_NOM'].'</option>';
}
}
?>
</select>
<br/><br/>
<label for="s_date"> Modifier la date de fin</label>
<input type="text" value="<?php if(isset($RS_DATE)) echo $RS_DATE;?>" name="s_date" id="s_date" maxlength="10" size="10"/>
<img src="/Libs/calendar/calendar_small.png" alt="Calendrier" style="vertical-align:middle; border:0;" title="Calendrier" />
<br/><br/>
<span class="valider">
<input type="submit" name="valider" value="<?php echo TXT_VALIDER; ?>" />
</span>
<br/><br/>
<div style="text-align:center; margin-top: 50px;">
<input id="supprimer_resa_button" disabled="disabled" type="submit" name="supprimer_resa_button" style="font-size: 15px; width: auto; height:auto; font-weight:bold;" value="<?php echo TXT_SUPPRIMER_RESA; ?>" />
</div>
</form>
You just need to use:
$('#supprimer_resa_button').removeAttr('disabled');
instead of
$('#supprimer_resa_button').attr('disabled', '');
In recent jQuery api, you must use prop on boolean html attributes :
$('#supprimer_resa_button').prop('disabled', false)
Or
$('#supprimer_resa_button').prop('disabled', true)
attr is only with html attributes which can contain a value.
In your case, you can also do a little shorter :
function updateFormEnabled() {
$('#supprimer_resa_button').prop('disabled', verifyAdSettings());
}

passing data through text box from select option into another page

I am trying to pass data through a text box which is selected through the 'other' in select option. However, when I run the program, the data is not passed. Any ideas how to resolve this? here is the code that I am using. I have added most of the code below. I have to pass information through the select option in the form of a text box. However the information is not passed. Is there any other method that can do this, passing through text to another page?
<?php include_once("header.php"); ?>
<?php
$q_sel = "select * from tbl_drug";
$r_sel = mysql_query($q_sel);
?>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$( document ).ready(function() {
$('#my_textarea').hide();
$('#Quantity').change(function()
{
var o = $(this).find('option:selected').val();
console.log(o);
if(o=='other') $('#my_textarea').show(); else $('#my_textarea').hide();
});
});
</script>
</head>
<body style="background-color: #25383c;background-image: url(img/background.png);">
<?php include_once("nav.php"); ?>
<h1> Medication Appropriateness Index</h1>
<div class="container-fluid">
<div class="row">
<div class="col-sm-12">
<div class="well">
<form class="form-horizontal" role="form" action="save_drug.php" method="post">
<div class="form-group">
<label class="control-label col-sm-2">Drug:</label>
<div class="col-xs-3">
<select name="drug" id="Drug" class="form-control" required="">
<option value="" selected="" disabled="">Please select A drug...</option>
<?php
while($r1 = mysql_fetch_array($r_sel))
{ ?>
<option value="<?php echo $r1['d_id']; ?>"><?php echo $r1['drug_name']; ?></option>
<?php
}
?>
</select>
</div>
</div>
<script>
$(function() {
$("#dose").tooltip();
});
</script>
<div class="form-group">
<label class="control-label col-sm-2">Route:</label>
<div class="col-xs-3">
<select id="Quantity" name="quantity" class="form-control" required="">
<option value="" selected="" disabled="">Please select A dosage...</option>
<option value="PO">PO</option>
<option value="IV">IV</option>
<option value="PR">PR</option>
<option value="Topically">Topically</option>
<option value="other">Other (please specify)</option>
</select>
<textarea name="my_textarea" id="my_textarea"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="hidden" name="patient_id" value="<?php echo $_GET['patient_id']; ?>">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
always use 'name' attribute for inputs , because only name can send data on submit.
<textarea name="my_textarea" id="my_textarea"></textarea>

how to keep $_POST after submitting form with onchange event?

I have a list view and grid view which are submit buttons and I have sort selection if I click on one of the select options the form will be submitted but I want to keep $_POST value whether the list had been clicked or Grid because when I submit the form the data will be gone
I want something like:
Name had been clicked and list had been clicked before that
live example: (I changed it but concept is the same)
I cannot remove onchange submit of select drop down and simply first choose the drop down selection and then submit the buttons because I need it to be like that for when going to the option load the form with new information
The reason why I am submitting on onchange is that I need it because I sort my items with this submit
my question is how can I have them both? do I need two forms? do I need to use jQuery?
or php will do the work?
I kept value of option after submit by javascript but I don't know how to maintain the value of $_POST that which one had been clicked
how can I keep $_POST value when it has been set and submit the form on onchange of sort?
<form method="post" action="">
<div id="gridSort">
<span>View Results As:</span> <span>
<input type="submit" class="listButtons" name="view" value="List"> </span> <span>
<input type="submit" class="resultButtons" name="view" value="Grid"></span>
<select id="sortSelect" class="sortSelect" size="1" name="sort" onchange="this.form.submit();">
<option selected>Sort</option>
<option value="Name">Name</option>
<option value="PriceLowToHigh">Price - Low</option>
<option value="PriceHighToLow">Price - High</option>
</select>
</div>
</form>
<script type="text/javascript">
document.getElementById('sortSelect').value ="<?php if(! $_POST['sort']):?>"Sort"<?php else: echo $_POST['sort']; endif;?>";
</script>
<?php
if(isset($_POST["view"])):
if($_POST["view"]=="Grid")
{
echo "Grid clicked";
echo "<br/>";
}
if($_POST["view"]=="List" )
{
echo "List clicked";
echo "<br/>";
}
endif;
?>
Simply add a hidden field to your form:
<form method="post" action="">
<input name="selected_sort" value="<?php echo !empty($_POST['sort']) ? strip_tags($_POST['sort']) : ''; ?>" />
<input name="selected_view" value="<?php echo !empty($_POST['view']) ? strip_tags($_POST['view']) : ''; ?>" />
<div id="gridSort">
<span>View Results As:</span> <span>
<input type="submit" class="listButtons" name="view" value="List"> </span> <span>
<input type="submit" class="resultButtons" name="view" value="Grid"></span>
<select id="sortSelect" class="sortSelect" size="1" name="sort" onchange="this.form.submit();">
<option selected>Sort</option>
<option value="Name">Name</option>
<option value="PriceLowToHigh">Price - Low</option>
<option value="PriceHighToLow">Price - High</option>
</select>
</div>
</form>
This will allow the data to be sent across in all subsequent form submits
<form method="GET" action="">
<body >
<div id="gridSort">
<span>View Results As:</span> <span>
<input type="submit" class="listButtons" name="view" value="List"> </span> <span>
<input type="submit" class="resultButtons" name="view" value="Grid"></span>
<select id="sortSelect" class="sortSelect" size="1" name="sort" onchange="this.form.submit();">
<option selected>Sort</option>
<option value="Name">Name</option>
<option value="PriceLowToHigh">Price - Low</option>
<option value="PriceHighToLow">Price - High</option>
</select>
</div> </body>
</form>
<script type="text/javascript">
document.getElementById('sortSelect').value ="<?php if(isset( $_GET['sort'])){ echo $_GET['sort']; } ?>";
</script>
<?php
if(isset($_GET["view"])){
if($_GET["view"]=="Grid")
{
echo "Grid clicked";
echo "<br/>";
}
if($_GET["view"]=="List" )
{
echo "List clicked";
echo "<br/>";
}
}
?>
I TRIED TO REWRITE YOUR CODE WORKS FINE, but you need to replace post method with get, this will help user on reference and page refresh as many as he want.
Here is what I did for someone who will become frustrated like me:
<form method="post" action="" id="myform">
<div id="gridSort">
<input type="hidden" name="selected_sort" value="<?php echo !empty($_POST['sort']) ? strip_tags($_POST['sort']) : ''; ?>" />
<input type="hidden" name="selectionList_view" value="<?php echo !empty($_POST['Listview']) ? strip_tags($_POST['Listview']) : ''; ?>" />
<input type="hidden" name="selectionGrid_view" value="<?php echo !empty($_POST['Gridview']) ? strip_tags($_POST['Gridview']) : ''; ?>" />
<span>View Results As:</span> <span>
<input type="submit" class="listButtons" name="Lisview" value="List"> </span> <span>
<input type="submit" class="resultButtons" name="Gridview" value="Grid"></span>
<select id="sortSelect" class="sortSelect" size="1" name="sort" onchange="this.form.submit();" >
<option selected>Sort</option>
<option value="Name">Name</option>
<option value="PriceLowToHigh">Price - Low</option>
<option value="PriceHighToLow">Price - High</option>
</select>
</div>
</form>
<script type="text/javascript">
document.getElementById('sortSelect').value ="<?php if(! $_POST['sort']):?>"Sort"<?php else: echo $_POST['sort']; endif;?>";
</script>
<pre>
<?php print_r($_POST); ?>
</pre>

Categories