Javascript ParseInt() not working in Firefox - javascript

I have a small java script that basically picks up whatever the user has entered into a form and sends it as JSON to a servlet that does some stuff. It's sort of a "preview" function before they submit the form itself. The script works in Chrome, however Firefox does not correctly parse a hidden div I have in the page that tells the JS how many fields of the form there are.
The JS
function send_formdata() {
var numGenes = parseInt(document.getElementById("numGenes").textContent);
alert(numGenes);
var jsonObj = [];
for (var i = 0; i <numGenes; i++) {
if (document.getElementById("c"+i).value == "") {
alert("Please fill out all fields before checking tax model.");
return;
}
jsonObj.push({"value" : document.getElementById("c"+i).value})
}
....
I added the alert() as a debug. In chrome, the alert reads "25" in Firefox it reads "NaN".
The part of the page being picked up:
<div id="numGenes" style="display: none">25</div>
Any Ideas on why Firefox doesn't work here? It's not erroring out, the script simply ends up sending an empty array to the server.

You have to pass radix as a second parameter. Click here to see the documentation.
You should use it like this:
var numGenes = parseInt(document.getElementById("numGenes").textContent, 10);

The code as shown above is missing a single "}" at the end to correctly close off the function. Otherwise, it works in Firefox - displays the value in the . The subsequent document.getElementId() fails, but I assume you have DOM elements with id's c0, c1, etc.

Related

var dataString = \'search=\'+ searchid; - jquery

I'm new to jQuery and I am trying to understand a bit of code to be able to apply a similar concept in my coursework.
$(function(){
$(".search").keyup(function() {
var searchid = $(this).val();
var dataString = \'search=\'+ searchid;
if(searchid!=\'\') {
}
});
})(jQuery);
What is the dataString variable trying to do?
There are quite a few things that seem "off" with this snippet of code, which I'll address below.
What is this code doing?
It looks like some basic functionality that might be used to build a search querystring that is passed onto some AJAX request that will search for something on the server.
Basically, you'll want to build a string that looks like search={your-search-term}, which when posted to the server, the search term {your-search-term} can be easily identified and used to search.
Noted Code Issues
As mentioned, there are a few issues that you might want to consider changing:
The Use of Escaped Quotes (i.e. \') - You really don't need to escape these as they aren't present within an existing string. Since you are just building a string, simply replace them with a normal ' instead. Without knowing more about your complete scenario, it's difficult to advise further on this.
Checking String Length - Your existing code once again checks if the searchId is an empty string, however you may want to consider checking the length to see if it actually empty via searchId.length != 0, you could also trim this as well (i.e. searchId.trim().length != 0).
Consider A Delay (Optional) - At present, your current code will be executed every time a key is pressed, which can be good (or bad) depending on your needs. If you are going to be hitting the server, you may consider adding a delay to your code to ensure the user has stopped typing before hitting the server.
You can see some of these changes implemented below in the annotated code snippet:
// This is a startup function that will execute when everything is loaded
$(function () {
// When a keyup event is triggered in your "search" element...
$(".search").keyup(function () {
// Grab the contents of the search box
var searchId = $(this).val();
// Build a data string (i.e. string=searchTerm), you didn't previously need the
// escaping slashes
var dataString = 'search=' + searchId;
// Now check if actually have a search term (you may prefer to check the length
// to ensure it is actually empty)
if(searchId.length != 0) {
// There is a search, so do something here
}
}
}

How do you compare JavaScript innerHTML return values, when there's a special character involved?

I have a web page with a form on it. The "submit" button is supposed to remain deactivated until the user fills in all the necessary fields. When they fill in a field, a checkmark appears next to it. When all the checkmarks are there, we're good to go.
A checkmark might be set by code like this:
if (whatever) checkLocation.innerHTML = CHECKMARK;
Here's the code I'm using to do the final check. It just loops through all the locations where there may be checkmarks. If it finds a location without a mark, it disables the submit button and leaves. If it gets through them all, it activates the button and returns true.
function checkSubmitButton() {
var button = document.getElementById(SUBMIT_BUTTON);
for (var i=0; i<CHECK_LOCATIONS.length; i++) { // should be for-each, but JS support is wonky
var element = document.getElementById(CHECK_LOCATIONS[i]);
console.log(CHECK_LOCATIONS[i] +": " +element.innerHTML);
// if found unchecked box, deactivate & leave
if (element.innerHTML != CHECKMARK) {
button.disabled = true;
return false;
}
}
// all true--activate!
console.log("ACTIVATING BUTTON!");
button.disabled = false;
return true;
}
Here's the problem: this works so long as the const CHECKMARK contains something simple, like "X". But specs call for a special HTML character to be used: in this case ✓, or ✓. When I do the comparison (in the if line) it ends up comparing the string "✓" to the string "✓". Since these two are not equal, it doesn't recognize a valid checkmark and the button never activates. How can I compare the contents of the HTML element my constant? (And hopefully make the code work even if down the road somebody replaces the checkmark with something else.)
Thanks.
There is no problem with the check character and it behaves exactly like the X character. The problem is, that your html have the checkmark character stored as html entity in hex string. If you compare checkmark to checkmark it works just fine: https://jsfiddle.net/m7yoh026/
What you can do in your case is to make sure the CHECKMARK variable is the actuall checkmark character, not the html entity.
Other option is to decode the html entity: https://jsfiddle.net/m7yoh026/3/
var CHECKMARK = '✓'
var decoded_checkmark = $('<textarea />').html(CHECKMARK).text();
console.log($('div')[0].innerHTML)
if ($('div')[0].innerHTML == decoded_checkmark) {
$('body').append('checkmark recognized<br>')
}
You can convert a character to its HTML entity equivalent like so:
var encoded = raw.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
return '&#'+i.charCodeAt(0)+';';
});
Well, here's what I ended up doing: I made a function called encodeHtml() that takes a character or string, writes it to a brand new div, and then returns what's contained in that div:
function encodeHtml(character) {
var element = document.createElement("div");
element.innerHTML = character;
return element.innerHTML;
}
Then I can compare to what it returns, since it automatically changes "✓" to "✓", and will work with any unforeseen changes to that character. It's a bit of a kludge, but it works. (It's still not clear to me why JavaScript does this automatic conversion...but there are many design choices in which JavaScript mystifies me, so there you go.)
Thanks all for the help.

jquery getting value from input

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.

How can I validate I have drawn something in jSignature panel or not?

jSignature is having canvas and it has a class. How can I validate jSignature whether I have drawn something or not ?
I have added one bind for click event.
$sigdiv.bind('click', function(e) {
$("#num_strok").val(parseInt($("#num_strok").val()) + 1);
});
Problem is even I click some corner also num_strock get increases. And for some dragging it will not increase.
I have tried in Google whether it has any built in isEmpty function is there or not. But I have not found anything.
if( $sigdiv.jSignature('getData', 'native').length == 0) {
alert('Please Enter Signature..');
}
Very late to the party... So I wanted to give some input on my findings, each related to
using $("#sigDiv").jSignature('getData', 'putSomethignInHere') function to validate the a signature is present.
Here are the options I have examined for the second attribute passed into the jSignature function:
native returns an object of objects .length == 0 when the sig box is empty, but .length > 0 when there is something in the sig box. If you want to know how many strokes just use the length of this object.
NOTE: According to the jSignature documentation:
"Stroke = mousedown + mousemoved * n (+ mouseup but we don't record that as that was the "end / lack of movement" indicator)"
base30 also returns an object. Here I looked at the information in the second index position of this object.
x = $("#sigDiv").jSignature('getData', 'base30')[1].length > 0 ? TRUE : FALSE Here x would yeild TRUE if the box has been signed and FALSE when the jSig box is left untouched.
In my case, I used the base30 attribute for validating signature complexity, not just "did the end user draw something?".
x = $("#sigDiv").jSignature('getData', 'base30')[1].length > {insertValueHere} ? TRUE : FALSE. To validate the end user actually signed in the box and gave more than a simple '.' of small 'x'. The return value of the second index yielded from base30 gets larger as the complexity. Thus, if the user did enter just a dot,
x = $("#sigDiv").jSignature('getData', 'base30')[1].length would be about 5. The yielded value just get larger and larger the more the end user draws in the box. The highest lenght I recorded during my testing was 2272. And I scribbled and scribbled in the box for all of 15 secounds.
According to the jSig documentation:
base30 (alias image/jSignature;base30) (EXPORT AND IMPORT) (VECTOR) data format is a Base64-spirited compression format tuned for absurd compactness and native url-compatibility. It is "native" data structure compressed into a compact string representation of all vectors.
image- this is a choice I would avoid for validation. It produces an object with a long string in the second index position. The last one I measured was 672 characters long. Using image produces a string regardless whether the sig box is blank or used. And to make things more unuseful, the string produced is different for a blank signature box in Chrome verse a blank signature box in FF Developer. I'm sure the image value has a use, but just not validation.
svgbase64 - this is similar to image with exceptions. Unlike image, using svgbase64 produces a long -yet shorter- string in the second position. Also, this string IS the same when I performed the Chrome verse FF Developer check. This is where I stopped my testing. So I assume you can use svgbase64 for validation.
These are my conclusions, yours may vary. Please don't hold my low reputation against me.
According to the jSignature website there is a getData function in the API. If you use the getData function on an empty signature area as reference, you could then use getData whenever you want and compare it to the empty reference. You would then be able to tell if something has been written in the signature area.
This is just a guess from my part, as I haven't used this script, but I think something like this would be able to work.
EDIT
I also found this on the website
The dom element upon which jSignature was initialized emits 'change'
event immediately after a stroke is done being added to the storage.
(In other words, when user is done drawing each stroke. If user draws
3 strokes, this event is emitted 3 times, after each stroke is done.)
Here is how you would bind to that event:
$("#signature").bind('change', function(e){ /* 'e.target' will refer
to div with "#signature" */ })
Event is emitted asynchronously through a "thread" ( setTimeout(..., 3) ) so you don't need to wrap your event handler into "thread" of any kind, as jSignature widget will go on and will not be waiting for you to be done with your custom event handler logic.
Couldn't you just set a flag variable that gets set to true on the first change event? That would indicate that something is written into the area
You can check the base30 vector if any points are there.
var isSignatureProvided=$sigdiv.jSignature('getData','base30')[1].length>1?true:false;
This worked for me, part using roch code :
it basically assigns the signature to a hidden textarea before submitting for validation:
<div id="signatureparent">
<div id="signature"></div>
<label for='signature_capture' class='error'></label>
</div>
<span style="visibility:hidden;">
<textarea name="signature_capture" class="required" id="signature_capture"></textarea>
</span>
<script>
$(document).ready(function(){
$('#submit').click(function() {
var isSignatureProvided=$('#signature').jSignature('getData','base30')[1].length>1?true:false;
if (isSignatureProvided) {
var $sigdiv = $("#signature");
var datapair = $sigdiv.jSignature("getData", "svgbase64");
var data = $('#signature').jSignature('getData');
$("#signature_capture").val(data);
}
});
});
</script>
Unfortunately no of existing answers worked for me. On my site I have two methods of inputting a signature: manual and jSignature('importData', imgBase64)
Testing of jSignature('getData', 'native') worked only for manual drawing. And nothing worked for the image way.
The solution appeared to be simple. Just test the canvas element. It probably won't work for IE9 but who cares. Here is it in TypeScript:
isSignatureBlank() {
var canvas = <any>$('#signatureElem').find("canvas")[0];
if (!canvas) return true;
this.emptyCanvas = this.emptyCanvas || document.createElement('canvas');
this.emptyCanvas.width = canvas.width;
this.emptyCanvas.height = canvas.height;
return canvas.toDataURL() == this.emptyCanvas.toDataURL();
}
Adopted from here: How to check if a canvas is blank?
Search the code in your javascript file. Check when they are hiding 'Undo Stroke' block
t.dataEngine.data.length
That will help you finding how many stroke is made to the signature panel.
Maybe try something like this (assuming your signature fields are of class 'signature')...
$('.signature').each(function (index) {
var datapair = $(this).jSignature("getData", "svgbase64");
if (datapair[1].length > 1000 ) {
// Signature is valid; do something with it here.
}
});
The best answer:
if($sigdiv.jSignature('getData', 'native').length == 0) {
alert('Please Enter Signature..');
}
produced the following error:
$sigdiv.jSignature(...) is undefined
So I would suggest using:
if(typeof($sigdiv.jSignature('getData', 'native')) != 'undefined') {
alert('Please Enter Signature..');
}

Javascript not working in firefox

I have a PHP form validation function that I developed in chrome and now will not work in firefox or Opera.
The function checks to see if a section of the form is blank and shows and error message. If there is no error then then the form submits through document.events.submit();
CODE:
function submit_events()
{
//Check to see if a number is entered if the corosponding textbox is checked
if (document.events.dj_card.checked == true && dj_amount.value==""){
//Error Control Method
//alert ('You didn\'t enetr an Amount for DJ\'s Card!');
var txt=document.getElementById("error")
txt.innerHTML="<p><font color=\"#FF0000\"> You didn\'t enetr an Amount for DJ\'s Card!</font></p>";
window.document.getElementById("dj_card_label").style.color = '#FF0000';
//Reset
window.document.getElementById("company_amount_label").style.color = '#000000';
window.document.getElementById("own_amount_label").style.color = '#000000';
}else{
document.events.submit();
}
The document.events.submit();does work across all my browsers however the check statements do not.
If the box is not ticked the form submits. If the box is ticked it does not matter whether there is data in the dj_amount.value or not. The form will not submit and no error messages are displayed.
Thanks guys.
Here are some things I noticed. Not sure if it will solve the problem, but you need to fix some of these; some of them are just observations.
dj_amount is not declared nor referenced; my guess is you mean documents.events.dj_amount
You should put a ; at the end of every statement in javascript, including the end of var txt = document.getElementById("error")
You don't need to escape the string in the txt.innerHTML line; you only need to escape like quotes, such as "\"" or '\'', not "'" or '"'
You don't need the window.document referenced; document will do in almost all cases
EDIT - As Guffa points out, FONT is an old and deprecated element in HTML. It's not the cause of your problems, but modern markup methods mean you don't need it. Consider omitting and applying the style to the paragraph tag instead.
See edits below.
function submit_events() {
//Check to see if a number is entered if the corosponding textbox is checked
if (document.events.dj_card.checked == true && document.events.dj_amount.value == "") {
//Error Control Method
//alert ('You didn't enetr an Amount for DJ\'s Card!');
var txt = document.getElementById("error");
txt.innerHTML = "<p style=\"color: #FF0000;\"> You didn't enter an Amount for DJ's Card!</p>";
document.getElementById("dj_card_label").style.color = '#FF0000';
//Reset
document.getElementById("company_amount_label").style.color = '#000000';
document.getElementById("own_amount_label").style.color = '#000000';
} else {
document.events.submit();
}
}
Consider Firebug so that you can see and log to console javascript errors and messages:
http://getfirebug.com
I believe one of the above answers would solve your problem. For future reference, although it might not be suitable for your project, please know that writing forms and javascript feedback is much easier and faster when you use a library like jQuery.
To have minimal changes in code, just add this line before the first if statement:
var dj_amount = document.forms["events"].elements["dj_amount"];
However your code need serious optimization let us know if you're interested.
Edit: here is the optimization. First the "small" things - instead of whatever you have now for "error" container, have only this instead:
<p id="error"></p>
Now add this CSS to your page:
<style type="text/css">
#error { color: #ff0000; }
</style>
This will take care of the red color, instead of hard coding this in the JS code you now control the color (and everything else) from within simple CSS. This is the correct approach.
Second, right now you are submitting the form as response to onclick event of ordinary button. Better approach (at least in my humble opinion) is having submit button then overriding the form onsubmit event, cancelling it if something is not valid. So, first you have to change the function name to be more proper then have proper code in the function. Cutting to the chase, here is the function:
function ValidateForm(oForm) {
//declare local variables:
var oCardCheckBox = oForm.elements["dj_card"];
var oAmoutTextBox = oForm.elements["dj_amount"];
//checkbox cheched?
if (oCardCheckBox.checked) {
//store value in local variable:
var strAmount = oAmoutTextBox.value;
//make sure not empty:
if (strAmount.length == 0) {
ErrorAndFocus("You didn't enter amount for DJ's Card!", oAmoutTextBox);
return false;
}
//make sure it's numeric and positive and not too big:
var nAmount = parseInt(strAmount, 10);
if (isNaN(nAmount) || nAmount < 1 || nAmount > 1000000) {
ErrorAndFocus("DJ's Card amount is invalid!", oAmoutTextBox);
return false;
}
}
//getting here means everything is fine and valid, continue submitting.
return true;
}
As you see, when something is wrong you return false otherwise you return true indicating the form can be submitted. To attach this to the form, have such form tag:
<form ... onsubmit="return ValidateForm(this);">
And instead of the current button have ordinary submit button:
<input type="submit" value="Send" />
The code will be called automatically.
Third, as you can see the function is now using "helper" function to show the error and focus the "misbehaving" element - this makes things much more simple when you want to validate other elements and show various messages. The function is:
function ErrorAndFocus(sMessage, element) {
var oErrorPanel = document.getElementById("error");
oErrorPanel.innerHTML = sMessage;
document.getElementById("dj_card_label").style.color = '#FF0000';
document.getElementById("company_amount_label").style.color = '#000000';
document.getElementById("own_amount_label").style.color = '#000000';
}
Last but not least, the "new" code also makes sure the amount is positive number in addition to check its existence - little addition that will prevent server side crash.
Everything else is pretty much self explanatory in the function: naming conventions, using local variables.... most important is have as little redundancy as possible and keep the code readable.
Hope at least some of this make sense, feel free to ask for clarifications. :)
You should bring up the error console so that you see what the error actually is.
Lacking that information, I can still make a guess. Try some less ancient HTML code; the parser can be picky about code you add to the page using innerHTML:
txt.innerHTML="<p style=\"color:#FF0000\"> You didn\'t enetr an Amount for DJ\'s Card!</p>";

Categories