trying to update a span with maths result in jQuery - javascript

I am having what is probably a simple issue with some jQuery code. I have two inputs that form variables to a simple piece of maths. One is a text box, the other a range input. I need to display the result of a very simple calculation in a span element.
Here is the html and js I have:
<input type="text" name="txt_bserves" id="txt_bserves" value="0">
<span id="currsalesval">10%</span>
<input type="range" name="convertslider" id="convertslider" min="0" max="100" value="10">
<span id="currsalesconv">525 serves</span>
function updateValue()
{
var sliderval = $('#convertslider').val();
var bserves = $("#txt_bserves").val();
var cserves = (bserves * (sliderval/100));
$("#currsalesval").text(sliderval.concat("%"));
$("#currsalesconv").text(cserves.concat(" serves"));
}
$('#convertslider').on('change, mousemove', function(){
updateValue();
});
The issue comes on the third line, a simple piece of maths to calculate a percentage of the input box.
The currsalesval span updates fine with the percentage value from the slider. But the currsalesval span is not updated with the cserve value.
I realise this might be a type conversion issue, but having been thrugh a number of different variations of conversions, I thought I'd ask here instead.
Thanks in advance guys.

cserves is not a string , so it doesn't have a concat method. Instead of :
$("#currsalesconv").text(cserves.concat(" serves"));
try
$("#currsalesconv").text(cserves + " serves");

Related

How to edit dynamic form fields to create a single hidden field comprised of the value of two fields

I need to send a form off to where a single hidden field is comprised of two of the other fields that will be dynamically populated by a user (post/zip code and first line of address) where after regular expression only the numbers remain "123|456".
I have attempted to start, using the code below, where I monitor the output in the console. I have managed to dynamically edit a textfield so that all that is shown are the numbers but this is not suitable for a user. So I was trying to store the edited textfield data into the hidden field whilst leaving the complete line of address but I could not see how this can be done.
Also, can someone explain why if I remove the commented line the variable is not stripped of any letters albeit just 1?
$(document).ready(function() {
$("#testMe").on('propertychange change click keyup input paste', function() //attaching multiple handlers
{
var removedText = $("#testMe").val().replace(/\D/, '');
$("#testMe").val(removedText); //only removes once if removed
console.log(removedText);
}
);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="hidden" id="hide" value="">
<input type="text" id="testMe" value="">
<span id="test2"></span>
The question was kind of unclear to me, but I did my best to answer.
https://jsfiddle.net/ccu6j6xu/
<input type="hidden" id="hide" value="">
<input type="text" id="zip" value="">
<input type="text" id="address" value="">
<span id="test2"></span>
In the HTML, all I did was add another input, because I think that's what you wanted to do?
$(document).ready(function() {
$("#zip, #address").on('propertychange change click keyup input paste', function() {
var concatText = $("#zip").val().replace(/\D/g, '') + "|" + $("#address").val().replace(/\D/g, '');
$("#test2").text(concatText);
$("#hide").val(concatText);
});
});
Then in the JavaScript, I changed the selector to match the new inputs, and then I changed the function.
The first line of this function defines a variable concatText to hold the values of each input concatenated with a | character between. Each one has regex applied to remove the letters for the final value. Then the next line changes the value of the span to display, and the final line applies this value to the hidden input.
Again, the question was kind of confusing to me, but feel free to comment and I can help some more :)
EDIT: reread the question, I think this better answers

Need to display result of addition in a text box using javascript

I need to create two text boxes where the user can insert number, and a button that adds them.
I need to use the .val() to bring the data from the html body, that is done.
My issue is that I don't know how to display the result in a text box, and not using the alert option.
Help!
You need to add change listeners to your html elements and you need to run a function on change.
<input type='number' id='firstBox' onChange='calculate()' />
<input type='number' id='secondBox' onChange='calculate()' />
<input type='number' id='answerBox' />
function calculate(){
var first = Number(document.getElementById('firstBox').value)
var second = Number(document.getElementById('secondBox').value)
var answer = document.getElementById('answer')
answer.value = first + second
}
Also, I created a quick fiddle for you here, definitely check it out it will help you get acquainted.

$(this).val() not working in FireFox but works in Chrome

This is my problem. When I try to set the value of an input field in FireFox nothing happens. I don't get any errors. It simply just doesn't work. It is supposed to add two decimal places after the number. It works perfectly in Chrome. Here's my jQuery code...
$('input.drawer').on('blur', function() {
var number = parseFloat($(this).val());
var n = number.toFixed(2);
$(this).val(n);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input tabindex="1" class="drawer f-right m-left w50 right-text" type="number" placeholder="$0.00" />
I've tried using $(this).attr('value' n); but that doesn't work either.
So, it does "work", but Firefox simply formats the number differently, it truncates the 0s. If you do
$(this).val(6.00);
you will see that it shows 6.
If you do
$(this).val(6.50);
it will show 6.5 but also an error that it is not a valid value.
What's with the error?
The default step value of the input is 1 which makes Firefox only consider numbers as valid that are a multiples of that.
If you set step="0.01" then Firefox considers floating point numbers as valid.
But the formatting is still incorrect
However, this still won't show the decimals for whole numbers. I guess that's just how it is given that the spec doesn't seem to describe how the value should be formatted.
If the format is more important to you than the functionality of the number input, use a normal text input instead.
This has to do with how firefox treats the number input type. https://bugzilla.mozilla.org/show_bug.cgi?id=1003896
You can try text if that is an acceptable input type for you.
Having found the above citation everything below is only interesting but not useful
For example in Firefox vs Chrome check out
http://jsbin.com/coyuyipeca/edit?html,js,output
You'll see the value is indeed formatted correctly in the alert in FF but lost when pushed to the number field. Change the input to
<input tabindex="1" class="drawer f-right m-left w50 right-text" type="text" placeholder="$0.00" />
and you'll see it work. Of course you will lose the benefits of the number field (notably mobile inputs) so it depends on how important that functionality is to you.
Note: One odd thing I note is if you set the input to
<input tabindex="1" class="drawer f-right m-left w50 right-text" type="number" step=".01" placeholder="$0.00" />
You can use the increment button and get decimals, it only seems to be lost when jQuery sets the value. Not sure if this is an issue with jQuery or with FF
This seems to work for me in the following jsfiddle:
<input tabindex="1" class="drawer f-right m-left w50 right-text" type="number" placeholder="0.00" />
$('input.drawer').on('blur', function() {
var number = parseFloat($(this).val());
var n = number.toFixed(2);
$(this).val(n);
});
Which is your exact code. The only thing is you cannot input '$' symbol into a number field. That would fail. So for eg: '3.4512' gets truncated to '3.45' and set properly, but '$3.4512' just gets cleared when I try it.
https://jsfiddle.net/bz0os3kp/1/
Your code seems to work. It does truncate the trailing zeros in firefox however.
I found a work around that seems to work in Firefox. I change the type of input to number on focus giving me the proper keypad on mobile but then change the type back to text on blur giving me to two decimal places. See the code below...
$('input.drawer').on('blur', function(){
var number = parseFloat($(this).val());
var n = number.toFixed(2);
$(this).attr('type','text');
$(this).val(n);
});
$('input.drawer').on('focus', function(){
$(this).attr('type','number');
});

JavaScript - change value of output based on checkboxes selected

I'm fairly new to JavaScript and am trying to write some code that lists three price options in a form, as checkboxes. If both of the first two are selected, I want the total price to drop by a certain amount.
My code is based on the code in this question:
Javascript checkboxes incorrect calculating
They reset the base value by a date variable. I assume that if I have a function that sets the base to a negative value if those two boxes are checked, that would achieve what I want. I'd also like the output to have an additional tag of 'save (x) per month' when this happens.
However I'm not sure how to go about relating the variable to the checkboxes.. do I need to use jquery as per how to change the value of a variable based on a select option:selected?
Jquery is never necessary, but it is always a plus. since you are learning javascript, i would recommend not using the framework yet.
First you need a form (it would be better if you showed us what your form looks like):
<form>
<input type="checkbox" id="first" /><label for="first">First Box</label> <br>
<input type="checkbox" id="second" /><label for="second">First Box</label> <br>
<input type="text" id="output" value="5.00"/>
</form>
Now the javascript
<script type="text/javascript">
var first = document.getElementById("first");
var second = document.getElementById("second");
first.onchange = function () {
if (this.checked == true) {
document.getElementById("output").value = "new Value";
}else {
document.getElementById("output").value = "other Value";
}
}
... the same can be done for 'second' ....
</script>
I'm assuming you are modifying your recalculate() function from your earlier question. In that function, after you get your sum, add this to apply the discount:
if ($("#chkBox1,#chkBox2").filter(":checked").length == 2)
{
sum -= discount;
}
To write the message to your output, modify your $("#output").html(sum) code to this:
$("#output").html(sum + " Save $" + discount + " per month");
if (document.getElementById('checkBox1').checked && document.getElementById('checkBox2').checked) {
// Change the price
}
There are many ways to address this issue. As a reminder before I get into it, never do something like 'calculating price' on the client-side. That is, you can calculate the price so show the user, but any real calculations should be done on the server side (as clients can adjust and manipulate form submissions).
I created a simple example that will tally the results of checked checkboxes (and simply displays the result). There are lots of ways you can manipulate this code to fit your purpose. I have used jQuery, but there are other interesting options for this problem (check out KnockoutJS, for instance).
<input type="checkbox" class="adjust one" data-value="1.00" id="so1" /> <label for="so1">$1.00</label> <br/>
<input type="checkbox" class="adjust two" data-value="2.00" id="so2" /> <label for="so2">$2.00</label><br/>
<input type="checkbox" class="adjust one" data-value="3.00" id="so3" /> <label for="so3">$3.00</label>
<p>
Total: <span class="total"></span>
</p>
Then, you want to include the following JavaScript (along with the jQuery library).
var total;
var calculateTotal = function() {
total = 0.0;
$('input[type="checkbox"]:checked').each(function() {
total += parseFloat($(this).data('value'));
});
$('.total').text(total);
};
$(document).ready(function() {
$('input[type="checkbox"]').live('change', function() {
calculateTotal();
});
calculateTotal(); //do it for initial price
});
calculateTotal() will calculate a total based on the checkboxes (inputs of type checkbox) which match the selector "checked". This then pulls the data attribute "value" from each checkbox and calculates a total based on that number. The logic for your problem is likely to differ, but simply adjusting calculateTotal should handle this. Finally, the calculateTotal function gets called whenever a checkbox is 'changed' (and once initially).
Hopefully this should be a big help in getting you up and running. Here is a JSFiddle live demonstration.

getting not a number(NaN) error html/js

I am getting NaN error while clicking radio button first. The page have a3 radio button when I click that 1st button it saya NaN and remaining 2 buttons has no response
this is my HTML
<input type="hidden" name="totalamount" id="totalamount" value="<?php echo get_total_amount();?>" /
<input type="radio" name="rmr" id="payment1" value="3" onclick="updatepayment(this.value)" />
<input type="radio" name="rmr" id="payment2" value="5.5" onclick="updatepayment(this.value)" />
<input type="radio" name="rmr" id="payment4" value="10" onclick="updatepayment(this.value)" />
<div id="finalamount">
</div>
also I have mentioned my JS
$(document).ready(function(){
$('input[name=rmr]').click(function () {
//make sure one is checked
if($('input[name=rmr]:checked').length > 0) {
$('#finalamount').html($("#totalamount").val() * $("input[name=rmr]:checked").val());
}
});
});
Three things:
1) As you're using the amount from the "totalamount" element, one has to ask: Are you sure that
value="<?php echo get_total_amount();?>"
...is outputting a valid number? Because if not, then the code
$('#finalamount').html($("#totalamount").val() * $("input[name=rmr]:checked").val());
...will indeed result in NaN. The * operator will try to convert both of its operands from strings to numbers, and of course if the value output by that PHP code isn't a valid number (for instance, if it's "$0.00" or something), the result of the conversion will be NaN. And NaN times anything is NaN.
This example of an invalid amount in the "totalamount" element yields something that looks a lot like the behavior you describe. (That code isn't identical to yours, I did some very light refactoring, see below. But for the purposes of demoing an invalid number, it doesn't matter.)
2) There's no > at the end of that hidden input in the text of your question. If you did a direct copy-and-paste, I wonder if that could be the problem?
3) As you're using jQuery, there's no need for the onclick attributes. Instead:
$(document).ready(function(){
$("input[name=rmr]").click(function(){
var checked = $("input[name=rmr]:checked");
updatePayment(this.value);
if (checked.length > 0) { // make sure one is checked
{
$("#finalamount").html( $("#totalamount").val() * checked.val() );
}
});
});
...assuming you want updatePayment called every time.
Live example
Folding updatePayment into the main click behavior lets you avoid any issues that may exist with the order in which DOM0 (onclick attribute) handlers and DOM2 handlers (the ones used with jQuery) are called.
It is working fine for me. Please find the working code in jsfiddle. You have to make sure that the value in the totalamount input is a numeric value. You can user parseFloat() to convert the string value into a float value.
Ex
parseFloat($("#totalamount").val()) * $("input[name=rmr]:checked").val()
As #Crowder parseFloat() is not necessary since javascript take care of the type conversions.
You try to put an alert()/console.log() command before the calculation to see whether the totalAmount is having an non-numeric value. Ex: alert($("#totalamount").val())

Categories