PHP get dropdown value and text - php

<select id="animal" name="animal">
<option value="0">--Select Animal--</option>
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Cow</option>
</select>
if($_POST['submit'])
{
$animal=$_POST['animal'];
}
I have a dropdown like this. What I want, I want to get selected value and text in button submit using PHP. I mean if it's selected 1st one. I want to get both 1 and Cat

Is there a reason you didn't just use this?
<select id="animal" name="animal">
<option value="0">--Select Animal--</option>
<option value="Cat">Cat</option>
<option value="Dog">Dog</option>
<option value="Cow">Cow</option>
</select>
if($_POST['submit'] && $_POST['submit'] != 0)
{
$animal=$_POST['animal'];
}

$animals = array('--Select Animal--', 'Cat', 'Dog', 'Cow');
$selected_key = $_POST['animal'];
$selected_val = $animals[$_POST['animal']];
Use your $animals list to generate your dropdown list; you now can get the key & the value of that key.

You will have to save the relationship on the server side. The value is the only part that is transmitted when the form is posted. You could do something nasty like...
<option value="2|Dog">Dog</option>
Then split the result apart if you really wanted to, but that is an ugly hack and a waste of bandwidth assuming the numbers are truly unique and have a one to one relationship with the text.
The best way would be to create an array, and loop over the array to create the HTML. Once the form is posted you can use the value to look up the text in that same array.

you can make it using js file and ajax call. while validating data using js file we can read the text of selected dropdown
$("#dropdownid").val(); for value
$("#dropdownid").text(); for selected value
catch these into two variables and take it as inputs to ajax call for a php file
$.ajax
({
url:"callingphpfile.php",//url of fetching php
method:"POST", //type
data:"val1="+value+"&val2="+selectedtext,
success:function(data) //return the data
{
}
and in php you can get it as
if (isset($_POST["val1"])) {
$val1= $_POST["val1"] ;
}
if (isset($_POST["val2"])) {
$selectedtext= $_POST["val1"];
}

Related

read all option in another page

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.

Get JSON specific value using jQuery

I have a json which is generated through php and i assigned it to a JS variable like below,
var jsonObj = {
"ATF":["FLV"],
"Limecase":["FLV"],
"RCF":["FLV","HTTP","PALM","MOBILE","3GP","H263","F263","WMV"],
"Wave":["FLV","IPHONE","MOBILE"]
}
And also i have a selectbox in html as below,
<select id="selectbox" data-rel="chosen">
<option value='ATF'>ATF</option>
<option value='Limespace'>Limespace</option>
<option value='RCF'>RCF</option>
<option value='Wave'>Wave</option>
</select>
On changing, i am getting the selected value and passing it as below,
alert(jsonObj.selVal); but alert throws "undefined"
But if i give direct value jsonObj.ATF, it gives FLV.
Please suggest me on this.
var selVal = 'ATF'; // or from an input
alert(jsonObj[selVal]);

Loading a PHP file and set variable based on selection

I need to load the content of a PHP file using jquery based on what is selected by the user in one or more select fields.
I can use...
$("#first-choice").change(function() {
$("#second-choice").load("getter.php?choice=" + $("#first-choice").val() );
});
...to create the variable 'choice' and when the 'first-choice' field is set by the user.
However, what if I want to use 2 variables based on two drop down selectors, to set the variable 'choice' (based on the selection of #first-choice) and choice2 (based on the selection of #second-choice).
So I would want to load a PHP file something like getter.php?choice=first-choice&choice2=second-choice
here's how i would handle this situation..
don't treat your selects as ids. use a single class for all select options, then bind .change() to all selects using a class-based selector. if you do this, you can iterate over X number of selects, use their ids as the query argument variable and their values as each query value. I created a quick demo for you on jsfiddle. I also posted the code for you below....
Here is my demo on jsfiddle
<div>
<select class="php-options" id='first-choice' name='first-choice'>
<option value='1-0'>choose</option>
<option value='1-1'>1-1</option>
<option value='1-2'>1-2</option>
<option value='1-3'>1-3</option>
<option value='1-4'>1-4</option>
<option value='1-5'>1-5</option>
</select>
</div>
<div>
<select class="php-options" id='second-choice' name='second-choice'>
<option value='2-0'>choose</option>
<option value='2-1'>2-1</option>
<option value='2-2'>2-2</option>
<option value='2-3'>2-3</option>
<option value='2-4'>2-4</option>
<option value='2-5'>2-5</option>
</select>
</div>
<div id="request-url"></div>
$(document).ready(function(){
//treat your select options with classes,
//bind change event on each select
$('.php-options').change(function(e){
var urlValues = [],
parameterArgs = "";
//loop selects to build parameters
$('.php-options').each(function(i,v){
var optValue = $(this).val(),
optId=$(this).attr('id'),
parameter = ""+optId+"="+optValue;
urlValues.push(parameter);
});
//build parameter string
parameterArgs =urlValues.join("&");
//output query
$('#request-url').text('getter.php?'+parameterArgs);
});
});

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.

Selected value using jQuery, PHP, MySQL

Does anybody know why I cannot specify the default value this way when it is pulling values from MySQL? I am ultimately trying to have it repopulate the dropdown lists with the appropriate $_REQUEST fields, so that editing can be easier.
$(document).ready(function(){
$("#region").load('getRecords.php?start=regions');
}); //jQuery initializations
...............
<select
class = "region"
name = "region"
onchange = "value = this.value;
$('.country').load('getRecords.php?region='+value)
">
<option>.....Reading database.....</option>
</select>
<script>$('.region').val('Africa');</script>
...............
This is the kind of info that gets placed
<option value = "">Select One Region-------</option>
<option value="Africa">Africa</option>
<option value="Americas">Americas</option>
<option value="Asia">Asia</option>
<option value="Australasia">Australasia</option>
<option value="Europe">Europe</option>
<option value = "">------or a Sub-Region------</option>
<option value="Alps">Alps</option>
<option value="Amazon">Amazon</option>
//ETC>>>>
I can only get the jQuery .val method to work for very simple setups.
Not quite sure what you are aiming for but maybe something like this will give you a nudge in the right direction (taken from the top of my head), probably has syntax errors.
$("select.region option[selected]").removeAttr("selected");
$("select.region option[value='Africa']").attr("selected", "selected");
try this:
document.getElementById("region").selectedIndex=0;//put index of the element which you want as default
and give id="region" in select tag
You need to have a valid <option value="Africa"> first before you can make that value become the default. <select> tags do not have arbitrary value attributes.
I recommend like below:
$('#region option[value="' + response_var[0].columnname + '"]').prop('selected', true);

Categories