This is driving me crazy and I couldn't find information that could help me figure this out.
I have a simple check-in form as follows:
<label for="adults" class="field-label"> Adults</label>
<label class="field select prepend-icon">
<select id="adults" name="adults" onChange="updatesum()">
<option value="0">...</option>
<option value="300">1</option>
<option value="600">2</option>
<option value="900">3</option>
</select>
</label>
Those option values are prices used to calculate the price per person and the text is actually the amount of adults checkin-in.
What I can't figure out is that when I submit the form the PHP posts the value of the field instead of the amount of adults checking in which are between 1 and 3 max.
$adults = strip_tags(trim($_POST["adults"]));
Can i replace that values before sending the email to something like this:
If the value = 300 then replace with 1
If the value = 600 then replace with 2
If the value = 900 then replace with 3
and then send the email with the number of adults and not the price.
Can anybody give me a hand?? thanks!!
You can check it live here westermansfrigga.se and press the button "boka nu", that's the form I'm making.
It's still in testing phase you can make test bokings and you should get the corresponding emails. For a clear understanding of what I mean with replacing the values. In the confirmation email adults = 300 instead of 1.
The behaviour of your form is the expected one. The value of the field is sent, not its text. So
<option value="ThisWillBeSent">This will NOT be sent</option>
I imagine that you use "value" for some operation on onChange (so if I were you, I would add that script to the question). The best solution would be to have a different attribute holding the number:
<option data-value="300" value="1">One Adult</option>
This way, the number of adults gets sent, and the client still has the amount to work upon. In the javascript you read the new attribute, e.g. in jQuery,
sum += $el.attr("data-value")
instead of
sum += $el.attr("value")
If you're using plain Javascript, then you would have something like
var combo = document.getElementById("adults");
var adultValue = combo.options[combo.selectedIndex].getAttribute("data-value");
To replace values server side, in PHP, you can use switch:
switch ($valueIn) {
case 300: $valueOut = 1; break;
case 600: $valueOut = 2; break;
case 900: $valueOut = 3; break;
default:
// Throw some error, to be warned should you ever change
// the client side array and get an unknown value such as 1200.
}
(or, in this case, also $valueOut = $valueIn / 300).
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'm working on a small website and I'm currently stuck on a small issue.
Ive got a set of dropdown boxes created and populated in HTML, for example:
<select name="heatingType" id="heatingType" required>
<option value="" disabled selected>Select Your Option</option>
<option value = "Gas">Gas</option>
<option value = "Electricity">Electricity</option>
<option value = "Other">Other</option>
</select>
I'm able to store the values in a variable once the form has been posted/submitted, These are stored in my Controller Class eg:
$newCalc = new ConCalc();
// instantiate drawing tool
$draw = new DrawTool();
// parse (render) appliance view
$renderedView = $draw->render('../View/calculator.php', array('calcvalues' => $newCalc->getValues()));
if(isset($_POST['btn-calcCon'])){
$heatType = $_POST['heatingType'];
$meterType = $_POST['meterType'];
$bedrooms = $_POST['noBedrooms'];
$house = $_POST['houseType'];
$age = $_POST['houseAge'];
echo $heatType;
echo $meterType;
echo $bedrooms;
echo $house;
echo $age;
}
echo $renderedView;
If i echo out any of the varibales then it will display the value that was selected and posted in that dropdown.
My table structure is as follows:
HeatingType MeterType Bedrooms HouseType HouseAge Consumption
Gas Standard 1 or 2 Flat Less than 11 years 5430
Gas Standard 1 or 2 Flat More than 11 years 7270
So for example, if i chose Gas, Standard, 1 or 2, Flat and Less than 11 then i should have 5430 returned.
Now the problem I'm facing is how to use these posted values in a select statement,
I know i need to do something along the lines of :
SELECT Consumption fron ConTable WHERE HeatingType LIKE heatingTypeDropdownValue AND MeterType LIKE MeterTypeDropDownValue etc etc.
but im not exactly sure
Any help will be appreciated
Thanks!
I solved it by creating a session array:
`$_SESSION['post-data'] = $_POST;
$_SESSION['post-data']['heatingType'];
$_SESSION['post-data']['meterType'];
$_SESSION['post-data']['noBedrooms'];
$_SESSION['post-data']['houseType'];
$_SESSION['post-data']['houseAge'];`
And then using $_SESSION['post-data']['heatingType'] In the where clause
I'm having a bit of a confusing question but hopefully you'll get what I mean:
In my website I'm trying to implement a select box which is updated based on the value from a previous select box. For that I'm using a javascript that takes the values. For example an option from the select box looks like this:
<option value="22"> Apple </option>
I need the value in order to filter the select boxes but in my PHP script I need to get that 'Apple' text. Is there a way to do that?
Sorry for the noob question but web development is new for me.
Edit:
This is the java script I'm using for filtering the second select box:
$("#select1").change(function() {
if ($(this).data('options') == undefined) {
/*Taking an array of all options-2 and kind of embedding it on the select1*/
$(this).data('options', $('#select2 option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#select2').html(options);
});
If I try to change this 'value' in the filter function to some other attribute it doesn't work for some reason. I don't know JavaScript at all.
Try this
var pName = document.getElementById('selectname');
var name = pName.options[pName.selectedIndex].text;
Send the name value to your php script by hidden form field or ajax request,
It will contain the text of the option
try this
function getSelectedText(elementId) {
var elt = document.getElementById(elementId);
if (elt.selectedIndex == -1)
return null;
return elt.options[elt.selectedIndex].text;
}
var text = getSelectedText('test');
or
this.options[this.selectedIndex].innerHTML
fruits_array.php
<?php
$fruits= array(
22 => 'apple' ,
23 => 'orange'
);
form_handler.php
if( isset($_POST['chosen_fruit']) && (int)$_POST['chosen_fruit'] > 0 ){
include 'fruits_array.php';
echo you chose ' . $fruits[$_POST['chosen_fruit'];
}
pick_your_fruit.php
<form action='form_handler.php' method= POST>
<select name='chosen_fruit'>
<?php
include 'fruits_array.php';
foreach($fruits as $key=$fruit)
echo '<option value=' . $key . '>' . $fruit .'</option>' . PHP_EOL ;
?>
<input type=submit />
</form>
Give this a try. Maintain an array of fruit in one place. Include it where you need it. If necessary that array could be from a database.
Use the array to
generate the form elements
generate the message
But, essentially, transferring the number of the key between the form and the form handler eases the thorny question of validating the incoming data.
DRY. Dont Repeat Yourself. Now if you have 99 fruit, and you add another, you only add it in one place.
(the main thing missing is the handling of a fruit number which does not exist, which probably means someone is tampering with you input form, leave that for another question, eh?)
Try like this
<form method="post" action="getvalue.php">
<select name="fruit">
<option value="">select the option</option>
<option value="1">Apple</option>
<option value="2">Banana</option>
<option value="3">Mango</option>
</select>
</form>
<?php
$option = array('1'=>'Apple','2'=>'Banana','3'=>'Mango');
echo $option[$_POST['fruit']];
?>
The Apple is not passed to the server, only your value, in this case 23. You can see that when you change your formular method to GET, it will look like script.php?some_select=23.
Two solutions to solve it:
The first one (the easy one) would be:
<option value="Apple" data-filterid="22"> Apple </option>
And in your js:
var options = $(this).data('options').filter('[data-filterid=' + id + ']');
So you get Apple in your php script instead of 22. You could then filter it in javascript by accessing data-filterid instead of value.
The second solution would be to store an associative dictionary which maps the value to the number, e.g.:
<?php
$mapped = array(22 => "Apple", 23=>"Orange");
$value = $mapped[$_GET['option_name']];
I am sorry bad English. I have a select menu option value problem:
<select>
<option value=0>element1</option>
<option value=1>element2</option>
</select>
I am if select value="0" option and this post, it retuns the value with no problem. But, when I use value = 0 save mysql table, this value not 0 this return empty. This value saving column type integer? What is problem?
I am not using mysql_real_escape_string or any filter. If select value="1" option no problem, it is saving succesfully.
Thanks
I ran into this issue myself and what I found was that when posting option/select box values and reading them with PHP, when the 'value' of it was 0 it was acting like I did not post at all because I was checking to see anything had been posted like this:
if ($_POST['status']) {
// do stuff here
}
When in fact I needed to check it using isset(), because the way shown above returns false even if the value is 0. The example shown below checks to see if it really is set at all, even if the value is 0.
if (isset($_POST['status'])) {
// do stuff here
}
You did not show us your PHP code so I am only guessing this was also your problem.
you missed quotes (")
<select name="my_select">
<option value="0">element1</option>
<option value="1">element2</option>
</select>
<?php
$my_select_value = $_POST["my_select"];
echo $my_select_value;
?>
This one is a pain...no value is sent in the POST if it's a select and the value is 0....so if it's a POST and NOT sent you can assume the value was 0...
if($_POST){
if(isset($_POST['my_select'])){
//has a value, can assume it's 1 given the example
}else {
//posted, but value wasn't sent, can assume it's 0
}
}
My associative array.
$money = array("Nickels" => $_POST["nickels"], "Dimes" => $_POST["dimes"], "Quarters" =>$_POST["quarters"]);
My html form set up to handle Quarters,
Dimes and Nickels are not shown in this case for brevity.
<label><b>Quarters:</b></label>
<select name="quarters" >
<option value=".25">25c</option>
<option value=".50">50c</option>
<option value=".75">75c</option>
<option value="1">$1.00</option>
</select>
A user can only select either Quarters only, Dimes only, or Nickels only.
If a user selects Quarters with the option value of .25, this value will be sent to
the php script.
So I was just wondering for calculations based on the fact that the user can select
Quarters only with one value, Dimes only with one value, and Nickels only with one
value, and not a combination of denominations,
how would one go about setting up different test cases, for example if the user selects
$money["Quarters"]; // With different values coming from the html form as .25, .50,.75, or 1, and only one of the selected values will make it through to the php script depending on what the user selected.
Can I do this:
switch($selection)
{
case “Quarters”:
echo “ You chose $money[‘Quarters’]; .<br />”;
break;
case “Nickels”:
echo “You chose $money[‘Nickels’]; .<br />”;
break;
case “Dimes”:
echo “You chose $money[‘Dimes’]; . <br />”;
break;
default: print “Please select a Denomination”;
}
Thank you for not flaming the newb, I am still learning, and sorry for the mix and match in terms of " and “.
Selected values in a form are submitted as $_POST['quarters'].
I understand, that you want to check, if the user has selected more than one of your <select>s (correct?)
So, I'd create a check like this:
$selected = 0;
if ($_POST['quarters'] != "DEFAULT_VALUE_OF_YOU_SELECT_QUARTERS")
{
$selected++;
}
if ($_POST['nickels'] != "DEFAULT_VALUE_OF_YOU_SELECT_NICKELS")
{
$selected++;
}
if ($_POST['dimes'] != "DEFAULT_VALUE_OF_YOU_SELECT_DIMES")
{
$selected++;
}
if ($selected > 1)
{
// The user has selected more than one
}
There's a few things to pay attention to here.
So, first of all, your $money array captures every value the user submits.
Next, the way you have your HTML <select> statement set up, there's no default value. The first option in $_POST["quarters"] is going to be .25 even if the user never touches that pulldown. To avoid this, you would want to add to the Quarters <select>:
<option value="0">-- Select Quarters --</option>
But still this doesn't allow you to use a switch/case statement. You're still going to be submitting a value for EVERY HTML <select> tag. Florian Peschka's solution is better, since it checks every pulldown, making sure they only used one, and perhaps displays a message if they don't.
Finally... I don't know what $selection refers to in your example. You're populating the $money array, so the $selection variable doesn't exist.
I can further help if you clarify your question.