Javascript on screen calculations from select / radio box - javascript

Currently I am working on a reservations website, I have implemented select boxes and radio buttons to enable the user to select their party size and if they want VIP seating. I have also implemented a price factor based off of these two selections.
I have enabled php to perform the calculations once the submit button is pressed by the user, however I would much prefer for these calculations to be performed automatically on screen as well, using javascript, once the user makes a selection.
Here is the html code for the party size selection:
<select name="party" value="<?php echo $party;?>">
<option value="">Please Select</option>
<option <?php if (isset($party) && $party=="5") echo "selected";?> value="5">1 Person (£5)</option>
<option <?php if (isset($party) && $party=="10") echo "selected";?> value="10">2 People (£10)</option>
<option <?php if (isset($party) && $party=="15") echo "selected";?> value="15">3 People (£15)</option>
<option <?php if (isset($party) && $party=="20") echo "selected";?> value="20">4 People (£20)</option>
<option <?php if (isset($party) && $party=="25") echo "selected";?> value="25">5 People (£25)</option>
<option <?php if (isset($party) && $party=="30") echo "selected";?> value="30">6 People (£30)</option>
<option <?php if (isset($party) && $party=="35") echo "selected";?> value="35">7 People (£35)</option>
<option <?php if (isset($party) && $party=="40") echo "selected";?> value="40">8 People (£40)</option>
<option <?php if (isset($party) && $party=="45") echo "selected";?> value="45">9 People (£45)</option>
<option <?php if (isset($party) && $party=="50") echo "selected";?> value="50">10+ People (£50)</option>
</select>
<span id="party" class="error"><?php echo $partyErr;?></span>
Here is the html code for the VIP selection:
<strong> VIP area* : </strong> <br><br>
Yes (+£5) <input type="radio" name="vip" <?php if (isset($vip) && $vip=="Yes") echo "checked";?> value="Yes">
<br><span id="vip" class="error"><?php echo $vipErr;?></span><br>
No <input type="radio" name="vip" <?php if (isset($vip) && $vip=="No") echo "checked";?> value="No">
Heres the line I wish to display the total price on:
<strong>Total booking cost based on party size & VIP selection: £<span id="price">0</span></strong>
Here is the javascript I have thus far:
$(document).ready(function(){
$(document).on('change', '#party', function(e) {
$('#price').html(parseInt($(this).val()) + parseInt($('input[name="vip"]').val()));
});
$(document).on('click', 'input[name="vip"]', function(e) {
$('#price').html(parseInt($('#party').val()) + parseInt($(this).val()));
});
});
Currently the totals of each price aren't being calculated. When the user clicks a party size, the total cost shows blank and if the user selects to be seated in a VIP area, no change is made either. There is probably a simple error in my coding so if anyone knows how I can fix this to make it function properly, please help.
Thank you.

Your are selecting the span element, not the select. To correct this, you can change the "on" statement as follows:
$("select[name=party]").on("change", function() {
//your handler code
});

The selector you are using is wrong since "party" is the name of the select and not the ID.
$(document).on('change', '#party', function(e) {
Change your select element to
<select id="party" value="<?php echo $party;?>">
and change the id of your span below to something else.
Same thing applies to your VIP input.

Related

how to avoid repetition of values in dropdown list while updating in php

I want to update "profile of a user" in php. There is a repetition of one value for two times in dropdown list. for example i take language value='Punjabi' from database but there is also a value placed in dropdown with name of 'Punjabi'.
The issue is simply that there is a repetition of value which i don't want.
<?php $result=mysqli_query($conn, "select * from profile where id=$firstPerson");
while($queryArray=mysqli_fetch_array($result)){ ?>
<select name="language" id="language" >
<option value='<?php echo $queryArray["language"];?> '> <?php echo $queryArray["language"]; ?></option>
//for example, the value from database is "Punjabi"
<option value="Hindi">Hindi</option>
<option value="Punjabi">Punjabi</option>
<option value="Urdu">Urdu</option>
</select>
<?php } ?>
when a value='Punjabi' from database is selected in dropdown list, the dropdown should not show the value='Punjabi' that is already placed in dropdown.
Remember: i have more than 1000 values in my dropdown(html) list.
screenshot
Instead of creating a new option according to the user data, Check if existing options are equal to user data:
<select name="language" id="language" >
<option value="Punjabi" <?php if ($queryArray["language"]=="Punjabi"){echo 'selected="selected"'} ?>>Punjabi</option>
<option value="Hindi" <?php if ($queryArray["language"]=="Hindi"){echo 'selected="selected"'} ?>>Hindi</option>
<option value="Urdu" <?php if ($queryArray["language"]=="Urdu"){echo 'selected="selected"'} ?>>Urdu</option>
</select>
If there are large number of options and you don't want to hard code these conditions, you can remove the second option using javascript on DOM ready:
$(document).ready(function(){
$('option[value="<?php echo $queryArray["language"] ?>"]').eq(1).remove();
})
skip the loop when value is equal to Punjabi, Urdu and Hindi.
<?php $result=mysqli_query($conn, "select * from profile where id=$firstPerson");
while($queryArray=mysqli_fetch_array($result)){ ?>
<select name="language" id="language" >
<?php if($queryArray["language"]!="Punjabi" && $queryArray["language"]!="Urdu" &&
$queryArray["language"]!="Hindi") { ?>
<option value="Hindi">Hindi</option>
<option value="Punjabi">Punjabi</option>
<option value="Urdu">Urdu</option>
<?php } ?>
I think you are doing it wrong way the correct way would be having a table which stored all the languages along with values
using selected attribute to achieve your objective
<?php
$result=mysqli_query($conn, "select * from profile where id=$firstPerson");
$queryArray1=mysqli_fetch_array($result);
$langOfUser=$queryArray1["language"];
?>
<select name="language" id="language" >
<?php $result=mysqli_query($conn, "select * from langtab");
while($queryArray=mysqli_fetch_array($result)){ ?>
<option value='<?php echo $queryArray["languageValue"];?> ' <?php if($langOfUser== $queryArray["languageValue"]){ echo 'selected';}?>> <?php echo $queryArray["languageName"]; ?></option>
<?php } ?>
</select>
You have to use if condition to display values in select option.
<select name="language" id="language" >
<?php $result=mysqli_query($conn, "select * from profile where id=$firstPerson");
while($queryArray=mysqli_fetch_array($result)){
if($queryArray["language"]!="Punjabi") {
$opval = "<option value=" . $queryArray["language"] . ">". $queryArray["language"]. " </option> "
echo $opval;
}
?>
<option value="Punjabi">Punjabi</option>
<option value="Hindi">Hindi</option>
<option value="Urdu">Urdu</option>
</select>
So your problem is that you have html hardcoded options and database options. You need to merge them into one on that website.
So you can use some javascript
elements = [1, 2, 9, 15].join(',')
$.post('post.php', {elements: elements})
But you can fill your elements like this is you don´t want to write it by hand
$("#id select").each(function()
{
allOptionsInSelect.push($(this).val());
});
Than on php side you can do
$elements = $_POST['elements'];
$elements = explode(',', $elements);
And now you have html hardcoded select on server side. Now you need to check if it doesn´t already exist when you are printing from database
You can do that like this
if(in_array(value_from_database, $elements) {
// It is so skip
} else {
// It is not, so print it
}
You can use if elseif this way.
<select name="language" id="language" >
<option value='<?php echo $queryArray["language"];?>'><?php echo $queryArray["language"]; ?></option>
<?php if ($queryArray["language"] == "Hindi") { ?>
<option value="Punjabi">Punjabi</option>
<option value="Urdu">Urdu</option>
<?php } elseif ($queryArray["language"] == "Urdu") { ?>
<option value="Punjabi">Punjabi</option>
<option value="Hindi">Hindi</option>
<?php } elseif ($queryArray["language"] == "Punjabi") { ?>
<option value="Urdu">Urdu</option>
<option value="Hindi">Hindi</option>
<?php } ?>

How to call HTML required attribute when the value is 0?

I have a drop down list where I'm populating data from the database.
<div class="form-group">
<label>Title:</label>
<select class="form-control" name="Title" id ="titleselect" required>
<!-- <option value="" selected="selected">?</option> -->
<?php foreach ($titles as $row) {
if($this->session->userdata('status')=='active' && $this->session->userdata('Title') == $row->id) { ?>
<option value="<?php echo $row->id; ?>" selected="selected"><?php echo $row->value; ?></option>
<?php }else{?><option value="<?php echo $row->id; ?>"><?php echo $row->value; ?></option><?php } }?>
</select>
</div>
My form,
How values are populated from the database,
My database table,
I want to add a validation when the title form is populated with the value "0", which is "?", it should call the HTML required attribute.
Or I would like to disable the option with the '?' mark.
How can I do achieve this?
I have managed to find a solution to my issue. I managed to do it without any JS or Jquery. Just added an if statement.
<div class="form-group">
<label>Title:</label>
<select class="form-control" name="Title" id ="titleselect" required>
<?php foreach ($titles as $row) {
if($this->session->userdata('status')=='active' && $this->session->userdata('Title') == $row->id) { ?>
<?php if(($this->session->userdata('Title') == 0)) { ?>
<option value="" selected disabled><?php echo $row->value; ?></option>
<?php } else{?>
<option value="<?php echo $row->id; ?>" selected="selected"><?php echo $row->value; ?></option>
<?php } ?>
<?php }else{?><option value="<?php echo $row->id; ?>"><?php echo $row->value; ?></option><?php } }?>
</select>
you can use jquery like this: you can use an id for ? like id="yourZeroOption" and then
$('option#yourZeroOption').each(function() {
if ($(this).isChecked())
$("select").attr("required", true);
else
alert('this filled cannot be ?');
});
since what you asked was'nt clear enough this code might helf and if you manipulate this code you can get what you want from your code. but this for sure will give you a gist of what you should do. by the way this code does not need to submit it will show the alert before that
If this is in Laravel there is a way to catch certain number to be pass. In this case, try with greater_than rule with a custom message.
Example
$this->form_validation->set_rules('title', 'Title', 'greater_than[0]');
$this->form_validation->set_message('greater_than', 'Please select one of these value');
Note: JS validation works, But keep mind it's not always.
You should mark your <select> field as required, then the first option as disabled (and selected):
<select required>
<option value="" selected disabled>?</option>
<option value="1">Mr.</option>
<option value="2">Miss</option>
<option value="3">Mrs.</option>
</select>
This will make the first entry work as a placeholder basically.
we cant make it require with 0 value it can be done only if value=""
here is my idea,
<form action="/action_page.php">
<select required>
<option value="0">?</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<input type="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("select option:selected").val("");
});
</script>
<style>

PHP: Simple seeming IF statement but not seeming to be working

So I understand if this may take a while to process but I have a dropdown box and what it's meant to do is if certain selections are clicked then it will fetch info in the database depending on what they selected. My question is, why aren't my if statements working when I have applied a session onto each selection and am fetching them based on the ones clicked.
Here is the HTML:
<div class="button_wrap">
<select name="makeSelectLeft" class="compareButtonSizing" required="required" multiple="multiple">
<option>Make</option>
<?php session_start(); $_SESSION['MitOne']="Mitsubishi1" ?><option value="Mitsubishi1">Mitsubishi</option>
<?php session_start(); $_SESSION['SubOne']="Subaru1" ?><option value="Subaru1">Subaru</option>
<?php session_start(); $_SESSION['ToyOne']="Toyota1" ?><option value="Toyota1">Toyota</option>
</select>
<select name="modelSelectLeft" required="required" multiple="multiple">
<option>Model</option>
<?php session_start(); $_SESSION['LancOne']="Lancer1" ?><option value="Lancer1">Lancer</option>
<?php session_start(); $_SESSION['EvoOne']="Evolution1" ?><option value="Evolution1">Evolution</option>
<?php session_start(); $_SESSION['CamOne']="Camry1" ?><option value="Camry1">Camry</option>
</select>
<select name="yearSelectLeft" required="required" multiple="multiple">
<option>Year</option>
<?php session_start(); $_SESSION['1982 - 1983']="1982 - 1983" ?><option value="1982 - 1983">1982 - 1983</option>
<?php session_start(); $_SESSION['1983 - 1991']="1983 - 1991" ?><option value="1983 - 1991">1983 - 1991</option>
<?php session_start(); $_SESSION['1988 - 1995']="1988 - 1995" ?><option value="1988 - 1995">1988 - 1995</option>
<?php session_start(); $_SESSION['1995 - 2000']="1995 - 2000" ?><option value="1995 - 2000">1995 - 2000</option>
<?php session_start(); $_SESSION['2000 - 2007']="2000 - 2007" ?><option value="2000 - 2007">2000 - 2007</option>
<?php session_start(); $_SESSION['2007 - 2017']="2007 - 2017" ?><option value="2007 - 2017">2007 - 2017</option>
</select>
</div>
Thats where I added in the starts for the sessions. There is a session for each selection. In the PHP I currently have three outputs no matter what options I select. It's supposed to only have one and show one depending on what Make, Model, and Year you have selected.
Here is the PHP:
<?php
session_start();
if (!empty($_SESSION['MitOne']) && ($_SESSION['LancOne']) && ($_SESSION['1982 - 1983'])) {
$MitFirstState = mysql_query("SELECT Max_Speed FROM CarSpecifications WHERE id=2");
while ($MitFirstFetch = mysql_fetch_array($MitFirstState)) {
print_r($MitFirstFetch[0]);
}
}
if (!empty($_SESSION['SubOne']) && ($_SESSION['LegOne']) && ($_SESSION['1982 - 1983'])) {
$SubFirstState = mysql_query("SELECT Max_Speed FROM CarSpecifications WHERE id=3");
while ($SubFirstFetch = mysql_fetch_array($SubFirstState)) {
print_r($SubFirstFetch[0]);
}
}
if (!empty($_SESSION['ToyOne']) && ($_SESSION['CamOne']) && ($_SESSION['1982 - 1983'])) {
$ToyFirstState = mysql_query("SELECT Max_Speed FROM CarSpecifications WHERE id=4");
while ($ToyFirstFetch = mysql_fetch_array($ToyFirstState)) {
print_r($ToyFirstFetch[0]);
}
}
?>
The main thing I don't understand is why the if statements aren't working. I have tried putting else statements on there and changing the isset/empty variables and all of it. It doesn't seem to work.
Again I apologise for the large amount of info. If someone could help that would be greatly appreciated.
P.S. If someone has a javascript solution they are welcome.
Thank You.
Request-Response is actually simpler than you're trying to attempt.
Your request session in 2nd file will have values initialised for parameters "makeSelectLeft, modeSelectLeft and yearSelectLeft" in the $_REQUEST object. These values are data in "value" attribute of "option".
<option value="Mitsubishi1">
Hence this php snippet is redundant. Remove these from your HTML.
<?php session_start(); $_SESSION['MitOne']="Mitsubishi1" ?>
In your PHP code, $_REQUEST['makeSelectLeft'] will give all values of options selected by user. Similarly you can retrieve data for others. Following that, make your database queries etc.
None of this is being executed properly. As mentioned, you need your session_start(); one time and at the top of the page. Second you need to take advantage of form submission values, not session values. Last, you have to submit the form or use AJAX to process the user's selections. Here is an example (submission of the form is required, you would need to research ajax to do dynamic selections):
<?php
# I'm not convinced you even need this in your example, but you only put it
# once at the top of the page
session_start();
# Process the submission
if(!empty($_POST['action']) && $_POST['action'] == 'do_options') {
# Here is where you do your if conditions based on the post, not session
print_r($_POST['selectleft']);
}
?>
<!--
....html on your page...etc.
-->
<form action="" method="post">
<input type="hidden" name="action" value="do_options" />
<div class="button_wrap">
<select name="selectleft[make]" class="compareButtonSizing" required="required" multiple="multiple">
<option value="">Make</option>
<option value="Mitsubishi1">Mitsubishi</option>
<option value="Subaru1">Subaru</option>
<option value="Toyota1">Toyota</option>
</select>
<select name="selectleft[model]" required="required" multiple="multiple">
<option value="">Model</option>
<option value="Lancer1">Lancer</option>
<option value="Evolution1">Evolution</option>
<option value="Camry1">Camry</option>
</select>
<select name="selectleft[year]" required="required" multiple="multiple">
<option>Year</option>
<option value="1982_1983">1982 - 1983</option>
<option value="1983_1991">1983 - 1991</option>
<option value="1988_1995">1988 - 1995</option>
<option value="1995_2000">1995 - 2000</option>
<option value="2000_2007">2000 - 2007</option>
<option value="2007_2017">2007 - 2017</option>
</select>
</div>
<input type="submit" value="SAVE" />
</form>

Filter Dropdown Based on Another Dropdown Selection

I have multiple dropdowns and want to filter the contents of the second dropdown based on what is selected in the first dropdown. Here is the following code that I have so far. How could I do this?
HTML/PHP:
<td>
<select id="major" onChange="updateCat();">
<?php foreach ($dropdown_major->fetchAll() as $drop_major): ?>
<option
value=""
data-name="<?php echo $drop_major ['Major Category'];?>"
>
<?php echo $drop_major ['Major Category'];?>
</option>
<?php endforeach; ?>
</select>
</td>
<td>
<select id="minor">
<?php foreach ($dropdown_minor->fetchAll() as $drop_minor): ?>
<option
value=""
data-name="<?php echo $drop_minor ['Minor Category'];?>"
>
<?php echo $drop_minor ['Minor Category'];?>
</option>
<?php endforeach; ?>
</select>
</td>
JavaScript:
function updateCat() {
var e = document.getElementById("major");
var majorSelected = e.options[e.selectedIndex];
document.getElementById("minor").value = majorSelected.dataset.name;
}
Database connection and SQL statements:
<?php
$host="xxxxxxxxxxx";
$dbName="xxxxx";
$dbUser="xxxxxxxxxxxxx";
$dbPass="xxxxxxxx";
$dbh = new PDO( "sqlsrv:server=".$host."; Database=".$dbName, $dbUser, $dbPass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql_major = "SELECT DISTINCT [Major Category] FROM ProductTable ORDER BY [Major Category] ASC";
$sql_minor = "SELECT DISTINCT [Minor Category] FROM ProductTable ORDER BY [Minor Category] ASC";
$dropdown_major = $dbh->query($sql_major);
$dropdown_minor = $dbh->query($sql_minor);
?>
Sorry don't have much time can't make your answer for your code but giving you an example which will surely help you. run snippet below.
HTML
<select id="first" onchange="showsecondlist()">
<option>Select</option>
<option value="1"> 1 </option>
<option value="2"> 2 </option>
</select>
<br>
<select id="second"></select>
and Javascript
function showsecondlist()
{
var uservalue=document.getElementById("first").value;
if(uservalue==1)
document.getElementById("second").innerHTML='<option value="1.1">1.1</option><option value="1.2">1.2</option>';
else if(uservalue==2)
document.getElementById("second").innerHTML='<option value="2.1">2.1</option><option value="2.2">2.2</option>';
}
this code will work for you but try to use JSON for sending options to user and then apply some if else statement according to user selection of first drop down.
Tip: If you have large no. of options in select statement or large no. of select statements in your code then go and learn AJAX First. its easy and simple you can learn it easily. JSON and AJAX hardly takes 2-3 days.In Ajax call function according to user selection and send data using JSON. Although Ajax increases no. of request to server but it will decrease code length. which decreases page load time, easy to maintain, and good for search engine. Google love pages with less code and more information and will help you in future too to solve lots of problems easily.
function showsecondlist()
{
var uservalue=document.getElementById("first").value;
if(uservalue==1)
document.getElementById("second").innerHTML='<option value="1.1">1.1</option><option value="1.2">1.2</option>';
else if(uservalue==2)
document.getElementById("second").innerHTML='<option value="2.1">2.1</option><option value="2.2">2.2</option>';
}
<select id="first" onchange="showsecondlist()">
<option>Select</option>
<option value="1"> 1 </option>
<option value="2"> 2 </option>
</select>
<br><br>
<select id="second"></select>

show or hide component with a trigger from multiplied combo box

I can't show or hide a component from a multiplied combo box, but I can show or hide it from an original combo box(the first combo box)
what should I do..?
this is function to multiply the combo box
function addEmploy() {}
$('#addEmploy').click(function(){
$('#comboEmploy')
.append('<br />')
.append($('#comboEmploy select').first().clone());
});
this is script to show or hide the component
$("#employ").change(function() {
if($(this).val() == "2"){
$("#comboStudy").show("slow");
}else{
$("#comboStudy").hide("slow");
}
});
This is the combo box
<span id="comboEmploy">
<select name="employ[]" id="employ">
<option value="NULL" selected >Choose one</option>
<?php foreach ($employs as $employ) :?>
<option value="<?php echo $employ->employ_id; ?>">
<?php echo $employ->employ_name; ?></option>
<?php endforeach; ?>
</select>
</span>
Add Employ
This is the component that I want to show/hide
<span id="comboStudy">
<select name="study[]" id="study">
<option selected value=NULL>Choose one</option>
<?php foreach ($studies as $study) :?>
<option value="<?php echo $study->study_id; ?>">
<?php echo $study->study_name; ?></option>
<?php endforeach; ?>
</select>
</span>
Can anyone help me. thanks before.
When you clone the select box, you need to tell jQuery to clone the events along with it:
.clone(true);
As you are appending elements to the DOM after page load you need to use the live() function to attach their events:
$("#employ").live("change", function() {
...
}

Categories

Resources