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()"?
Related
I found this example:
The Idea is to get the checked checkbox value, and use it further as avariable:
Maybe this example is not the best, but I only found this one as it is much closer to what I want.
See FIDDLE
<div id="pakker">
<input type="checkbox" checked="checked" value="39" />test 1<br/>
<input type="checkbox" value="79" />test 2<br/>
<input type="checkbox" value="29" />test 3<br/>
<input type="checkbox" value="49" />test 4<br/>
<script type="text/javascript">
jQuery(document).ready(function($) {
var sum = 0;
$('#pakker :checkbox').click(function() {
sum = 0;
$('#pakker :checkbox:checked').each(function(idx, elm) {
sum += parseInt(elm.value, 10);
});
$('#sum').html(sum);
});
});
</script>
As you can see it shows values only after mouse click checkbox. How can I make it to get the checked checkbox value on Loading page? Example: http://jsfiddle.net/vaKWs/31/
if more then one checkbox is selected it ADDS the numbers. is it possible to show the valuse like (93, 25, 256 etc) without adding them?
Is it possible the result to put into a VARIABLE so that i can use this variable in other functions on the page? For example if $variable { then } esle {...
* PS * I am new with php and js. Thank you for understanding!
jQuery(document).ready(function($) {
var sum = 0;
$('#pakker :checkbox').click(function() {
sum = 0;
$('#pakker :checkbox:checked').each(function(idx, elm) {
sum += parseInt(elm.value, 10);
});
$('#sum').html(sum);
});
$('#pakker :checkbox[checked]').each(function(idx, elm){
sum += parseInt(elm.value, 10);
});
$('#sum').html(sum);
});
in HTML:
<input type="checkbox" checked value="39" />test 1<br/>
http://jsfiddle.net/vaKWs/6/
There you go.
Please rate my answer.
that would really help me!!
already answered
You use a sum of the values, if you want them as separate text: sum += parseInt(elm.value, 10) + " " should do it. This forces a space between keeping them as a text string.
The example you have saves them into a variable already. Check out arrays for storing them into individual variables
Hope that helps
Actually #Jose makes a lot of sense to me.
i felt exactly like you before. but with of a lot of learning i manage to create nice sites.
let me help you on 3:
if you assign a varible at the top of the page like that HTML:
<script>
myNewVar = new Array();
//... rest of the script
</script>
so that variable is available to all scripts around..
I have a function that listens for onkeyup event, that onkeyup checks to see if a box has a value and if not blank is supposed pull the value of an elementID which is a phone number called from another page. It takes that value and inserts it in to a snippet of html that gets sent to another elementID. the folowing code is the function and the associated code.
<script language="javascript">
function monthlycheck() {
var mnthchk = document.getElementById("mdamountBox");
var cancelPhone = document.getElementById("cancelphoneLabel");
document.getElementById("cancelphonelistLabel").value = cancelPhone; <--gives the is null error
if(mnthchk.value!=""){
var newHTML = "<span style='color:#24D330'> Your Monthly pledge in the amount of $__ is valid and will be deducted this time every month<br> untill you notify us of its cancellation by calling <label id='cancelphonelistLabel'> </label>";
" </span>";
document.getElementById("mnthlychkdiscoLabel").innerHTML = newHTML;
}
}
</script>
<label id="mnthlychkdiscoLabel"> </label> <---this is where the final data is to be displayed
<label id="cancelphoneLabel">1-800-555-1111</label> <--- this is the phone number pulled from another page,
all the data is pulled together in a single page when loaded but is written in separate page using smarty templates. I keep getting the entitled error and have tried a number of different things to fix it but im stumped any help is greatly appreciated.
here is a jfiddle http://jsfiddle.net/rn5HH/
I think you are trying to access that id before it's created.
Also .value is only for inputs. It looks like you are creating a label, so you'd use innerHTML instead.
Something like this:
<script language="javascript">
function monthlycheck() {
var mnthchk = document.getElementById("mdamountBox");
var cancelPhone = document.getElementById("cancelphoneLabel");
if(mnthchk.value!=""){
var newHTML = "<span style='color:#24D330'> Your Monthly pledge in the amount of $__ is valid and will be deducted this time every month<br> untill you notify us of its cancellation by calling <label id='cancelphonelistLabel'> </label></span>";
document.getElementById("mnthlychkdiscoLabel").innerHTML = newHTML;
document.getElementById("cancelphonelistLabel").innerHTML = cancelPhone; //<--gives the is null error
}
}
</script>
<label id="mnthlychkdiscoLabel"> </label> <---this is where the final data is to be displayed
<label id="cancelphoneLabel">1-800-555-1111</label> <--- this is the phone number pulled from another page,
I'm not 100% what you are trying to do, so i just tried to make it work. There are many things you could probably simplify in this. It would help if you could create a jsfiddle to show it more clearly.
Edit:
Fixed the fiddle so it works and shows the phone number:
updated fiddle
Is that what it's supposed to do?
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/
I've referred to this post:
Post array of multiple checkbox values
And this jQuery forum post:
http://forum.jquery.com/topic/checkbox-names-aggregate-as-array-in-a-hidden-input-value
I am trying to collect an array (or concatenated string with commas, whatever) of checkbox values in a hidden input field using jQuery. Here's the script code I'm using:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
$(form).find("input[name=specialty]").val(function() {
return $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
});
});
</script>
A snippet of the relevant HTML:
<form id="advancedSearchForm" name="advancedSearchForm" method="post" action="<?php echo site_url('/magcm/advancedSearch#results'); ?>">
<input type="checkbox" name="FCM" id="FCM" class="chk" value="FCM" <?php echo set_checkbox('FCM', 'FCM'); ?>/>
<input type="hidden" name="specialty" id="specialty" value="" />
<input class="button" name="submit3" id="submit3" type="submit" value="Search" />
I've tried changing "submit" to "submit3" in the jQuery, which breaks (obviously). When I print_r($_POST), the checkboxes POST correctly but the condensed hidden variable does not. (It posts, but a blank value.) The checkboxes persist correctly using CI's hacked set_value() function (Derek needs to implement this in the main trunk... but that's another story)
I'm sure I'm doing something that is wrong and easy to point out. I've just been banging my head against the wall for the past 2 hours on it, trying various functions and changing a ton of things and analyzing it in Chrome dev tools (which don't show any errors).
Help is appreciated. :)
Let's say you applied an class, maybe "tehAwesomeCheckboxen" to every checkbox. Then
<script>
$("#advancedSearchForm").submit(function() {
var chkbxValues = $(".tehAwesomeCheckboxen").val();
$("#specialty").val( chkbxValues.join(",") );
});
</script>
EDIT:
I don't think the $_POST array is getting populated, since the submit is being handled locally by the JavaScript engine. SO... let's try this:
<script>
var chkbxValues = new Array();
$(".tehAwesomeCheckboxen").live("change", function(e){
var val = $(this).val();
if( $(this).is(":checked") ) {
if( chkbxValues.length == 0 || chkbxValues.indexOf(val) == -1){
// Add the value
chkbxValues.push(val);
}
}
else {
// remove the value
chkbxValues.splice( chkbxValues.indexOf(val), 1 );
}
$("#specialty").val( chkbxValues.join(",") );
});
</script>
This adds an event handler the checkboxes themselves, such that checking/unchecking the box alters the hidden element. Then your form handles its submission as normal.
Is this more in line with what you're trying to do?
P.S. Those who upvoted this, please note I have modified my answer. Please verify whether you still find it useful and adjust your vote accordingly.
I ended up solving it using PHP arrays rather than jQuery:
<input type="checkbox" name="chk[]" id="RET" class="chk" value="RET" <?php echo set_checkbox('chk', 'RET'); ?>/>
I changed the name to an array and POSTed it to my script, where I looped through the array and handled it there. Still not sure what the problem was with the jQuery-based solutions, but I figured I'd post this for everyone to refer to in the future.
You've got lots of nested functions() in your JavaScript, makes it hard to follow what you're doing.
However, it seems that you're just passing a function to .val() rather than an actual value. Try this instead:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
$(form).find("input[name=specialty]").val((function() {
return $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
})());
});
</script>
Or even better, calculate the value first:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
var value = $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
$(form).find("input[name=specialty]").val(value);
});
</script>
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.