I have a form with 2 dropdowns, 'Type' and 'Level', eg
Type
-----
Hotel
Restaurant
Casino
Level
-----
1
2
3
And a submit button which shows the price based on whichever options are selected in the dropdown. The price is calculated by some basic maths on the fly.
How can I do this using jquery?
Is it using onchange() or something?
$("#button_id_here").val("$your_amount_here");
If you want it to update automatically, bind it to the change event in the select/dropdowns
$("#select_id_here").change(function(){
//"basic maths"
$("#button_id_here").val("$your_amount_here");
});
You want more help, we would need to see code.
HTML:
<form>
<fieldset>
<p>
<label for="selectType">Type:</label>
<select id="selectType" name="type">
<option value="Hotel" data-cost="40">Hotel</option>
<option value="Restaurant" data-cost="80">Restaurant</option>
<option value="Casino" data-cost="35">Casino</option>
</select>
</p>
<p>
<label for="selectLevel">Level:</label>
<select id="selectLevel" name="level">
<option value="1" data-cost="0">1</option>
<option value="2" data-cost="15">2</option>
<option value="3" data-cost="30">3</option>
</select>
</p>
<p>
Total Cost: $<span id="cost">0</span>
</p>
<p><input type="submit" value="Go!"></p>
</fieldset>
</form>
jQuery:
$(function() {
$("#selectType, #selectLevel").change(function() {
var type = $("#selectType"),
level = $("#selectLevel"),
cost = $("#cost"),
typeCost = type.find(":selected").data('cost'),
levelCost = level.find(":selected").data('cost'),
total = typeCost + levelCost;
cost.html(total);
}).change(); // invoke the .change() trigger
});
See it in action here
You might want to also set something like "data-multiplier" for the level... whereas level 2 may have a 1.5x multiplier, and level 3 may have a 2x multiplier. You'd have to adjust the jQuery accordingly as well (total = typeCost * levelCostMultiplier, for example).
You can check if a select list has changed via jQuery's change() function.
Here's a way to do it:
HTML:
Type
<select name="type" id="type">
<option value="hotel" selected>Hotel</option>
<option value="restaurant">Restaurant</option>
<option value="casino">Casino</option>
</select>Level
<select name="level" id="level">
<option value="1" selected>1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<div id="result"></div>
jQuery:
var result = 1;
$("#type").change(function () {
var val = $(this).val();
$("#result").html("Type is " + val + ", level is " + $("#level").val());
});
$("#level").change(function () {
var val = $(this).val();
// Some basic math
result = parseInt(val) * 5;
$("#result").html("Type is " + $("#type").val() + ", level is " + val + ", result: " + result);
});
And the relevant jsfiddle:
http://jsfiddle.net/y2s4v/1/
Related
This code is displaying the dropdown value in textbox on selection. But i want to display my own values in textbox instead of those default values(Default values of dropdown). how could i do that thing . I have a text box with id "#amount".
This is HTML code:
<select id="d-name" class="form-control" name="menu">
<option value="Left Chest">Left Chest</option>
<option value="Simple back">Simple back</option>
<option value="Complex back">Complex back</option>
</select>
<input type="text" id="amount" />
This is javascript code:
jQuery('#d-name').change(function(e){
var selectedValue = jQuery(this).val();
jQuery("#amount").val(selectedValue);
});
You can use some conditions -
var selectedValue = jQuery(this).val();
var amount = '$0';
if(selectedValue == 'Left Chest')
amount = '$20';
else if (selectedValue == 'Simple back')
amount = '$30';
...
jQuery("#amount").val(amount);
You can also use switch cases.
You can also change the amount by using switch case:
jQuery('#d-name').change(function(e){
var selectedValue = jQuery(this).val();
switch(selectedValue) {
case "Left Chest":
amount = "$20"; // amount which u need
break;
case "Simple back":
amount = "Simple back"; // or amount if u need
break;
case "Complex back":
amount = "Complex back"; // or amount if u need
break;
default:
amount = "";
}
jQuery("#amount").val(amount);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<select id="d-name" class="form-control" name="menu">
<option value="Left Chest">Left Chest</option>
<option value="Simple back">Simple back</option>
<option value="Complex back">Complex back</option>
</select>
<input type="text" id="amount" />
Try this.
<select id="d-name" class="form-control" name="menu">
<option value="$20">Left Chest</option>
<option value="Simple back">Simple back</option>
<option value="Complex back">Complex back</option>
</select>
https://jsfiddle.net/x6f3k165/1/
Try,
<select id="d-name" class="form-control" name="menu">
<option>Please select...</option>
<option value="$20">Left Chest</option>
<option value="Simple back">Simple back</option>
<option value="Complex back">Complex back</option>
</select>
<input type="text" id="amount" />
<script type="text/javascript">
$('#d-name').change(function(e){
var selectedValue = $(this).val();
$("#amount").val(selectedValue);
});
</script>
I'm using .append() to create new lines inside a form composed by select boxes that are updated based on the value of the first one.
The purpose is to create as many lines (groups of select boxes) as needed and by changing the value of the first select box they update the others in the line.
I managed to do this with the following code:
HTML:
<div class="input_fields_wrap">
<table>
<tr>
<td class="span1">Select_1: </td>
<td class="span1">Select_2: </td>
<td class="span1">Select_3: </td>
<td class="span1">Select_4: </td>
</tr>
<tr>
<td>
<select class="span2" id='Select_1' name='Select_1[]'>
<option value="0">Seleccione...</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</td>
<td>
<select class="span2" id='Select_2' name='Select_2[]'>
<option value="0">Seleccione...</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</td>
<td>
<select class="span2" id='Select_3' name='Select_3[]'>
<option value="0">Seleccione...</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</td>
<td>
<select class="span2" id='Select_4' name='Select_4[]'>
<option value="0">Seleccione...</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</td>
</tr>
</table>
</div>
JQUERY:
<script type="text/javascript">
$('#Select_1').change(function(){
$('#Select_2').load("file.php?ID1=" + $(this).val());
$('#Select_3').load("file.php?ID2=" + $(this).val());
$('#Select_4').load("file.php?ID3=" + $(this).val());
});
var max_fields = 20;
var x = 1;
var wrapper = $(".input_fields_wrap");
var add_button = $(".add_field_button");
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
var html = '<div class="input_fields_wrap">';
html = html + '<select class="span2" id="Select_1" name="Select_1[]"><option value="0">Seleccione...</option><?php foreach($var1 as $row1){echo '<option value="'.$row1['ID'].'">'.$row1['Name'].'</option>';}?></select>';
html = html + '<select class="span2" id="Select_2" name="Select_2[]"><option value="0">Seleccione...</option><?php foreach($var2 as $row2){echo '<option value="'.$row2['ID'].'">'.$row2['Name'].'</option>';}?></select>';
html = html + '<select class="span2" id="Select_3" name="Select_3[]"><option value="0">Seleccione...</option><?php foreach($var3 as $row3){echo '<option value="'.$row3['ID'].'">'.$row3['Name'].'</option>';}?></select>';
html = html + '<select class="span2" id="Select_4" name="Select_4[]"><option value="0">Seleccione...</option><?php foreach($var4 as $row4){echo '<option value="'.$row4['ID'].'">'.$row4['Name'].'</option>';}?></select>';
html = html + '<button onclick="#" class="remove_field">Remove</button></div>';
$(wrapper).append(html);
}
});
$(wrapper).on("click",".remove_field", function(e){
e.preventDefault();
$(this).parent('div').remove();
x--;
});
</script>
This all works ok for the first line.
All the others that are created by the .append() in Jquery aren´t updated when the select box "Select_1" value is changed.
I need that all the lines created by append have the funcionality to update the 3 select boxes by change the first select box value.
I'm using JQuery 2.1.4
Thanks in advance.
Just found the problem.
It was a noob question after all.
Just have to:
Call the autocomplete function again to resolve the combobox problem;
Rename the comboboxes in the append code with a autoincrement number to contemplate each line;
Run the update comboboxes code after the append with the new comboboxes name;
Here's the code to put right after the append command:
$(wrapper).append(html);
$("#Select"+x).combobox({
select: function (event, ui){
$('#Select'+x).load("file.php?ID1=" + $(this).val());
$('#Select'+x).load("file.php?ID2=" + $(this).val());
$('#Select'+x).load("file.php?ID3=" + $(this).val());
}
});
The solution was found with some help found here: jQuery append elements not working with autocomplete
Thanks for all!
Does anyone know how to allow this character countdown to be controlled by pre-determined variables that are linked to the select field options?
var large = 300
var medium = 200
var small = 100
I appreciate any input greatly.
Example Code:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function updateCountdown() {
var remaining = 50 - jQuery('#post').val().length;
jQuery('#character_limit').text(remaining + ' characters remaining.');
}
jQuery(document).ready(function($) {
updateCountdown();
$('#post').change(updateCountdown);
$('#post').keyup(updateCountdown);
});
</script>
<textarea id="post" cols="40" rows="3" maxlength="500"></textarea>
<div id="character_limit"></div>
<select name="product" id="product">
<option value="large">Large Product</option>
<option value="medium">Medium Product</option>
<option value="small">Small Product</option>
</select>
You can achieve this by firstly changing the options of the select element to have a value equal to the length required by that type of product:
<select name="product" id="product">
<option value="300">Large Product</option>
<option value="200">Medium Product</option>
<option value="100">Small Product</option>
</select>
From there you can retrieve the selected value (converting it to a number) before subtracting the number of used characters. Also note that you would also now need to update the count on the change event of the #product field. Try this:
function updateCountdown() {
var charLimit = parseInt($product.val(), 10)
var remaining = charLimit - jQuery('#post').val().length;
jQuery('#character_limit').text(remaining + ' characters remaining.');
}
var $product = $('#product');
updateCountdown();
$('#post, #product').change(updateCountdown);
$('#post').keyup(updateCountdown);
Example fiddle
I've got an HTML form that has some static fields and some fields that are dynamically added with javascript. It looks sort of like this
<html>
<script type="text/javascript">
window.onload = function()
{
var select = document.getElementById("select");
var texts = document.getElementById("texts");
select.onchange = function()
{
var val = select.options[select.selectedIndex].value;
texts.innerHTML = "";
for(i=0; i < val; i++)
{
//texts.innerHTML += '<div><input type="text" name="t_' + i + '" value="select_' + i + '" /></div>';
texts.innerHTML += i + '<div><input type="text" name="t_' + i + '" /></div>';
}
}
}
</script>
<body>
<form method="POST" action="connection.php">
Question:<br>
<textarea name="question" cols="35" rows="5"></textarea><br>
<select id="select" size="1">
<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>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>
<div id="texts"></div>
<input type="submit" name="Submit" value="Submit" >
</form>
</body>
</html>
when the user clicks it adds a text box field. How does the data stored into the database.Kindly suggest me an idea what are the resources used to do this .Thanks in advance
Good day Shashak
In order to submit the data of your form into the database, regardless of the javascript of the form the data should be passed using in your case the POST method to a script 'connection.php' in your case.
This script should contain a way to connect to your database followed by the logic that will validate your data and then at the end if the validation is successful a database query that will INSERT the data into your database.
Which is your level of understanding when it comes to PHP or any other server-side scripting language and databases? - I will be able to give you more information if I know what you know.
I think instead of giving the textbox the name format t_1 , t_2 you can give it as an array like below
<html>
<script type="text/javascript">
window.onload = function()
{
var select = document.getElementById("select");
var texts = document.getElementById("texts");
select.onchange = function()
{
var val = select.options[select.selectedIndex].value;
texts.innerHTML = "";
for(i=0; i < val; i++)
{
//texts.innerHTML += '<div><input type="text" name="t_' + i + '" value="select_' + i + '" /></div>';
texts.innerHTML += i + '<div><input type="text" name="txt_name[]" /></div>';
}
}
}
</script>
<body>
<form method="POST" action="connection.php">
Question:<br>
<textarea name="question" cols="35" rows="5"></textarea><br>
<select id="select" size="1">
<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>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>
<div id="texts"></div>
<input type="submit" name="Submit" value="Submit" >
</form>
</body>
</html>
PHP
It will post data like this:
Suppose you select option 2.
$inputs = $_REQUEST['t']; // change the name like this name[]
$textarea = $_REQUEST['textarea'];
$selectbox = $_REQUEST['select']; // you should define the name of the select box as i used 'select'
insert into mysql
$conn = mysql_connect('localhost', 'db user', 'db password');
mysql_select_db('database name');
for($i=0; i<count($inputs); $i++) {
$sql = "insert into <table name> (textarea, inputs) values ($inputs[$i], $textarea)";
mysql_query($sql);
}
it will store each row as per your selection of input text boxes.
Note: Modify the query as per your requirement.
I have a dropdown list populated by mysql working perfectly, I also have it displaying the price set by mysql, so far i'm happy.
What the issue is as it's a multiple dropdown list, it will only display what is chosen first, if I pick 2 or more selections, only the first price is shown.
My second issue is I want the prices to add up i.e. 1st Selection's price is £1.99, 2nd Selection's price is £2.99 so the total should be £4.98
Finally once i have all this working, I want to continue this onto the 2nd / 3rd / 4th dropdown boxes so that all the boxes add up giving me a combined total.
Here's my html code to show you what i'm using:
<form method="post" action="" name="form1">
<?
include 'classes.php';
$query="SELECT * FROM Sex_Table";
$result=mysql_query($query);
?>
<select data-placeholder="Your Favorite Football Team" class="chzn-select" multiple tabindex="6" id="Sexdiv" name="Sexdiv" style="width: 300px;" onChange="getClothing(this.value),changePrice()">
<option>Select Colour Type</option>
<? while($row=mysql_fetch_array($result)) { ?>
<option value=<?=$row['ID']?> sex_price="<?=$row['Price']?>"><?=$row['Sex_Name']?> (£<?=$row['Price']?>)</option>
<? } ?>
</select><br /><br />
<p id="Clothingdiv">
<select style="width: 300px;" name="Clothing" disabled='disabled'>
<option>Select Sex First</option>
</select>
</p><br />
<script type="text/javascript"> $(".chzn-select").chosen(); $(".chzn-select-deselect").chosen({allow_single_deselect:true}); </script>
</form>
and here's my js:
function changePrice() {
var sex_price = $("option:selected").attr("sex_price");
$("#price_div").html("Price = £" + sex_price);
}
Thanks
Below is an example of what you're trying to do, I've given each select element I want to calculate the total for a class so that they are not mixed up with other elements.
jQuery
<script>
$(document).ready(function() {
$('.calculate').change(function() {
var total = 0;
$('.calculate').each(function() {
if($(this).val() != 0) {
total += parseFloat($(this).val());
}
});
$('#total').text('£' + total.toFixed(2));
});
});
</script>
HTML
<select class="calculate" name="select-1">
<option value="0">Please Select</option>
<option value="1.99">£1.99</option>
<option value="2.99">£2.99</option>
</select>
<select class="calculate" name="select-2">
<option value="0">Please Select</option>
<option value="1.99">£1.99</option>
<option value="2.99">£2.99</option>
</select>
<select class="calculate" name="select-3">
<option value="0">Please Select</option>
<option value="1.99">£1.99</option>
<option value="2.99">£2.99</option>
</select>
<span id="total">£0</span>
This will update the contents of total with the total price of each select element with class calculate when one of them is changed.
select with multiple should have the size attribute set as well, like this:
<select data-placeholder="Your Favorite Football Team" class="chzn-select" multiple="multiple" tabindex="6" id="Sexdiv" name="Sexdiv" style="width: 300px;" onChange="getClothing(this.value),changePrice()" size="10">
Your jQuery script:
$('select#Sexdiv').change(function() {
var value = 0;
$("select#Sexdiv option:selected").each(function(){
value += parseFloat($(this).val());
});
$("#price_div").html("Price = £" + value);
});
Hmm?