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())
Related
I try to do simple code for guessing notes by ear. I have tabs with several empty input fields and you need to put right numbers in these fields according to certain melody (for guitar fretboard) . One button shows first note, another button checks whether you put right or wrong number and depend on it approves or erase your number.
I know how to check every input field using its id's but can i do it such way that when i push 2nd button it get value from selected input and compare it to its placeholder or value attribute?
It is my codepen
https://codepen.io/fukenist/pen/BxJRwW
Script part
function showfirst() {
document.getElementById("fst").value = "12"
}
function show1other() {
var snote = document.getElementById("scnd").value;
if (snote == 9 ){
document.getElementById("scnd").value = "9";
}
else {
document.getElementById("scnd").value = "";
}
}
You can use document.querySelectorAll() to get all your inputs and loop over them.
Sample:
// Get all inputs as an array (actually NodeList, to be precise; but it behaves similar to an array for this use case)
var inputs = document.querySelectorAll('input');
// Function to reveal the first input's value
function showFirst(){
inputs[0].value = inputs[0].dataset.v;
}
// Function to check all values and clear input if wrong
function checkAll(){
inputs.forEach(function(input){
if(input.dataset.v !== input.value){
// Wrong answer, clear input
input.value = '';
}
});
}
<input data-v="12" size="2" value=""/>
<input data-v="9" size="2" value=""/>
<input data-v="8" size="2" value=""/>
<br/>
<button onclick="showFirst()">Show First</button>
<button onclick="checkAll()">Check All</button>
Notes:
I have used data-v to store the correct answer instead of placeholder as that attribute has a semantically different meaning
It may be out of turn but my two cents: Writing out entire songs like this by hand may become tedious. Consider using a JSON string or something similar to map out the tabs and use a templating framework to align them.. Some things you may need to look out for while designing something like this : Alignment of notes (successive notes, simultaneous notes), timing of the song, special moves like slide, hammer on etc.
It may be a better idea to make the Guitar Strings be a background element (either as a background-image or as absolutely positioned overlapping divs) (so You don't have to worry about the lines going out of alignment)
Reference:
HTMLElement.dataset
document.querySelectorAll
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');
});
I have two text boxes, in it will only be allowed positive integers.
If any alphabetical values or any other characters (e.g. %$&*£") are entered, an error message should be displayed and the values must not render a table.
<input type="button" value="total" name="B3" onclick="powerOf();">
This line allows for calculation to be made, how can this validation stop this from happening
when the incorrect values are entered?? As of now minus numbers are calculated and entering alphabets produces an empty table which is not quite what I was going for:
(no1== no1.match(/^-\d+$/) ? alert("First number must be positive"): no1 = no1 ? no1 : 0);
(no2== no2.match(/^-\d+$/) ? alert("Second number must be positive"): no2 = no2 ? no2 : 0)
var range1 = parseInt(no1);
var range2 = parseInt(no2);
Any ideas?
Note: you can do this simply via HTML5 form validation:
<input type="number" min="1">
Then you won't be able to submit the form unless the entered value is a number higher than 1. This only seems to work in Chrome though.
To answer your question, what you're looking for is event.preventDefault(). If you change your onclick function to:
<input type="button" value="total" name="B3" onclick="powerOf(event);">
then you can run event.preventDefault() in the powerOf function, and when you run that, the event will be "cancelled". For example:
function powerOf(event) {
if (!/^\d+$/.test(document.getElementById('input-1').value)) {
event.preventDefault();
}
}
that will cancel the click event when the value of the input with id="input-1" is not digits only.
See this demo for a working example.
This jsfiddle demonstrates the following issue.
The simplest example is:
<input id="number" type="number" value="1">
console.log(document.getElementById('number').value);
This logs 1 as expected. THIS however:
<input id="number" type="number" value="1A">
console.log(document.getElementById('number').value);
Just logs an empty string '', because of the non-numeric character in the value. Some devices+browsers (e.g. Chrome) allow you to enter non-numeric characters in these inputs.
This is annoying because I want the type="number" input for devices that support it (e.g. iPhone, iPad number keyboard). However I want to use javascript to stop dirty input from being entered - which requires fetching the value on keyup - then regex replacing the non-numeric chars.
It appears jQuery's .val() method gives the same result.
This is what I was looking for:
$('input[type=number]').keypress(function(e) {
if (!String.fromCharCode(e.keyCode).match(/[0-9\.]/)) {
return false;
}
});
I understand preventing user input can be annoying and this still allows invalid input such as 1.2.3
However in this situation it is exactly what I needed. Hopefully it will be of use to someone else. Thanks to #int32_t for the suggestion.
You're not supposed to use <input type=number> for things that are not numbers (in very mathematical sense—it won't work for phone numbers or zip codes either) and clearing of the value is deliberate.
You can test whether device supports type=number and attach your fallback only if it doesn't:
var input = document.createElement('input');
input.setAttribute('type','number');
if (input.type != 'number') { // JS property won't reflect DOM attribute
polyfill_number();
}
Alternatively (especially if your number is a zip code, serial number, etc.) you can use:
<input type=text pattern="[0-9]*">
and this will change the keyboard too.
I would like to make a form in HTML where a user enters some data, and via JS that data is used to calculate results that are output to result fields in real time. By that I mean that say I enter Age (24) and Height (1.82m), a field will automatically display the result of 24 * 1.82 after the 1.82 is typed.
Also I would like to know how to output a web page as PDF.
First question :
function calc() {
var a = parseFloat(document.getElementById('field1').value);
var b = parseFloat(document.getElementById('field2').value);
document.getElementById('total').value = a * b;
}
This gets the values from 2 fields (field1 and field2), multiplies them together and then updates the value of the total input. Example HTML used with the above would be :
<input id="field1" onblur="calc()" value="24" />
<input id="field2" onblur="calc()" value="1.82" />
<input id="total" value="" />
the onblur attribute calls the specified function (calc()) when the input looses focus. Note that this is a very simple example and contains no error checking (ie there is a number present etc)
Second question :
For creating PDFs from HTML wkhtmltopdf is the best I have used - its simple to use and has lots of wrappers for different languages (server side - not client side). It runs as a standalone application too (on a server). Oh and its free !
You will have to input fields, add an event listener that is being triggered when the content changes and then simply fill the "result" input with the result. With the use of jQuery this will be very simple.
For generating pdf's in Javascript take a look at this libary:
http://code.google.com/p/jspdf/