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>
Related
I have this filtering feature on my program. It is in the form of a drop-down list. I'm currently using the Select-Option method to display the options on my dropdown list. However, it doesn't look good if the list is very long so what I would want to do is create a submenu. For example, I have 20 options. What I want is to transform it into 5 options with each option also having children or sub-options.
Here's what I did originally and could be a good case. So instead of displaying the 3 malls under the main options, I would want to make a mother option called "Filter by Mall" then later on, "Filter by Location" instead of displaying all locations on the main option, etc.
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="GET">
<select name="formStats">
<option value="Rob">Robinson's Manila Stores</option>
<option value="MoA">Mall of Asia Stores</option>
<option value="GG">Greenbelt/Glorietta Stores</option>
<input type="submit" name="formSubmit" value="Submit"/>
</form>
Here's the part where I put the cases under my PHP script.
if(isset($_GET['formSubmit']))
{
$varStats = $_GET['formStats'];
$errorMessage = "";
switch($varStats)
{
case "Rob": $show = "Mall = 'Robinson\'s Manila'"; break;
case "MoA": $show = "Mall = 'Mall of Asia;"; break;
case "GG": $show = "Mall = 'Glorietta/Greenbelt'"; break;
}
$conn = db_connect();
showStore($conn, $show);
db_disconnect($conn);
exit();
}
On the issue of hovering over the option element this note from MDN might be of interest.
[2] Historically, Firefox has allowed keyboard and mouse events to
bubble up from the element to the parent element.
This doesn't happen in Chrome, however, although this behavior is
inconsistent across many browsers. For better Web compatibility (and
for technical reasons), when Firefox is in multi-process mode and the
element is displayed as a drop-down list. The behavior is
unchanged if the is presented inline and it has either the
multiple attribute defined or a size attribute set to more than 1.
Rather than watching elements for events, you should watch
for {event("change")}} events on
I experimented with nested selects - doesn't work. Listening for events on the option element also did not work ( at least not in Chrome which is what I use most these days, hence note above ) so you MIGHT be able to monitor events on the parent (select) and accomplish what you want that way - no doubt there is sometrickery available in jQuery to do this...
As an aside, a little experiment - not exactly what you were trying to do but close.
<select id='depsel'>
<option data-menu=1>1st Example
<option data-menu=2>2nd Example
<option data-menu=3>3rd Example
</select>
<span id='subopt' style='display:none;border:1px solid black;width:100px;min-height:200px;'></span>
<script>
var menu=document.getElementById('depsel');
var span=document.getElementById('subopt');
menu.addEventListener('change',function(e){
var selected=this.options[this.options.selectedIndex].dataset.menu;
span.style.display='block';
span.innerHTML='';
var div=document.createElement('div');
div.innerHTML=this.value;
div.onclick=function(evt){
span.style.display='none';
}
span.appendChild( div );
}.bind( menu ),false );
</script>
I've set up a currency conversion dropdown in a wordpress site.
The only thing missing is that every time I load another page, the currency will reset as the form selection was 'forgotten'.
Any ideas how to do this? I tried a suggested js cookie that I saw here, but it doesn't work.
This is what I got so far:
<form name="myform" id ="myform" method="post">
<select name="currency-select" id="sort" onchange="submitform();">
<option value="" selected="selected">Currency</option>
<option value="0">U.S Dollars (USD)</option>
<option value="1">Euros (EUR)</option>
<option value="2">British Pounds (GBP)</option> `
</select>
</form>
js:
function submitform()
{
document.myform.submit();
}
I tried using this code as recommended here but it doesn't really work out for me, I think I didn't do it the right way -
<?php
`session_start();`
if (isset($_POST['currency-select'])) {
$_SESSION['sort'] = $_POST['sort'];
}
?>
I added the $_SESSION to the form as well:
<option value="0" <?php if($_SESSION['sort'] == "0") echo "selected";?>>U.S Dollars (USD)</option>
UPDATE
I've made a few tests. The session seems to be saved (as I echoed it on a few pages while refreshing etc.) I guess the only problem now is related to the form itself. Even with the right session number, I can't get it to select the right option.
I've tried two methods, but both does not work:
<option value="0" <?php if($_SESSION['currency-select'] == "0") echo 'selected="selected"';?>>U.S Dollars (USD)</option>
or
<option value="0" <?php if($_SESSION['currency-select'] == "0") echo "selected";?>>U.S Dollars (USD)</option>
I'd store the selected value in a $_SESSION['selected_currency'] variable and the cross check and select it when the drop down is being populated with the currency list.
Assuming that the sessions are working, I will use something like below to keep the currency selected in your drop down.
<select name="currency">
<?php
foreach($currency as $value){
if($value->currency_code == $_SESSION['currency']){
echo "<option value='$value->currency_code' selected='selected'>$value->currency_name</option>";
} else {
echo "<option value='$value->currency_code'>$value->currency_name</option>";
}
}
?>
</select>
There could be shorter ways, I am using this for illustration purposes.
For permanent retain of data you only have a few possibilities, the easiest to implement are $_SESSION, $_COOKIE or in a Database.
You have two options to do that
1st is by adding a field to the options.php page and save your data then get back your data from the options.php for that you've to use update_option('nameOfField_form','nameOfFieldDb'); and get_option('nameOfFieldDb').
and 2nd option is by jquery.ajax(); method save your data in options.php
you may find these links helpful codex
get_option
update_option
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];
}
}
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.
}
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.