read all option in another page - php

I have a form which sends information with post method to another page. In the form I have a select box with three options, for example:
<select name="slctstate" id="slctstate">
<option value="0">aaaaa</option>
<option value="1">bbbbb</option>
<option value="2">ccccc</option>
</select>
In another page, I read the selected item with $_POST['slctstate'], but I want to read all options (key & value) in the select tag.
Can I do this?

First use a jquery function which stores all the options in a string
$(document).ready(function()
{
var myoption = '';
$('#drop_down option').each(function()
{
myoption = myoption + ',' + ($(this).val());
});
$('#hidden_text').val(myoption);
}
);
in the html use a hidden field
<input type="hidden" id="hidden_text" name="hidden_text"/>
WHen you will submit the form, catch this value with a list of options separated by (,);
On the action page, you can split the value using php explode() function
Check the fiddle
http://jsfiddle.net/1u9x5nbq/3/

No you can't without a work-around. The only value gets passed is the selected value. If you want to know all values you can use a work-around in javascript e.g.:
<select name="slctstate" id="slctstate">
<option value="0">aaaaa</option>
<option value="1">bbbbb</option>
<option value="2">ccccc</option>
</select>
//Include JQuery
<script>
$(function()
{
$('#slctstate option').each(function()
{
$('#slctstate').after('<input type="text" value="'+$(this).text()+'" name="slctstateOptions['+$(this).val()+']" style="display:none;" />');
//Where val() is the key and text() is the value.
});
});
</script>
Then you can access the values by using $_POST['slctstateOptions'].

No, you can't do that from the form. When you do submit, you send only selected value(s).

No,
The only value that is "selected" will be POSTed on Submit.

Related

send selected values of select box to PHP as string

I'm using Select2 3.4.5 for create select boxes,
I use this code for creatre a Multi-Value Select Boxe and everything is fine.
<select id="e1" name="mydata" multiple>
<option value="D1">Data1</option>
<option value="D2">Data2</option>
<option value="D3">Data3</option>
</select>
...
<script>
$("#e1").select2();
</script>
For get multiple selected values of select box in php I have to modify name="mydata" by name="mydata[]", and in PHP I get values by this code:
<?php
foreach ($_POST['mydata'] as $names) {
print "You are selected $names<br/>";
}
?>
But my question: How can I send selected values of select box to PHP as string to recover in php like this : 'D1,D2,D3' , and thanks.
Edit:
I want to send the data as string, not receive it as an array then
change it as string
Server-side with PHP
Ideally you would do this with PHP once the value is sent. To convert the selected items just want to implode the array
$names=implode(',', $_POST['mydata']);
Where $_POST['mydata'] is an array
[0]=>'D1',
[1]=>'D2',
[2]=>'D3'
implode(',', $_POST['mydata']) would be 'D1,D2,D3'
Client-side with jQuery
Your title says "send selected values of select box to PHP as string". You would do that in JS by catching the submit event of the form and using .join() to change the value of that field.
$('#formid').on('submit', function(){
$('#e1').val($('#e1').val().join(','));
});
Your form (not given) would need an id <form id="formid" ...>
If you want a client-side solution, try getting the val() and calling join():
$('#e1').val().join()
http://jsfiddle.net/gwgLV/
You can do it with javascript.
<select id="e1" name="mydata" multiple>
<option value="D1">Data1</option>
<option value="D2">Data2</option>
<option value="D3">Data3</option>
</select>
<button id="but" onclick="now()">Show selected values</button>
javascript code
function getSelectValues(select) {
var result = [];
var options = select && select.options;
var opt;
for (var i=0, iLen=options.length; i<iLen; i++) {
opt = options[i];
if (opt.selected) {
result.push(opt.value || opt.text);
}
}
return result;
}
function now(){
var el = document.getElementsByTagName('select')[0];
var x = getSelectValues(el);
alert(x);
}
Demo here
Instead of alert store in a variable and send it along with the rest of the form data. Or you can use join (as mentioned in other answers ) to send it over post to php.

Disable a submit button when one of the fields is empty

I am trying to disable a submit button when one or more of the selectors (generated dynamically) shown in the picture are empty..
I tried the following jQuery code:
<script>
var $submit = $("input[name=store_values]");
$(".ownlevelselect").each(function(){
if($(".ownlevelselect:empty").length>0){
$submit.attr("disabled","disabled");
}else {
$submit.removeAttr("disabled");
}
});
</script>
and these are the relevant parts of my form:
echo "<select class='ownlevelselect' id='ownlevelselect' name='level-".$compi['Competence_ID']."' >";
and the input buttons:
echo "<input type='submit' name='submit_values' value='Save'>";
echo "<input type='submit' name='store_values' value='Store'></form>";
The one I want to disable is the one with name='store_values'
There's something ambiguous in your question, do you mean empty like DOM empty (selects that contains no elements) or empty like selects with an empty value selected ?
If you mean empty like emtpy value, you can try this, handling change event like Shadow Wizard said:
$('document').ready(function(){
var submitButton = $('input[name="store_values"]');
/* Called to disable button on page load, done here but probably possible server-side */
checkValues()
/* Called on change event on dropdowns */
$('select.ownlevelselect').on('change',function(){
checkValues();
});
function checkValues(){
/* Disable button if found an empty <select> (mean, no <option> inside), or a select with an empty value selected */
submitButton.prop('disabled',$(".ownlevelselect > option:selected[value=''],.ownlevelselect:empty").length > 0);
}
});
If you mean empty like "Dom empty" (no option defined inside the select), you can try this (you can place it into a function and call it each time you dynamically add an element)
$('document').ready(function(){
var submitButton = $('input[name="store_values"]');
submitButton.prop('disabled',$(".ownlevelselect:empty").length > 0);
});
EDIT
Be carefull about your IDs, I don't have any relevant part of code to be sure, but you seem to reuse same ID for your selects, which is a bad idea :)
EDIT2
Here's a fiddle, so as you can see if I missed something:
http://jsfiddle.net/d8rb9/
you can use the event onBlur for each select to trigger a function that tests if all the other select are not empty, and then activate the submit button if so.
here is an exemple:
The select Tag :
<select class="ownLevelSelect" onBlur="checkSelects()">
<option></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>
</select>
The Javascript function:
<script>
function checkSelects(){
// integer to count the number of select with a correct value
var nonEmpty = 0;
// loop on all the select in the page with the class attribute : "ownLevelSelect"
$('.ownLevelSelect').each(function(){
if($(this).val()) {
nonEmpty++;
}
});
//desactivate the submit button if the number of selects in the page <> nonEmpty
($('.ownLevelSelect').length == nonEmpty)? $('#theSubmit').removeAttr("disabled") : $('#theSubmit').attr("disabled","disabled");
}
</script>
and maybe you need to call this function on page load so the button is disabled by default if one of the fields are empty
<script>
$(document).ready(function() {
checkSelects();
});
</script>
Note :
The ID attribut must be unique on the page, so in your code change this :
<select class='ownlevelselect' id='ownlevelselect' name='level-".$compi['Competence_ID']."' >";
By this :
<select class='ownlevelselect' id='ownlevelselect-".$compi['Competence_ID']."' name='level-".$compi['Competence_ID']."' >";
I hope this helped.

storing select box values into an array

i have two select boxes and a link.i select one value from the first select box and another from the second select box and click on the link.the values have to get stored in an array each time without the previous value getting replaced.how can i do this without using multiple select box?
<select name="sq" id="sq" >
<option value=""></option>
</select>
<select name="as" id="as" >
<option value=""></option>
</select>
sorry forgot to mention..its in codeigniter
You can use change event to store the selected values.
Html
<select name="sq" id="sq" >
<option value="1">1</option>
<option value="2">2</option>
</select>
Javascript
arrSelected = []
$("#sq").change(function(){
arrSelected.push($(this).val());
});
With the added info from the comments, here is my suggestion:
HTML:
<div class="selectLine">
<select name="sq[]" >
<option value=""></option>
</select>
<select name="as[]" >
<option value=""></option>
</select></div>
<a id="addOption">
JavaScript:
$('#addOption').click(function(){
$('.selectLine').last().after($('.selectLine').outerHtml());
$('.selectLine').last().prev().hide();
});
PHP receiving the post:
foreach($_POST['sq'] as $key=>$name){
//Make sure you stay consistent with the keys to make sure the 2 values were entered at the same time.
echo '<p>'.$name.' is a '.$_POST['as'][$key].'</p>';
}
Adding [] to the end of the name of inputs will place them in arrays. But you need more than one if you want more than one value...
You can remove $('.selectLine').last().prev().hide(); to keep the lines displayed to the user so he can change the values if you want.
This would send the data with AJAX without page refresh:
Use for the link Submit data
Then add the following jQuery script: (you need to include jQuery library first)
$('#submitlink').click(function(event) {
event.preventDefault(); // Stops default link behaviour on click
$.ajax({
url: "yourphp.php", // where to send
data: 'sq=' + $('#sq').val() + '&as=' + $('#as').val(), // select values
type: "POST",
success: function(data){
// If you want to confirm
alert('Added');
}
});
});
Then in your php script store the $_POST data in either a database or session...
Session example, storing:
<?php
session_start();
if (!isset($_SESSION['sq']) $_SESSION['sq'] = array();
$_SESSION['sq'][] = $_POST['sq'];
if (!isset($_SESSION['as']) $_SESSION['as'] = array();
$_SESSION['as'][] = $_POST['as'];
?>
To retrieve the results you could use:
<?php
session_start();
if (isset($_SESSION['sq']) print_r($_SESSION['sq']);
if (isset($_SESSION['as']) print_r($_SESSION['as']);
?>
But of course this could be elaborated.
If you wish to have persistence in your website, then I would recommend looking into PHP Cookies.
In your case, you want to store an array, persistently, so you have a few options.
Either implement a HTML Hidden Element or you can use Serialization to store the array inside a cookie.

load data from mysql with jquery and php

I have a drop down list (ddlAccount) which i can choose an item from it and do a db query in test.php to retrieve corresponding data, then output an input element with the returned data.
This is my javascript code:
function load1(){
$('#divAccountNum').load('test.php?accountInfo=' + document.getElementById('ddlAccount').value , '' ,function() {
alert('Load was performed.')});
}
load1 function called when i change the dropdown list items, and it takes the value of the selected option and sends it to test.php in a parameter called "accountInfo".
my html:
<select name="ddlAccount" id="ddlAccount" onchange="load1();">
<option value="1"> Account1</option>
<option value="2"> Account2</option>
<option value="3"> Account3</option>
</select>
<div id="divAccountNum" >
</div>
And test.php :
if($_GET['accountInfo'])
{
$account = $accountDAO->load($_GET['accountInfo']); //mysql query
//print an input holding account number as its value
echo "<input type='text' name='txtAccountNum' id='txtAccountNum' value='".$account->accountnumber."'/>";
}
The problem is that nothing happened when i choose an option (nothing appear in div (divAccountNum))
Any suggestions? Thanks in advance.
Edit:
I used #thecodeparadox 's bit of code and it works and i found a solution for the problem that i mentioned in the comments below which is that when choosing one item from the dropdown list it shows the value in input element and loads the form again. The solution is in:
jQuery Ajax returns the whole page
So my jquery code now looks like:
$(document).ready(function(){
$('#ddlAccount').on('change', function() {
$.get('testJquery.php?accountInfo=' + $(this).val(), function(accountNum) {
//console.log(accountNum);
$('input#txtAccountNum').val(accountNum);
});
});
And testJquery.php :
if($_GET['accountInfo'])
{
$account = $accountDAO->load($_GET['accountInfo']);
$accountNum = $account->accountnumber;
echo $accountNum;
}
And at last i added input element in divAccountNum which has id="txtAccountNum"
Though you don't give enough info about your problem, but you can try this:
function load1(){
$('#ddlAccount').on('change', function() {
$.get('test.php?accountInfo=' + $(this).val(), function(response) {
$('div#divAccountNum').html(response);
}, 'html');
});
}
NOTE:
$('#ddlAccount').on('change', fires when dropdown change
$.get('test.php?accountInfo=' + $(this).val().. send a get(ajax) request to test.php with value selected from drop down
parameter response with in $.get() second parameter callback function is the response from the server
'html' as third parameter of $.get() for data type you return, as you return a html so it is html.
for more info read:
change()
$.get()
To get selected option value from select input use:
$('#ddlAccount option:selected').val()

Changing contents of HTML select based on dropdown

I have a select item, that is filled with a list of files. This list of files is stored in a php variable.
I have another list of files, from another directory, stored in another variable.
I have a dropdown, with 2 options. When I change the dropdown, I want the items in the select to change to the file list associated with the item selected.
For example, my dropdown contains:
Misc Images
People
I have 2 variables, $misc and $people.
When Misc is selected, I want the select to contain all the images listed in $misc, and when the People option is selected I want the select to contain all the options listed in $people.
As far as looping through the php to generate all the items is fine, what I don't understand is how to do the javascript portion?
Thanks, and apologies for poor wording.
Try this code out.
PHP:
<?php
$miscArray = array("misc1", "misc2", "misc3");
$misc = implode(", ", $miscArray);
$peopleArray = array("people1", "people2", "people3");
$people = implode(", ", $peopleArray);
?>
HTML:
<form action="#">
<select id="fileCat">
<option id="misc">Misc</option>
<option id="miscData" style="display:none"><?php echo $misc ?></option>
<option id="people">People</option>
<option id="peopleData" style="display:none"><?php echo $people ?></option>
</select>
<select id="files"></select>
</form>
JS:
init();
function init()
{
addListeners();
}
function addListeners()
{
document.getElementById("fileCat").onchange = fillSelect;
}
function fillSelect()
{
var fileCat = document.getElementById("fileCat");
var imageFiles;
switch(fileCat.options[fileCat.selectedIndex].id)
{
case "misc":
imageFiles = document.getElementById("miscData").innerHTML.split(", ");
break;
case "people":
imageFiles = document.getElementById("peopleData").innerHTML.split(", ");
break;
}
var parent = document.getElementById("files");
parent.innerHTML = "";
if(imageFiles.length)
{
for(var i=0;i<imageFiles.length;i++)
{
var option = document.createElement("option");
//populate option with corresponding image text
option.innerHTML = imageFiles[i];
parent.appendChild(option);
}
}
}
I mocked up some data in PHP and then echoed it into a hidden <option> tag for each category. Then, the data is grabbed using a case/switch depending on the id of the selected option.
I think something like this would work. You would set the onchange attribute of your drop down box to call that function. You will need to have a URL that returns the options you want to use in JSON (selectMenus.php in that example). You'd need two different urls or one that takes a parameter to indicate which option set.
could You provide us some code? It is quite heavy to write it completely of nothing :)
UPDATE:
then how about You try the following (or similar) by using jQuery:
<select id="foo">
<option class="misc">MISC</option>
<option class="misc">MISC2</option>
<option class="people">People1</option>
</select>
<script type="text/javascript">
$(document).ready(function(){
$('option.misc').click(function(){
$('#foo').html('<option class="misc">MISC</option>
<option class="misc">MISC2</option>');
});
});
</script>
PHP is server side. JavaScript is client side. You have two options
(1) send an XmlHTTP request back to your server to pull the options and update the select list, or (2) send the values to a hidden field on the initial render of the page and get the values from there.

Categories