I have been looking for this all day - Change currencies throughout the page when choosing between countries or currencies from dropdown menu.
What I basically need is a dropdown menu which shows countries or currencies. When you select anyone of it like USD all the prices throughout the page are changed to USD. Now if you change it AUD/CAD/PKR etc they will be changed accordingly. I basically need it in Javascript but if anyone can provide it in PHP, it would be okay too.
A very good example of this is: http://creativeon.com When you change currency from right top dropdown menu - it changes the currencies of all the packages in the main content.
I am a HTML developer and do not know much about javascript. Please help me.
P.S. I have searched codingforums.com too and found only two links which are not of my use because they are currency converter:
http://www.codingforums.com/showthread.php?t=196577
http://www.codingforums.com/showthread.php?t=196373
The beauty of webapps is that you can borrow good ideas by looking a the source code (using a toll like the Firebug plugin in FF). As you can see in the example you mention the page is reloaded when a different currency is chosen:
$('#Items, #Items_input').change(function(){
$.post('/conlogic/ajax.php?action=currency',
{'curr': $(this).val()},
function(data){
if ( data=="OK" ) window.location.reload();
});
});
Apparently in this case the page is re-rendered server side with the different currency.
I write a javascript version. no Ajax, currency change rates was borrowed from google.
HTML Code
<select id="currencySelector">
<option value="usd">USD</option>
<option value="aud">AUD</option>
<option value="eur">EUR</option>
<option value="gbp">GBP</option>
</select>
<div class="currency" data-currencyName="usd">15<span>USD</span></div>
<div class="currency" data-currencyName="eur">15<span>EUR</span></div>
<div class="currency" data-currencyName="gbp">15<span>BGP</span></div>
<div class="currency" data-currencyName="aud">15<span>AUD</span></div>
Javascript Code
var
selector = document.getElementById("currencySelector");
var
currencyElements = document.getElementsByClassName("currency");
var
usdChangeRate = {
AUD: 1.0490, // 1AUD = 1.0490 USD
EUR: 1.4407, // 1EUR = 1.4407 USD
GBP: 1.6424,
USD: 1.0
};
selector.onchange = function () {
var
toCurrency = selector.value.toUpperCase();
for (var i=0,l=currencyElements.length; i<l; ++i) {
var
el = currencyElements[i];
var
fromCurrency = el.getAttribute("data-currencyName").toUpperCase();
if (fromCurrency in usdChangeRate) {
var
// currency change to usd
fromCurrencyToUsdAmount = parseFloat(el.innerHTML) * usdChangeRate[fromCurrency];
var
// change to currency unit selected
toCurrenyAmount = fromCurrencyToUsdAmount / usdChangeRate[toCurrency];
el.innerHTML = toCurrenyAmount + "<span>" + toCurrency.toUpperCase() + "</span>";
el.setAttribute("data-currencyName",toCurrency);
}
}
};
Run the code
You can run the code above at http://jsbin.com/ewuyoq/5 or build your own version http://jsbin.com/ewuyoq/5/edit
I would use jQuery, so feel free to disregard my answer if you don't want to use an external library. It can be found on www.jquery.com.
First, you make a span for all places where currency should be changed, give it class "currency" and in the name attribute, you put the value in your "base currency". Example:
<span class="currency" name="499"> 499 </span>
Then you can make a button, say it has id "showInEuro".
<input type="button" id="showInEuro" />
Then write some jQuery code similar to this:
var usdToEuroExchRate = 1.5; // Obviously just a magic constant
// When the button is clicked
$("#showInEuro").click(function() {
// Iterate through all of the currency spans
$("span.currency").each(function(index) {
// And take their names times the exchangerate and put it in the span.
$(this).text($(this).attr("name") * usdToEuroExchRate);
});
});
Of course, you should try to use real, live exchange rates.
I made a JSFiddle for you: http://jsfiddle.net/An3v9/9/
Related
I would like implement on my own website this kind of search box - http://www.chippmunk.com/.
(under Savings Start Here)
How this works with a sliding horizontal input & 2 other inputs, one of which having a dropdown effect? i would like to know how all these things are combined to search.
Do you know some tutorials for this or could you help me to build?
Thank you so much in advance.
Based on Vlad Preda's comment, I got a code and edited it slightly to create a slider function which gives me a variable ( say range 23 to 109), which answers part of my question.
<div>
<input id="cost" name="cost" type="range" min=23 max=109 value=93 style="width: 40%;">
<output for="cost">1</output>
</div>
Now I would require to use this as an input, along with another input (an string. e.g. a store name)
How would I manage to combine these two elements to give me a proper search results?
JavaScript code -
$(function() {
var el, newPoint, newPlace, offset;
$("input[type='range']").change(function() {
el = $(this);
width = el.width();
newPoint = (el.val() - el.attr("min")) / (el.attr("max") - el.attr("min"));
offset = -1.3;
if (newPoint < 0) { newPlace = 0; }
else if (newPoint > 1) { newPlace = width; }
else { newPlace = width * newPoint + offset; offset -= newPoint;}
el
.next("output")
.text(el.val());
})
.trigger('change');
});
I guess there is a variable e1.val() which has got the updated value, I would need to combine this with another input and pass both parameters to the search variable.
I'm looking to create a pretty simple calculator, but I need it to update on each keystroke. I cannot seem to find anything in that specific category. Can anyone point me to the right direction?
I'm looking for something like A*1.325 + B*3.76 where B is a drop down menu and A is the text field that people will be filling out. Every time the drop down is changed or a keystroke is registered in the text box.
I will also try to do some RegEx to only allow numbers or decimal points!
Thank you guys very much!!!
PS. Will be using PHP/HTML to create the form.
Step 1:
Do the jQuery tutorials. fun fun fun :D :D :D
http://docs.jquery.com/Tutorials
Step 2:
Now that you understand jQuery, notice that jQuery supports a bunch of event handlers. For instance, you can assign a click event to something that resembles an item in a dropdown menu:
$("itemInMyDropDownMenu").click(function(e) {
doSomeCalculation(parseFloat(this.val()));
}
Step 3:
Chose the right event handlers to use. click (for the dropdown menu) and keyup (for the text field) sound hopeful.
Step 4:
Keep tinkering. You don't need PHP at all.
The first question. If you need just simple calculator, why would you need AJAX? AJAX can send requests to web pages and scripts and get the XML, JSON, html or simple text responses.
If you still need AJAX, read http://www.w3schools.com/ajax/default.asp
Realtime updates:
Set the id of elements you are going to work with.
Create the appropriate handler, which is called any time the field is changed.
<input type="text" id="field" value="" onChange="javascript: setA(this)"/>
function setA(obj){
var a = 0 ;
if (obj.value)
a = obj.value ;
//call any function to calculate anything and send a.
}
If you want to display something, here id comes to be handy.
<div id="result"></div>
document.getElementById("result").innerHTML = 345 ; //just set to what you need
You can fully utilize javascript for building simple calculator without submitting the form, as it can work in real time.
Hope it helps :)
While I waiting to hear back I did a little more research and found some code that I think will work for what I was looking for. I was overthinking the whole thing!!
<html>
<head>
</head>
<body>
<script>
function doMath() {
var totalparts = parseInt(document.getElementById('parts_input').value);
var labor = parseInt(document.getElementById('labor_input').value);
var misc = parseInt(document.getElementById('misc_input').value);
var subtotal = totalparts + labor + misc;
var tax = subtotal * .13;
var total = subtotal + tax;
document.getElementById('subtotal_input').value = subtotal;
document.getElementById('tax_input').value = tax;
document.getElementById('total_input').value = total;
}
</script>
<div>Total Parts: <input type="text" id="parts_input" value="1" readonly="true" /></div>
<div>Labor: <input type="text" id="labor_input" onBlur="doMath();" /></div>
<div>Misc: <input type="text" id="misc_input" onBlur="doMath();" /></div>
<div>Sub Total: <input type="text" id="subtotal_input" readonly="true" /></div>
<div>Tax: <input type="text" id="tax_input" readonly="true" /></div>
<div>Total: <input type="text" id="total_input" readonly="true" /></div>
</body>
</html>
You don't need to use, and shouldn't use, AJAX for this. Instead, you should do something like this:
$("#textfieldID, #dropDownMenuID").change(function() {
var aVal = $("#textFieldID").val() == "" ? 0 : parseFloat($("#textFieldID").val());
var bVal = $("#dropDownMenuID").val() == "" ? 0 : parseFloat($("#dropDownMenuID").val());
$("#answerID").text((aVal*1.325 + bVal*3.76).toString());
});
Have you tried onchange="calculator()"?
I have a list of widths in a dropdown box. They are dynamic because each product has different widths so I've setup the code to look for the minimum and maximum. Then it sets up a dropdown list in increments of 1".
Next to the width are 1/8" increments. So for example you could pick 52 1/8.
If the maximum width is 92 inches let's say, the 1/8 increment dropdown box should disappear or disable because since 92 is max.. you can't pick 92 1/8.
How do I make that 1/8ths box disappear or disable? Here is part of my current code for the dropdown box.
<select name="width_str" id="width_str" onchange="doCalc();" style="width:50px;">
<option value="">--</option>
<?php
$counter = $minwidthRS - 1;
$start = $minwidthRS;
for($start; $start < $maxwidthRS + 1; $start++) {
$counter = $counter + 1;
echo "<option value=".$counter.">".$counter."</option>";
}
?>
</select>
Code for the select dropdown box with 1/8ths that I would like to disable or disappear when MAXIMUM above is selected.
<select name="widthfrac_str" id="widthfrac_str" onchange="doCalc();" style="width:50px;">
<option value="">--</option>
<option value="1/8">1/8</option>
<option value="1/4">1/4</option>
<option value="3/8">3/8</option>
<option value="1/2">1/2</option>
<option value="5/8">5/8</option>
<option value="3/4">3/4</option>
<option value="7/8">7/8</option>
</select>
I'm aware of how to send a selected width value over to a PHP page using AJAX and compare it there, but what do I send back in the success callback? Could I send something that tells the container of that 1/8 measurement dropdown to disable or disappear?
Many thanks! If you need more code let me know. The doCalc() script basically uses AJAX and sends the width to php processing page in order to update price instantly.
EDIT (added more code):
Here is part of my script..
<script type="text/javascript">
function doCalc(){
var roomX = $('#room_str').val();
... lots of variables set here
$.post('db_query.php',
{roomX:roomX, etc. etc. etc.},
function(data) {
data = $.parseJSON(data);
$('#roomname-placeholder').html(data.roomname);
// ... lots of placeholders and code here
});
return false;
};
</script>
Not sure if it helps but I learned a little about using a callback to alter an input field and replacing its value with this: $('input[name=x_login]').val(data.loginid);
It would be great if there was code like that to simply change the other dropdown box disabled=disabled? Does that make sense? I'm still learning programming lingo!
You can call another function with onchange(), which should check the number chosen for the first value. If it is the maximum, then toggle function to hide the second element. A neater solution would be to include the 'check for maximum value and toggle if true' inside doCalc.
Remember to make PHP check also the value, since if user chooses the second value AND then the maximum for the first block, it should hide the second one, but it's value might still be sent.
EDIT:
<script type="text/javascript">
function doCalc(){
var roomX = $('#room_str').val();
if (roomX == <?php echo $maxwidthRS; ?>)
{
document.getElementById('widthfrac_str').style.display = 'none';
// You also need to make the second element's value 0 within those brackets
}
... lots of variables set here
$.post('db_query.php',
{roomX:roomX, etc. etc. etc.},
function(data) {
data = $.parseJSON(data);
$('#roomname-placeholder').html(data.roomname);
// ... lots of placeholders and code here
});
return false;
};
</script>
There's no problem putting php within javascript if it's in a .php file. It worked as the OP stated in the comments, great!
I'm implementing a system these days, i want to implement a combo box selection process but i don't know how to implement it, so asking you guys favor?
my scenario is this, let's say we have two combo box selection lists, left one and right one, left one is the main one and the right one is the child of the left one.
when i select a item from the left combo box the right combo box's content should be changed according to the selection of the left one,
Ex: let's think about mobile phones, if i select the brand
Nokia
from the left combo box right combo box's content should be changed to
C6-01
E7-00
5232
X3-02
C1-01
C7-00
5228
C5-03
5250
6120ci
E5-00
E73
like wise. please help me to implement a this kind of scenario!
any tutorial links, sample codes to understand the scenario is better!
regards,
Rangana
The trick is do subscribe to the change event and reset the contents of the second box accordingly.
HTML:
<select id="brand">
<option value="">- select -</option>
<option value="nokia">Nokia</option>
<option value="apple">Apple</option>
</select>
<select id="type"></select>
JavaScript (on ready):
var selectBrand = $("#brand");
var selectType = $("#type");
var optionsList = {
nokia: [
"C6-01",
"E7-00"
],
apple: [
"iPhone 3",
"iPhone 3G",
"iPhone 4"
]
};
selectBrand.change(function() {
var brand = selectBrand.val();
var options = optionsList[brand];
var html;
if (options) {
html = '<option value="">- select -</option>';
$.each(options, function(index, value) {
html += '<option value="' + value + '">' + value + '</option>';
});
} else {
html = '<option value="">Select a brand</option>';
}
selectType.html(html);
}).change();
Full example at See http://www.jsfiddle.net/TJJ8f/
This works by having two things. Firstly, a server that will return JSON for the category you need and, secondly, the code for the front end.
<?php
// Do what you need to
$modelsArray = getModelsForBrand($_REQUEST['brand']);
echo json_encode($modelsArray);
?>
This uses the json_encode function to get the JSON on the array returned by whatever you use to get the models. I haven't used this function myself but it looks pretty simple.
Then your jQuery would look like this:
$("#brandCombo").change(function(){
var chosenBrand = $(this).val(); // Get the value
$.getJSON('/your-php-file.php', { "brand" : chosenBrand }, function(request){
// Successful return from your PHP file
$("#modelCombo").empty();
// For each item returned, add it to your models combo box
$.each(request, function(i,item){
$("#modelCombo").append("<option value='" + item.value + "'>"+ item.name + "</option>");
});
});
});
In this example, brandCombo is the ID of the list with the brands and modelCombo is the ID of the list the models should appear. When the value of brandCombo is changed, it makes the request to your PHP file to get the array of models in JSON. Then it goes through each one and adds a new option to your modelCombo list.
A similar question I answered is here, where I mentioned how to do it with all the data already on the page and in listboxes (hiding/showing them) or by AJAX requests (as the example above).
The other option, as shown in dyve's answer is to have all the information you need on the page already, in the form of a JavaScript object. If you wanted to do this, then then PHP json_encode function could still be of use (although you just call it once with all your data and plop it onto the page).
A number of previous SO posts cover this topic, have a look at this for example: Using javascript and jquery, to populate related select boxes with array structure
I need a way of having multiple selections but only one visible at a time.
When the user wants to add another selection he/she clicks a button,checkbox,radio..whatever
They need to be able to add an unlimited number of selections. Any Ideas?
Old question, but might as well add my 2 cents, in case anyone else wants to know an answer.
I would use JavaScript to create a <select> element in a "more" section, from a JavaScript loop. For example, your first page would have
<input type="button" value="New Select Box" onclick="createNewBox();" /><br />
<span id="selectElement1">
<select>[your code for the select box goes here]</select>
<span id="selectElement2"></span>
</span>
Which could setup your basic select element, and the New Select Box would activate this JavaScript function code:
<script type="text/javascript">
// Initialization Code
var currentSelect = 1; // Keeps track of which select box is current
// New Select Box code
function createNewBox()
{
var currentSelect = currentSelect + 1;
var nextSelect = currentSelect + 1;
document.getElementById('selectElement'+currentSelect).innerHTML = "<select>[code goes here]</select><span id=\"selectElement"+nextSelect+"\"></span>";
}
</script>
This whole thing can run with only those two code snippets, and no jQuery code is needed.