How to read a value from a select box with php? - php

im using the cms contao and i got an overview page of some projects with 3 filters, one of them looks like this:
<select name="catitem_region_de" id="ctrl_filter_field_catitem_region_de" class="select" onchange="window.location=this.options[this.selectedIndex].value">
<option value="../cartitem_country/Deutschland" selected="selected">– Region –</option>
<option value="../cartitem_partner_country/Deutschland/catitem_region_de/Europa">Europa</option>
<option value="../cartitem_partner_country/Deutschland/catitem_region_de/Amerika">Amerika</option>
</select>
As you can see, when u select an option, the page refreshes with the selected filter.
My problem is, i want on every visit / refresh of the page, that a php script reads the value of the selected="selected" option. So that it looks like this:
If the option is "-Regio-", display content for region and if the content is anything else, display another content.
How can i do this with php?
thx

If I were you, I would split your page in smaller pieces.
First part - Array of your links in JavaScript :
var links = { 0 : '',
1 : '../cartitem_partner_country/Deutschland/catitem_region_de/Europa',
2 : '../cartitem_partner_country/Deutschland/catitem_region_de/Amerika' };
Second Part - Drop Down box:
<select name="catitem_region_de" id="ctrl_filter_field_catitem_region_de" class="select" onchange="changeDDB()">
<option value="0" selected="selected">– Region –</option>
<option value="1">Europa</option>
<option value="2">Amerika</option>
</select>
Third Part - On Change JavaScript :
function changeDDB() {
var idx = document.getElementById("ctrl_filter_field_catitem_region_de").selectedIndex;
if(idx != 0) {
window.location = links[idx];
}
}

Related

HTML Dropdown menu with autosuggestion and auto updation

I am trying to develop a webpage based on html, css. I am using PHP for server side scripting.
I want a dropdown menu to be displayed with available options, But at the same time I need this drop down list to accept text. so I can choose from dropdown list as well from the text box whatever I want.
I found one solution for the above scenario and working fine, but what extra I want that, once I write something in the text box, which is not an options of the dropdown, from the next time it will auto include it.
e.g. ->
currently my dropdown is having say three options "Samsung", "Sony", "Apple"
<option value="one">Samsung</option>
<option value="two">Sony</option>
<option value="three">Apple</option>
Now, "Lenevo" is not available. For the First time in the text box I will write "Lenevo" as my choice, there after it will include it into the dropdown menu.
<option value="one">Samsung</option>
<option value="two">Sony</option>
<option value="three">Apple</option>
<option value="four">Lenevo</option>
.
.
Like that it will happen.
Thanks for help.. :)
The best solution would be something like select2. (JavaScript)
For examples look here: Link
If you want to stay with PHP only, you need to offer a from to submit text values:
(Disclaimer: This solution is quite bad practice. But it's an example on how to solve it, on a low level.)
1) offer a form
<input type="text" name="addSelection">
2) Read post request
$newOption = $_POST["addSelection"];
3) Persist new option somewhere (here Session, also possible are databases)
$_SESSION["additionalOptions"][] = $newOption;
4) Merge with standard options
$options = ["apple","banana"];
$options = array_merge($options,$_SESSION["additionalOptions"]);
5) Create Options in HTML
<select name="fruits">
<?php
foreach($options as $option){
echo '<option value="'+$option+'">'+$option+'</option>';
}
?>
</select>
Use select2 plugin
https://github.com/select2/select2
<script type="text/javascript" src="/assets/profile/js/select2.min.fda43621.js"></script>
var validateTag = function (term, data) {
var value = term.term;
var re = /^[a-z\d\-_\s]+$/i;
if (re.test(value))) {
return {
id: value,
text: value
};
}
return 'wrong_characters';
};
$("#selectAlt").select2({tags: true, maximumSelectionLength: 6, maximumInputLength: 20, createTag: validateTag});
HTML:
<select name="selectAlt[]" id="selectAlt" multiple="multiple" custom-placeholder="Genre">
<option value="Blues">Blues</option>
<option value="Classic Rock">Classic Rock</option>
<option value="Country">Country</option>
</select>

Setting a select list from values in a database

I have 2 select lists, one naming products and another for quantities.
<select name="fish" id="fish">
<option value="blueFish">Blue Fish</option>
<option value="redFish">Red Fish</option>
<option value="pinkFish">Pink Fish</option>
<option value="greenFish">Green Fish</option>
</select>
<select name="numFish" id="numFish">
<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>
</select>
I would like it so when a product is chosen, the corresponding quantity from the database will be set accordingly.
So if there was a record that customer Billy had bought 5 Pink Fish, when I select Pink Fish, the quantity select list will change to 5.
This would be for use in a PHP form using a MySQL database.
Is such functionality possible, and if so how would I go about doing it?
You might want to google for ajax requests. What it does is detecting a change (in your case) through javascript, send the value you selected to another php script which should do a sql query to return the quantity. The ajax request will catch the returned value and through javascript again change the value from the select dropdown.
All this would happen in the background and your site wouldn't refresh.
If you are not very used to javascript you can have a look at the jquery framework, which makes this task a bit easier, and with a lot of examples documented.
I didn't paste any code because assume you are not familiar with javascript/jquery/ajax. You might want to read a bit of documentation and play around a bit, and come back when you have a concrete problem, that would be the normal workflow here in Stackoverflow.
Edit: (some code as requested by OP)
Javascript:
$('#fish').change(function(){
var fishType = $('#fish select option:selected');
$.ajax("getQuantity.php", {fish: fishType}, function(data){
data = JSON.parse(data);
if(data.status == "OK"){
var quantity = data.quantity;
$('#numFish option[value='+quantity+']').prop("selected", true);
} else {
alert("error");// or console.log(), whatever you prefer
}
}
});
php (getQuantity.php):
<?php
$fish = $_POST['fish']; //getting the fish type
$sql = "your SQL to select the fish quantity for that type";
$result = mysqli_query($mysqli, $sql);
if(mysqli_num_rows($result)>0){
$row = mysqli_fetch_assoc($result);
$data = array("status" => "OK", "quantity" => $row['quantity']); // you can just output a string with the number if you want, but this way you have more control and better debugging.
echo json_encode($data);
}
?>
It's a basic code, it still would need to catch some errors for the database or return a different status. But basically that's it. I didn't even test that code so use it as a guideline only.
Change <select name="fish" id="fish"> to <select name="fish" id="fish" onchange="getQuantity(this.value);">
Declare the following function in javascript:
function getQuantity( o ) {
// get the quantity from the database using ajax,
// and set the quantity dropdown here.
}

Form 'SELECT' element returning incorrect value

Hello I have a form select element as follows:
<select name="color" id="color">
<option value="1" label="Red">Red</option>
<option value="2" label="Green">Green</option>
<option value="3" label="Blue">Blue</option>
</select>
When I submit the form, and check the $_POST, I get:
array('color' => 'Red')
Where it should be:
array('color' => '1')
I am a little confused, would it have something to do with the label attribute?
---- Edit ----
dojo.addOnLoad(function() {
dojo.forEach(zendDijits, function(info) {
var n = dojo.byId(info.id);
if (null != n) {
dojo.attr(n, dojo.mixin({ id: info.id }, info.params));
}
});
dojo.parser.parse();
});
var zendDijits = [{"id":"color","params":{"autocomplete":"true","required":"true","dojoType":"dijit.form.ComboBox"}},...
Your code appears to be valid, but the label may be interfering with something. Since you don't need it (you use the same text as the text between the option tags), I suggest you remove it.
Try it this way:
<select name="color" id="color">
<option value="1">Red</option>
<option value="2">Green</option>
<option value="3">Blue</option>
</select>
Some more info on the label attribute.
Definition and Usage
The label attribute specifies a shorter version of an option.
The shorter version will be displayed in the drop-down list.
Although the information was not provided in the question for anyone to answer, the solution to the problem was this:
The form element was being created in Zend Framework as a Zend_Dojo_Form_Element_ComboBox, and I found the following information in the documentation.:
ComboBoxes return the label values, and not the option values, which
can lead to a disconnect in expectations. For this reason, ComboBoxes
do not auto-register an InArray validator (though FilteringSelects
do).
Changed the element to a Zend_Dojo_Form_Element_FilteringSelect, and the problem was resolved, working fine now.
Thanks to #devdRew who asked the right question that tipped me off on the thought of dojo/dijit changing the value of what is posted.

Building an URL according to values sent from multiple select boxes

I'm working at some e-commerce website where I have a bunch of filters for each product category. The filters are displayed in select boxes and each filter has more than one value.
For example if you are browsing the watches category, possible filters are: brand (Tissot, Certina, Timex), movement type (automatic, mechanic, quartz), chronograph (yes, no).
The value for each select option is a pair of filter id and filter option id, separated by a comma.
For example:
<label for="filter-sex">Sex</label>
<select id="filter-sex" name="filter-sex">
<option value="">All</option>
<option value="1,1">For her</option>
<option value="1,2">For him</option>
</select>
<label for="filter-brand">Brand</label>
<select id="filter-brand" name="filter-brand">
<option value="">All</option>
<option value="3,10">Tissot</option>
<option value="3,11">Certina</option>
</select>
What I would like to accomplish is to pass those values in the URL.
For example if I select "For her" from the filter mentioned above, my URL must look like http://www.mystore.com/watches/filters-1,2/
Then, if I select Tissot from the brand filter, the URL must look like http://www.mystore.com/watches/filters-1,2-3,10/
Any ideas how can I build that URL according to selected values?
I am assuming you have a button that when the user clicks, it takes them to the url, right?
$('select').change(function(){
buildURL();
});
function buildURL(){
var baseUrl = 'http://www.mystore.com/watches/filter';
var url = baseUrl;
$('select').each(function(index, value){
if(value.value != "")
url += '-' + value.value;
});
$('#url').html(url);
}
For this version, check out: http://jsfiddle.net/jCq9U/
If you would like to do it server side, it would be the same logic.
$baseUrl = 'http://www.mystore.com/watches/filters';
$filterSex = $_POST['filter-sex'];
$filterBrans = $_POST['filter-brand'];
header('Location: ' . $baseUrl . "-" . $filterSex . "-" . $filterBrand);

Get data from SELECT

Let's say I have this:
<select name="exposure">
<option value='1,0.005'>Micro</option>
<option value='2,0.007'>Mini</option>
</select>
<select name="clicks">
<option value="2500">2500 - Clicks</option >
<option value="500">500 - Clicks</option >
</select>
<label>Price:</label>
<div id="price"></div>
How can I do, so whenever I select something from select="exposure", it will automatically change the OPTIONS of select="clicks", and at last, take the value from select="clicks" and then multiply it with the second value of select="exposure".
Example
I have selected
<option value='2,0.007'>Mini</option>
And with this option, the only click package that is available is:
<option value="2500">2500 - Clicks</option >
Price: 0.007*2500 = 17,5
Is that possible?
Try this
$("select[name=clicks]").change(function(){
$("label").text( parseFloat($(this).val()) * parseFloat($("select[name=clicks]:option:eq(1)")[0].value) );
});
To "select value of select":
$('select[name="exposure"]').val('2,0.007');
To make only some options available:
$('select[name="clicks"] option[value="500"]').remove();
To extract data from value:
var splitResult = $('select[name="exposure"]').val().split(',');
alert(splitResult[0] * splitResult[1]);
But I personally suggest to not pass additional information via the attribute "value"; better solution would be to create a new attribute to such needs.

Categories