I have an order form. If the user change the packages, the price will be changed.
HTML
<select name="item" id="item">
<option value="i1">Item1</option>
<option value="i2">Item2<option>
</select>
<select name="detail" id="detail">
<option value="d1">Detail1</option>
<option value="d2">Detail2</option>
</select>
<p>Price : <span id="price"></span></p>
The PHP below will send the data gotten from the form
PHP
$item=$_POST["item"];
$detail=$_POST["detail"];
$price=0;
if($item=="p1"){
$price=$price+10;
}
else{
$price=$price+5;
}
if($detail=="d1"){
$price=$price+2;
}
else{
$price=$price+1;
}
// codes for sending the data to database
jQuery below will show the price of the chosen package. I want it to show the price everytime it's changed
jQuery
var item=$("#item").val();
var detail=$("#detail").val();
var price=0;
$("#item").on('change',function(){
if(item=="i1"){
price=price+10;
$("#price").html("$ "+price);}
else{
price=price+5;
$("#price").html("$ "+price);}
})
$("#detail").on('change',function(){
if(detail=="d1"){
price=price+2;
$("#price").html("$ "+price);}
else {
price=price+1;
$("#price").html("$ "+price);}
})
I want : price=price(item)+price(detail). The problem is, if the user change it more than once, it will add the number, althought the PHP will not send the number from jQuery.
Let's say, a user chooses Item1 and Detail2. The price shows 11. But, if the user changes it to Detail1, it will shows 13, etc, and finally, the user chooses Item2 and Detail1. PHP will send 7, but the jQuery will show more than 7. Any idea?
Hi :) You can use this code instead:
For you HTML:
<select name="item" id="item">
<option value="0" disabled selected>Select your option</option>
<option value="10">Item1</option>
<option value="5">Item2<option>
</select>
<select name="detail" id="detail">
<option value="0" disabled selected>Select your option</option>
<option value="2">Detail1</option>
<option value="1">Detail2</option>
</select>
<p>Price : <span id="price"></span></p>
and for your Jquery:
$(document).ready(function () {
$("#item,#detail").on('change',function() {
var item=$("#item").val() || 0;
var detail=$("#detail").val() || 0;
var price = 0;
price = parseInt(item) + parseInt(detail);
$("#price").html("$ "+price);
});
});
The simplest solution is to have one function that calculates the total when either of the values change, meaning it will recalculate the total price every time instead of having two functions affecting the same value. here is my solution below:
// Storage for the item prices
var itemDict = {
"p1": 10,
"p2": 4,
"p3": 0
};
// Storage for the detail prices
var detailDict = {
"d1": 2,
"d2": 5,
"d3": 2
};
$("#item").on('change', function () {
CalcPrice();
})
$("#detail").on('change', function () {
CalcPrice();
})
function CalcPrice() {
var price = 0;
const itemPrice = itemDict[$("#item").val()] || 2; // 2 as a default
const detailPrice = detailDict[$("#detail").val()] || 1; // 1 as a default
$("#price").html("$ " + price);
}
The problem is with these lines:
var item=$("#item").val();
var detail=$("#detail").val();
var price=0;
You are declaring and setting the values globally. And it will get set only once when the page is loaded. So, when you access these variables within the change event of #item and #detail, you are accessing the values from these global variables and doing the math and saving it back! So, the next time any of these change event is fired (that is, if user changes the item or detail from the dropdowns), you are again accessing the values from the global variables which contains the data from the previous calculation!
That's why you were getting wrong values.
So, the solution is to move those three variables to inside each of those change events
(what #JYoThi suggested), like these:
$("#item").on('change',function(){
var item=$("#item").val();
var detail=$("#detail").val();
var price=0;
if(item=="i1"){
price=price+10;
$("#price").html("$ "+price);}
else{
price=price+5;
$("#price").html("$ "+price);}
});
$("#detail").on('change',function(){
var item=$("#item").val();
var detail=$("#detail").val();
var price=0;
if(detail=="d1"){
price=price+2;
$("#price").html("$ "+price);}
else {
price=price+1;
$("#price").html("$ "+price);}
});
This will probably solve your issue for now!
#Vinia and #Cornelis has provided some good solutions too, hope you would be able to understand it on looking at it.
Cheers!
Related
I have a .php page with about two hundred select form elements on it. The element values are being populated by a .txt file in the same directory using PHP:
<?php
$schoolselected = 'schools.txt';
$eachlines1 = file($schoolselected, FILE_IGNORE_NEW_LINES);
?>
and
<select name="schoolselected001">
<option value="" disabled selected>Select School...</option>
<option value=" " <?php if(isset($_POST['schoolselected001'])) echo "selected"; ?>></option>
<?php foreach($eachlines1 as $lines1){
echo "<option value='".$lines1."'>$lines1</option>";
}?>
</select>
Each select form element have the same name but with 001 through 200.
I'm using this jQuery function to disable an option when selected to prevent doubling up:
<script>
$(document).ready(function(){
$('select[name*=schoolselected]').on('click', function() {
$('option').prop('disabled', false);
$('select[name*=schoolselected]').each(function() {
var val = this.value;
$('select[name*=schoolselected]').not(this).find('option').filter(function() {
return this.value === val;
}).prop('disabled', true);
});
}).change();
});
</script>
Everything works perfectly and there was no delay when I tested with ten values but now with two hundred values, there is a 10-12 second delay each time I click any of the select form elements.
Are there any tweaks I can do to the existing code to remove the delay? Or maybe I'm taking the wrong approach? I looked into caching the data but had no luck finding a solution. If I disable the jQuery function there is zero delay. Any help or suggestions would be appreciated.
So many questions to what you are trying to achieve
Why 200 select dropdowns?
Why did you use 'on click' on a select? you want 'on change' event right?
your code is slow because you are iterating twice over your 200 selects
here is the working code
<script>
$(document).ready(function(){
var lastSelectedValue = {};
$('select[name*=schoolselected]').on('change', function() {
var currentSelect = this.attributes.name.value;
var oldValue = lastSelectedValue[currentSelect];
lastSelectedValue[currentSelect] = this.value;
$('select[name*=schoolselected]').not(this).each(function() {
if(oldValue){
$(this).find("option[value='"+oldValue+"']").prop('disabled', false);
}
$(this).find("option[value='"+lastSelectedValue[currentSelect]+"']").prop('disabled', true);
});
});
});
</script>
I have 2 selectboxes
<h3>Results</h3>
<select id="register_form" name="sport" />
<option value="Rugby">Rugby</option>
<option value="Cricket">Cricket</option>
<option value="Football">Football</option>
</select>
<?php
echo'<select name="match">';
echo'<option value="'.$row['event_id'].'">'.$row['team1'].' VS '.$row['team2'].'</option>';
echo'</select>';
?>
<input id="register_form" type="submit" value="Display" name="submit" />
User searches for a result by:
selecting sport type in 1st selectbox and then in 2nd selectbox option values are populated based on sport type.
Is it possible to do this in PHP without the user having to first press submit to get the $_POST value of sport type?
What is my best option here?
PHP always need to reload the page to refresh your informations, so, as anant kumar singh said, you need to use AJAX for that. And as yak613 said, jQuery will help you to use AJAX easily
1.Ajax is the only option what you asked for that(without page refresh)
When you use php it's only possible with page refresh. but with ajax without page refresh it's possible.
helping links are:-
Use jQuery to change a second select list based on the first select list option
https://www.daniweb.com/web-development/php/threads/372228/php-and-ajax-auto-populate-select-box
https://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax
You can use this Multiple Select Dropdawn lists: http://coursesweb.net/ajax/multiple-select-dropdown-list-ajax_t , it can be used for multiple sets of Select lists.
I've faced with the same problem in my project. But the needed functionality was higher - not two dependent selectboxes and bigger number. I've written a simple function to load my selectboxes:
//formId - form where selectbox is
//name - attribute "name" of selectbox
//dataSourceUrl - url to PHP-file
//affectingField - string with value that filters the selecbox's data
function loadSelectbox( formId, name, dataSourceUrl, affectingField ){
//console.log('Loading data to selectbox name="'+name+'":');
var selectbox = $('#'+formId+' select[name="'+name+'"]');
if(selectbox){
//console.log("Selecbox found");
if(affectingField != null){
var affectingValue = $('#'+formId+' [name="'+affectingField+'"]').val();
dataSourceUrl += '?affectingValue='+affectingValue;
}
var options = selectbox.find('option');
var jqxhr = $.ajax({
url: dataSourceUrl,
dataType: 'text'
})
.done(function(data) {
//console.log(data);
if(data != ""){
var optionsObject = JSON.parse(data);
var i = 0;
console.log(optionsObject);
var options = [];
$(optionsObject).each(
function(){
options[i] = '<option value="'+$(this)[0]['val']+'">'+$(this)[0]['text']+'</option>';
i++;
}
);
selectbox.html(options);
if(urlParamsSet[name] == false){
setParamFromUrl(name);
}
}
else{
selectbox.html('<option value="">Все</option>');
}
})
.fail(function() {
alert("Problems with server answer");
})
selectbox.prop("disabled", false);
}
else{
console.log("No selectbox with such name");
}
}
Not saying that this code is perfect, but it works. PHP-file must return the values to selecbox in JSON format (convert from with structure: array(index, value, text) ).
I am having trouble with populating chosen plugin multiple get with data from an ajax call. I tired following the below posts,
Jquery Chosen plugin - dynamically populate list by Ajax
Multiple Select - Chosen jQuery
Jquery chosen ajax call populate multiselelect not working
But did not help. The data just doesn't get filled :( my ajax request is as follows,
<script type="text/javascript" lang="javascript">
function doGetTag() {
alert('here');
$.ajax({
url: 'index.php/rest/resource/qtag',
//data: data,
success: function(data) {
var jsonObj = JSON.parse(data);
var tags = "";
var curVal = document.getElementById('tags').innerHTML;
for(var i = 0; i < jsonObj.length; i++) {
var tagObj = jsonObj[i];
//document.write("<option>" + tagObj.tagName + "</option>");
var tagHtml = "<option>" + tagObj.tagName + "</option></br>";
tags = tags + tagHtml ;
}
tagTotal = curVal + tags;
document.getElementById('tags').innerHTML = tagTotal;
alert( document.getElementById('tags').innerHTML);
},
type: "get"
});
}
</script>
which returns a json string. the data gets properly displayed over here if I alert it out on a message box. But the issue is how to populate the multiple get plugin? following is my html,
<select data-placeholder="Tag your question here" style="width:350px;height:50px;" multiple class="chosen-select" id="tags">
<option value="" ></option>
</select>
I am very new to this plugin and would very much appreciate your help :)
FYI
I did it using direct php as follows,
<select data-placeholder="Tag your question here" style="width:350px;height:50px;" multiple class="chosen-select" id="tags">
<option value="" ></option>
<?php
$con=mysqli_connect("localhost","user","pass","db");
$result = mysqli_query($con,"SELECT * FROM tags");
while($row = mysqli_fetch_array($result))
{
echo"<option>".$row['tagName']."</option>";
echo"</br>";
}
?>
</select>
and it properly displays the data, but the project requirement states it is a MUST to use AJAX request to populate data. Thank you very much :) your expert advice is very much appreciated :)
Fist of all check your url: 'index.php/rest/resource/qtag',
This may work :
success: function(data) {
$("#tags").html(data).trigger('liszt:updated');
}
where data = (echo from sourse)
<option value=0> </option>
<option value=1> Option 1 </option>
<option value=2> Option 2 </option>
Hi guys i have a combobox with jquery - but i cant make the second one populated when the first select coming selected alredy. im try to get the value without change the select.
<form>
<select name="tipo" id="Tipo_Id" class="buscaTiposVeiculos">
<option value="1" selected="selected">teste1</option>
<option value="2">teste2</option>
<option value="3">teste3</option>
<option value="4">teste4</option>
</select>
<select name="marca" class="recebeMarcas">
<option value="">--- Select ---</option>
</select>
</form>
jquery
$('select.buscaTiposVeiculos').change(function () {
$("select.recebeMarcas").html('<option value="">Carregando...</option>');
// var opt = $("select.buscaTiposVeiculos"); tried like this
// var val = $(this).val(); tried like this
// var val = $(this).find('option:selected').val(); not works
$('select.recebeMarcas >option').remove();
$.post('/inc/geraCidades.php', {
tipov: $(this).val(),
tipo: "tipo"
}, function (data) {
$('select.recebeMarcas').html('<option value="">Selecione a Marca</option>' + data);
});
});
your selected value is
$("#Tipo_Id option:selected").val();
To trigger change event on page load and populate second select automatically. Some commented code can be removed
/* create the change handler use ID is better selector for efficiancy*/
$('#Tipo_Id').change(function() {
/* this populates second select with one option*/
$("select.recebeMarcas").html('<option value="">Carregando...</option>');
/* this removes option populated in line above*/
$('select.recebeMarcas >option').remove();
$.post('/inc/geraCidades.php', {tipov: $(this).val(), tipo : "tipo"}, function(data) {
$('select.recebeMarcas').html('<option value="">Selecione a Marca</option>'+data);
});
/* trigger the change event on page load*/
}).change();
I have created a real estate search function where in the user will input the price range. I have put two select fields to minimize user error, one for the minimum price and the other for maximum price. I want to utilize a dynamic form to further minimize entry error.
For example, the minimum price select has the following values:
$100k (default)
$200k
$300k
$400k
$500k
$600k
$700k
$800k
$900k
$1M
While the maximum price select has the same as above but without $100k and with additional $2M+, with a default value of $200k.
What I want to happen is to have a function that will not only validate the entry on-page but also dynamically change the select options for the maximum price. So when the user selects a minimum price, the maximum price field options will not display the selected minimum price and below.
So at the start, if the user selects $500k minimum, the maximum automatically changes to $600k while removing from the options anything below it.
What's the best approach for this?
Thanks in advance!
Update:
I followed Jake's answer and I can't make it work.
Here's the code of the form and script:
<form name="search" action="/search/" method="get">
<label>Price Range: </label>
Between:
<select name="min_price">
<option value="1">1M</option>
<option value="2">2M</option>
...
<option value="15">15M</option>
<option value="20">20M</option>
</select>
and
<select name="max_price">
<option value="2">2M</option>
<option value="3">3M</option>
...
<option value="30">30M+</option>
</select>
...
</form>
<script type="text/javascript">
$("#min_price").change(function(){
var min = $(this).val();
$("#max_price").find("option").each(function(){
if (this.value <= min) {
$(this).hide();
}
else {
$(this).show();
}
});
});
</script>
I'm using wordpress and it has jQuery 1.4.4. How can I make it work? Is there an error on my html code?
You can do this client side (in browser) using JavaScript. For example, with jQuery:
$("#min_price").change(function(){
var min = $(this).val();
$("#max_price").find("option").each(function(){
if (this.value <= min) {
$(this).hide();
}
else {
$(this).show();
}
});
});