I am having trouble when trying to set a value in a select. I keep seeing NaN as my result (in some browsers - mainly android smartphone / tablet default browsers)
I am running a simply if statement and setting the value if the condition is true:
if (variable1 >= variable2)
{
$('select[title="title"]').val(variable1);
}
Where a 'typeof' check on both variable1 and variable2 before the if statement show them both as numbers. Despite this the resulting value shown in select in the browser is NaN.
I've even tried wrapping the javascript Number() function around the variables like so:
if (Number(variable1) >= Number(variable2))
{
$('select[title="myTitle"]').val(Number(variable1));
}
But I still get the same result!
Note: This works fine in desktop / laptop browsers and even Opera Mobile on my Samsung Galaxy S2 but as I'm working towards this being an app to run on any phone I wanted to be complete in my error checking.
edit:
In case it's my select thats the problem (as suggested below) what's wrong with it here?
Is it because it is converted to a string at the point I return it?
var startPoint = this.do_calcTotal(); // typeof startPoint shows as number
var endPoint = startPoint + 12; // typeof endPoint shows as number
var mySelect = '<select title="myTitle" class="myClass">';
for (o=startPoint; o<endPoint; o++)
{
mySelect += '<option>'+Number(o)+'</option>'; // is this right?? it shows 'o' and 'Number(o)' as typeof number!?
}
mySelect += '</select></span></div>';
return mySelect;
Edit: and the code to add the current selected value to the span for display...
function do_changeNumberSpan(value)
{
$('.mySpan').text(Number(value)); // even tried throwing a Number() round the value here!!
}
Ok. Check out this jsfiddle. This should help you understand a little bit of what your goal is... and how you can accomplish it.
http://jsfiddle.net/aaronfrost/yFuyu/
Related
I have an input with id="meetingName" and maxlength="100".
I have a listener added with Javascript that runs a Javascript function to calculate how many characters have been typed and hence how many of the 100 characters remain to be typed.
The code works fine in (Mac) Firefox but not in Chrome or Safari. In Chrome & Safari it displays NaN.
If I run the code to get the number of characters typed:
var numChars = document.getElementById('meetingName').textLength;
... and I do a console.log(numChars) step, it shows as NaN in Safari but as 0 in Firefox (which is correct as I have yet to type any characters). I have tried it with and without using Number() to tell it to act as a number, same story either way.
If I ask what the variable type is
var test1=typeof numChars
... and I log that to the console, it shows correctly as 'number' in both Firefox and Safari.
But if I then, immediately run isNAN() on numChars, it says it's not a number in Safari.
HTML
<input type="text" id="meetingName" required maxlength="100">
JS
// Set up a listener to count the number of characters in the Meeting Name input field
var meetingName = document.getElementById('meetingName');
meetingName.addEventListener("focus", meetingNameNumChars, false);
meetingName.addEventListener("input", meetingNameNumChars, false);
// Get max number of characters in the Meeting Name <input> field
var maxCharsMn = Number(document.getElementById('meetingName').maxLength);
function meetingNameNumChars() {
var numChars = document.getElementById('meetingName').textLength;
var test1=typeof numChars;
console.log(test1);
if (isNaN(numChars)) {
console.log(numChars);
}
var numCharsLeft = maxCharsMn - numChars;
document.getElementById('numCharsLeftMeetingName').innerHTML = " " + numCharsLeft + " characters remaining.";
}
So, in the above code, I have two console.log lines:
In Firefox it comes back as one logged item = "number" because the if statement doesn't evaluate as true
In Safari it comes back with two consecutive logged items = "number" and then "NaN" because ... I wish I knew! I tried a parseInt(numChars) step just in case and nothing changed.
Funny enough, the same code, run on a textarea element works just fine in Firefox, Chrome & Safari.
Help much appreciated folks.
For a cross-browser solution, use value.length. Take a look at a working solution below.
// Set up a listener to count the number of characters in the Meeting Name input field
var meetingName = document.getElementById('meetingName');
meetingName.addEventListener("focus", meetingNameNumChars, false);
meetingName.addEventListener("input", meetingNameNumChars, false);
// Get max number of characters in the Meeting Name <input> field
var maxCharsMn = Number(document.getElementById('meetingName').maxLength);
function meetingNameNumChars() {
var numChars = document.getElementById('meetingName').value.length;
var numCharsLeft = maxCharsMn - numChars;
document.getElementById('numCharsLeftMeetingName').innerHTML = numCharsLeft + " characters remaining.";
}
<input type="text" id="meetingName" required maxlength="100">
<p id="numCharsLeftMeetingName"></p>
Here is my Javascript code.
$("#changetemp").click(function () {
var temp = $("#temperature").html;
var final_letter = temp[temp.length-1];
$("#temperature").html(function ()
{if (final_letter == "F") {return celsius;}
else {return fahrenheit;}});});
});}});});
It is supposed to toggle the temperature between celsius and fahrenheit but does a big fat nothing. I've googled and changed a few things (e.g. gone between val, html and text, and tried charAt but I can't get it to do anything, let alone the right thing. Any suggestions would be very welcome.
Edit: "#changetemp" is the button you click to toggle between temperature (ideally).
"#temperature" is where the temperature displays (and it does, but then won't change).
Also tried:
console.log(final_letter); (which gave the correct letter in the console)
console.log(celsius); (which reports as 'undefined') as does console.log(fahrenheit);
These two are defined earlier via a JSON
$.getJSON( url, function(location){ var celsius =
$("#temperature").html(Math.round(location.main.temp - 273) + "°C");});
and I tried to make them be global variables by putting
var celsius;
var fahrenheit;
after the beginning of the first function (which surrounds everything else) but I'm guessing that didn't work.
More:
Googling suggests that variables cannot begin with a number. Is this what is stopping me here?
1. I've managed to show the temperature though, just not change it.
2. How do you get round that? I tried changing the code so that 'celsius' would give 'Temperature: 10C' rather than '10C' but that didn't solve it.
i assume the error is in the line var temp = $("#temperature").html;
Does it help if you change it to var temp = $("#temperature").html();?
html is a jQuery function, so you need to call it with the parantheses. Otherwise temp will not contain the content of the #temp element, but rather a reference to the html method. Therefore you don't get the last letter of the content.
Can you tell me what I am missing in writing this code?
<button onclick="getBrowserName()">You Browser Name?</button>
<script>
function getBrowserName()
{
//Uses external interface to reach out to browser and grab browser useragent info.
var browserAgent:String = ExternalInterface.call("function getBrowser(){return navigator.userAgent;}");
//Determines brand of browser using a find index. If not found indexOf returns (-1).
if(browserAgent != null && browserAgent.indexOf("Firefox")>= 0)
{
alert("Firefox");
}
else if(browserAgent != null && browserAgent.indexOf("Safari")>= 0)
{
alert("Safari");
}
else if(browserAgent != null && browserAgent.indexOf("MSIE")>= 0)
{
alert("IE");
}
else if(browserAgent != null && browserAgent.indexOf("Opera")>= 0)
{
alert("Opera");
}
else
{
alert("Undefined");
}
return 0;
}
</script>
Well, there are a few things wrong here.
var browserAgent: String: it appears that you're using actionscript syntax, but JS uses dynamic typing, so var is all you need. There's no need to explicitly define the variable's data type, and if you try to do it this way in JS, it's going to give you syntax errors.
ExternalInterface.call: this is another carryover from ActionScript: you don't need this. In fact, it won't work at all because there's no ExternalInterface class in standard JS.
Your getBrowser() function is unnecessary. You're setting browserAgent equal to the result of calling a function from an ExternalInterface, but you can do this directly: var browserAgent = window.navigator.userAgent.
When I fixed those things, it worked fine.
Next time, I would recommend checking the browser console, because, if nothing is happening, the errors that appear there will help you solve your issue nine times out of ten.
Demo
If you replace this line
var browserAgent:String = ExternalInterface.call("function getBrowser(){return navigator.userAgent;}");
with this line:
var browserAgent = window.navigator.userAgent;
Then your script works fine on my side.
However, the criteria you use to test the engine are not precise. Have a look at this:
http://www.useragentstring.com/pages/useragentstring.php
There are many browsers that will tell you Firefox even if they another brand. But they are based on each other or they use a specific engine that is built in other browsers too.
If I use your script with a Chrome browser, it says "Safari" instead of "undefined".
About the punctuation: I know of only two places in Javascript where to use the double point:
the conditional operator a = b ? c : d;
the attribute - value assignment in object notation: { name : value }
Your code line containing :String = ExternalInterface... reminds me rather on ActionScript (?).
Im not quite sure what the follow code should be doing. Are you sure its correct?
var browserAgent:String =
ExternalInterface.call("function getBrowser(){return navigator.userAgent;}");
I would expect this code to simply look like this:
var browserAgent = navigator.userAgent;
Below is a example with this change.
http://jsbin.com/lukasere/1/edit
This has me stumped, and should be pretty simple.
I have an input in my html:
<input type="text" id="fafsaNbrFam" name="fafsaNbrFam" value="<%=nbrFam%>" class="hidden" />
System.out.println(nbrFam); // Works, gives me "6"
Then my js code:
$("#submit").click(function(e) {
var numEntries = 0;
var fafsaNbr = 0;
$("input[name^='name_']").each(function() {
if (this.value) {
numEntries++;
}
});
// EVERYTHING ABOVE HERE WORKS
fafsaNbr = $("input[name=fafsaNbrFam]").val();
alert(fafsaNbr + "X");
// WHERE THE 6 is I want to put the variable fafsaNbr, just hardcoded for now.
if (6 > numEntries && !confirm("The number of members you listed in your household is less than the number you indicated on your FAFSA. Please confirm or correct your household size. ")) {
e.preventDefault();
}
});
On my alert to test this, I get "undefinedX", so basically my jquery to get the value is coming up undefined.
EDIT: So it turns out my code wasn't the problem, but the placement of my input. Even though the original input placement was being processed, once I changed it, it all worked properly. Needless to say, I am still stumped.
You are missing the quotes around the name value. Try:
fafsaNbr = $("input[name='fafsaNbrFam']").val();
Your code is working fine,
I just added your code to jsFiddle and it works
Live EXAMPLE
Could you please make sure, the java scriplet is loading inside the value tag properly or not by checking the view source in browser?
Try to parse the value of the input like this:
fafsaNbr = parseInt($("input[name=fafsaNbrFam]").val());
Or Check whether the $("input[name=fafsaNbrFam]") is undefined or not.
I have two dropdowns. When selecting a value from the first (bron) I want to select an entry from the second.
This is fired from the onChange of the first dropdown.
function DepId() {
var bron = document.getElementById("IDUserDepartment");
var doel = document.getElementById("IDDepartment");
var bronwaarde = bron.options[bron.selectedIndex].value;
for ( var i = 0; i < doel.options.length; i++ ) {
var doelwaarde = doel.options[i].value;
if ( doelwaarde == bronwaarde ) {
doel.options[i].selected = true;
return;
}
}
}
But this does not work.
EDIT: for whatever reason, I never get a match. When I hardcode any of the values, and then do: doel.options[hardcodedvalue].selected=true, the option is selected. When I test for window.alert(doelwaarde) inside the loop, this always returns zero.
Any suggestions?
Your code should work, I see nothing wrong with it. If I may make three suggestions:
You might want to use jQuery: simpler code, better multi-browser support.
Use console.log instead of a window alert for debugging purposes: less intrusive, won't interrupt your testing (have a look at the developer console of your browser).
You might want to use English names for your variables, controls, etc. More developers will be able to read it, besides English is often shorter than Dutch ;)