I have a select multiple list that has a few items in it. It is a list of IP addresses for an ACL. People can add/remove IPs, and then save the list. However, unless you select an item on the list, $_POST[selectName] does not contain any values. How can I accomplish this? I know I can do this with javascript but I would rather stick to PHP.
Edit/corrected: You need JS. There is no way to send all (selected and not selected) options via POST. You have to programatically select all options before submission.
File with form (file1.php):
<script type="text/javascript">
function selectAll()
{
selectBox = document.getElementById("someId");
for (var i = 0; i < selectBox.options.length; i++)
{
selectBox.options[i].selected = true;
}
}
</script>
<form method="post" action="file2.php">
<select id="someId" name="selectName[]" multiple>
<option value="123.123.123.123">123.123.123.123</option>
<option value="234.234.234.234">234.234.234.234</option>
</select>
<input type="submit" name="submit" value=Submit onclick="selectAll();">
</form>
File that receives POST (file2.php):
<?php
foreach ($_POST['selectName'] as $item)
{
print "$item<br/>";
}
?>
Just to tack on this you could also use the jQuery version of #Kamil's code which is a little simpler than the loop:
<script type="text/javascript">
jQuery('[name="form1"]').on("submit",selectAll);
function selectAll()
{
jQuery('[name="selectName[]"] option').prop('selected', true);
}
</script>
<form name="form1" method="post" action="file2.php">
<select id="someId" name="selectName[]" multiple>
<option value="123.123.123.123">123.123.123.123</option>
<option value="234.234.234.234">234.234.234.234</option>
</select>
<input type="submit" name="submit" value=Submit onclick="selectAll();">
</form>
Related
I have a select list, but on page reload , the data in the list is not saved of corse.
I have fixed this with TextBoxes and Radio buttons by reading the variables from $_GET.
Here is an example of the form I have now:
<form action="" id="exampleForm" method="get">
<input type="checkbox" name="exampleCheckbox" <?php if (isset($_GET['exampleCheckboxStatus'])) {echo "checked";} ?>>Check this
</br>
<select name="exampleList" multiple>
<option>Apple</option>
<option>Banana</option>
<option>Cherry</option>
</select>
<input type="submit" value="Submit" id="submitButton"> </form>
I would like to keep the values of the 'exampleList' once submitted
(I stay on the same page)
I have seen posts on here that almost look like what I ask, but most of them want to use javascript. Is there an solution for my problem, wich look similiar to what I already have right now? I would like to fix this with php because I dont think I have enough knowledge of Javascript (yet)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
var opts = localStorage.getItem('opts'); // get selected items from localStorage key
opts = opts.split(','); // split result from localstorage to array
$('#exampleList').val(opts); // select options with array
});
</script>
<html>
<body>
<select id="exampleList" multiple>
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="cherry">Cherry</option>
</select>
</body>
</html>
When you POST the form you only need to write the selected option values, comma separated, to the localstorage.
I finally found a solution:
The only flaw is the order of the :)
But since I use a plugin for displaying it does not matter much.
The fix:
I created 2 Array lists
list1 with everying in it
list2 with all selected values
Then I subtract list2 from list1 and dont have duplicates
So I can print both in different print methods.
<?php error_reporting(E_WARNING);
$fruitArray = array("Apple", "Banana", "Cherry", "Durian", "Eggfruit", "Fig", "Grapefruit");
$selectedFruitArray = $_GET['exampleList'];
$fruitArray = array_diff($fruitArray, $selectedFruitArray);
?>
<form action="" method="get">
<select name="exampleList[]" multiple>
<?php
foreach($fruitArray as $value) {
echo "<option value='$value'>$value</option>";
}
foreach($selectedFruitArray as $value) {
echo "<option value='$value' selected>$value</option>";
}
?>
</select>
<input type="submit">
</form>
Use FormRepo, a plugin specially made for retaining form data
on page refreshes.
Its usage is also simple:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="FormRepo.js"></script>
<script>
var $form = $('#input')
, $output = $('#output')
, repo = new FormRepo('restclient')
;
// get the last submitted values back
repo.restore($form/*, $form.attr('id')*/ ); // don't necessarily need an identifier
$form.submit(function (e) {
// preserve the last submitted values
repo.preserve($form/*, $form.attr('id')*/ ); // don't necessarily need an identifier
});
console.log( repo.all() );
</script>
You can do it by using session. This is the way using it you can store last selected value in session. Session value will not be destroyed even if you reload paga.
For e.g.,
<?php
session_start(); // Other Code
<div>
<p>Subtitle needs to be
<input type="radio" name="subTitleRadio" <?php if ($_SESSION['subTitleRadio'] != "LIKE") echo "checked"; ?> value="LIKE">contain
<input type="radio" name="subTitleRadio" <?php if ($_SESSION['subTitleRadio'] == "=") echo "checked"; ?> value="=">be equal to
</p>
<input type="search" name="subTitleSearchBox" placeholder="filter for subtitle" class="chosenStyle" value="<?php echo $_GET['subTitleSearchBox'];?>">
</div> //Other Code
?>
PHP Code for set value in session after submit :
<?php
session_start(); //Not required if your form action is on same page, else required //Rest code
$_SESSION['subTitleRadio'] = $_GET['subTitleRadio'] // OR $_POST['subTitleRadio']; // Rest code
?>
Same code works for me.
first of all at value parameters to the options, then you can check if exampleList has the right value and use that. for example:
<option value="apple" <?php if (isset($_GET['exampleList']) && $_GET['exampleList'] == "apple") echo "selected=\"selected\""; ?>>Apple</option>
Well, you could try something along these lines. It's a bit lengthy, you could shorten it up quite a bit. By showing it this way, I hope it's simpler to understand.
<form action="" id="exampleForm" method="get">
<?php
if (isset($_GET['exampleCheckboxStatus'])) {
echo '<input type="checkbox" name="exampleCheckbox" checked> Check this';
} else {
echo '<input type="checkbox" name="exampleCheckbox"> Check this';
?>
<br />
<select name="exampleList[]" multiple>
<?php
if( in_array('apple', $_GET['exampleList']) ) {
echo '<option value="apple" selected>Apple</option>';
} else {
echo '<option value="apple">Apple</option>';
}
if( in_array('banana', $_GET['exampleList']) ) {
echo '<option value="banana" selected>Banana</option>';
} else {
echo '<option value="banana">Banana</option>';
}
if( in_array('cherry', $_GET['exampleList']) ) {
echo '<option value="cherry" selected>Cherry</option>';
} else {
echo '<option value="cherry">Cherry</option>';
}
?>
</select>
<input type="submit" value="Submit" id="submitButton">
</form>
Note that I added [] to the select's name and corrected the br tag.
Adding [] will change the type from "string" (text) to an array (several texts). Then we can check what texts are included.
Try it for yourself, play around with the code a bit.
I am attempting to build a simple contact form inside of a function so that I may add it as a shortcode later. I wish to change the mailto address based on a "select" value.
function contact_form_function() {
switch($_POST['selectedValue']){
case 'webmaster':
$mailbox='webmaster#email.com';
break;
case 'careers':
$mailbox='careersk#email.com';
break;
case 'projects':
$mailbox='projects#email.com';
break;
case 'info':
$mailbox='info#hotmail.com';
break;
default:
// Something went wrong or form has been tampered.
}
?>
<form action="MAILTO:<?php echo($mailbox); ?>" method="post" enctype="text/plain">
<input type="text" name="name" required> Name(required)
<input type="text" name="mail" required> Mail(will not be published, required)
<input type="text" name="website"> Website
<select name="selectedValue">
<option value="webmaster">Website Comment</option>
<option value="careers">Careers Information</option>
<option value="projects">Project Opportunity</option>
<option value="info">Other</option>
</select>
<textarea></textarea>
<?php
echo($mailbox);
?>
<input type="submit"></submit>
</form>
<?php
}
?>
Its not echoing anything back and not changing the email address so I know I've done something wrong. I just don't know what. I'm a novice when it comes to coding so any advice is helpful.
You need to set the $mailbox value before you try to use it. I recommend using jQuery.
<script src="jquery.js"></script>
<script type="text/javascript">
jQuery.noConflict();
(function ($) {
function readyFn() {
$("#emailSelect").change(function(){
$("#your_form").attr('action', 'MAILTO:' + $("#emailSelect").val() + '#email.com');
});
}
$(document).ready(readyFn);
})(jQuery);
/*$(document).ready(function(){
$("#emailSelect").change(function(){
$("#your_form").attr('action', 'MAILTO:' + $("#emailSelect").val() + '#email.com');
});
});*/
</script>
...
<form action="" id="yoor_form" method="post" enctype="text/plain">
...
<select name="selectedValue" id="emailSelect">
<option value="webmaster">Website Comment</option>
<option value="careersk">Careers Information</option>
<option value="projects">Project Opportunity</option>
<option value="info">Other</option>
</select>
</form>
You need to set the $mailbox value before you try to use it.
And if you want something to happen in the browser when the user selects an option in the drop down, you have to use javascript, not PHP.
You are defining $mailbox after you try to use the value.
You have to have your $mailbox = ... stuff before your <form>.
Got a simple form made of a text input and a option select input. When submititing, Firebug shows me that on POST no value from the option input has been sent, only the value from the text one. After checking other similar questions, don't find any spelling mistake...
FORM:
<form id="turn_conf" method="POST" action="config/forms/turn_conf/turn_insert.php">
<div class="smartFormContent">
<p class="inputForm">
<label for="nombre">Nombre:</label>
<input id="tu_name" class="" type="text" value="" name="tu_name">
</p>
<p class="inputForm">
<label for="tipo">Tipo turno:</label>
<select id="tu_type" class="" name="tu_type">
<option value="1">MaƱana</option>
<option value="2">Tarde</option>
<option value="3">Noche</option>
</select>
</p>
<input class="smartFormSubmit" type="submit" value="Crear" name="submit">
</div>
</form>
Firebug shows posted data as:
FIY: this POST form is sent by jQuery, here is the code:
function validaDatos(e)
{
var turnName = $('input[name=tu_name]').val();
var turnType = $('input[name=tu_type]').val();
$.post($(this).attr('action'), { tu_name:turnName, tu_type:turnType }).success(feedback);
var emptyRow='<div class="tableRow newRow"><div class="contentColumn60"><span class="tableContentText"></span></div><div class="contentColumn20"><span class="tableContentText"></span></div><div class="contentColumn10"><div class="tableIconLink"></div></div><div class="contentColumn10"><div class="tableIconLink"></div></div></div>';
$(emptyRow).prependTo('.tableContent').hide().slideDown(500);
messageInsert();
e.preventDefault();
}
function feedback (datos) {
var content= datos;
$('.newRow').html(datos);
}
There are duplicate FORM tags:
<form method="POST" action="config/forms/turn_conf/turn_insert.php" id="turn_conf">
<form id="turn_conf" method="POST" action="config/forms/turn_conf/turn_insert.php">
This will probably cause the browser not to post the data properly.
The two FORM tags also share the same ID which is not permitted id="turn_conf".
var turnType = $('input[name=tu_type]').val()
tu_type is not an input, is a select. This will work:
var turnType = $('select[name=tu_type]').val()
hy, i have a problem with a form. i know the question is simple but i can not have a solution. Well, this is my form:
<form id="search" method="post" action="cerca_redirect2.php" >
<select id="tipo" name="tipo"class="chzn-select" style="width:165px;" tabindex="1" >
<option value="http://case.vortigo.it/vendita-immobili/index.php"> Vendita</option>
<option value="http://case.vortigo.it/affitto-immobili/index.php">Affitto</option>
</select>
<input id="field" name="field" type="text" value=""/>
<input id="submit" type="submit" value="" />
</form>
my goal is when i select "Vendita" and i submit the form i have to go to the url in the select "Vendita", for each select. someone can help me? thanks
In the server side php code, do something like this
if (isset($_POST['tipo']) && !empty($_POST['tipo']))
{
header('Location: ' . $_POST['tipo']);
}
Note: This is a very basic version, you will want to ensure the url is valid by either maintaining a list of urls on the server, or something similar.
There are many different ways, but you can for example use following:
See the onsubmit part in the form definition
<form id="search" method="post" action="cerca_redirect2.php" onsubmit="this.action=document.getElementById('tipo')[document.getElementById('tipo').selectedIndex].value" >
If I understan your question correctly, you need a way to change the action value to the selected option's value
this is how to do that
$(document).ready(function(){
$("#tipo").on("change", function(){
$("#search").attr("action", $(this).val());
});
});
DEMO: http://jsfiddle.net/6ybMP/
You want to change the action of the form based on the select? The following should be along the lines of what you want.
$('#tipo').on('change', function() {
var newAction = this.val();
$('#search').prop('action', newAction);
}
UPDATE
You will want to wrap this code in $(document).ready() so that the event will be registered after the DOM has been loaded.
Like so:
$(document).ready(function() {
$('#tipo').on('change', function() {
var newAction = this.val();
$('#search').prop('action', newAction);
}
});
I have got a form (php in html or the other way around). Once user selects an option in a drop down list, it would get the input value and create a few text boxes. It seems like I have to use onchange(). How do I read the input and perform logics within the script inself? Instead of opening another .php script?
Currently this is what I have.
<?php
$tables = $_POST["tables"];
?>
<html>
<body>
<form method="post" action="<?php echo $PHP_SELF;?>">
Table Name: <div id="tables">
<select name="tables">
<option value="Applications">Application</option>
<option value="Device">Device</option>
</select>
</div>
</form>
<?
echo "".$tables."";
?>
You can't interact with PHP once the HTML is sent to the browser without either
Refreshing the page, or
Using AJAX (JavaScript).
If you know the options in the <select> beforehand (which it seems like you do), you should write some JavaScript to accomplish what you need. Here is a simple example using jQuery.
$('#tables_select').change(
function( eventObject ){
alert('You chose ' + $(this).val());
switch( $( this ).val())
{
case 'Applications':
$('#tables').append('<input type="text" name="application_name" value="Enter an application name" />"');
break;
case 'Device':
$('#tables').append('<input type="text" name="device_name" value="Enter a device name" />"');
break;
}
}
);
You will need to add additional logic to remove the inserted elements if the user changes their choice, and to insert the correct <input> elements when the page first loads, but it is a good starting point.
if you want to add any input type ... here is the demo demo with code
you use following method.
<form method="post" action="<?php echo $PHP_SELF;?>" onChange="return createTxtbox()">
Table Name: <div id="tables">
<select name="tables">
<option value="Applications">Application</option>
<option value="Device">Device</option>
</select>
</div>
<span id="fooBar"> </span>
</form>
then write javascript,
<SCRIPT language="javascript">
function createTxtbox() {
var type="text";
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", type);
element.setAttribute("value", type);
element.setAttribute("name", type);
var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(element);
}
</SCRIPT>