How do I get a function to run with the .onsubmit event? - javascript

There is probably a really easy solution to this but I cannot for the life of me work out how to fix this issue, and nothing I have found so far has done the trick.
I'm trying to get the function "validate" to run when the form "apply" is submitted:
function init() {
var applyForm = document.getElementById("apply");
setJobValue();
applyForm.onsubmit = validate;
}
Validate looks like the following:
function validate() {
alert("If this alert is up then validate is running");
var dateOfBirth = document.getElementById("dob").value;
var state = document.getElementById("state").value;
var postcode = document.getElementById("postcode").value;
etc.
The function "setJobValue" is running (so I know init is working) and there are no errors in the console, but what adjustments would I have to make for validate to be called?

Well, what happens is that when you put your code above in the head, the script runs when the HTML gets rendered. So during that time, it allocates different memory and function blocks. So when you call that function again, then it gives you different results and no errors because of the existing references. Well its a bit weird but its the way JS works and it is always recommended to put your JS code at the bottom of the page.

You can directly call validate method from your init method instead.
function init() {
var applyForm = document.getElementById("apply");
setJobValue();
validate();
}

When we assign a function to an event, it will fire at last.
so in your case, This should work
function init() {
var applyForm = document.getElementById("apply");
setJobValue();
applyForm.onsubmit = functionToSave;
}
And call your validation method on the submit button onclick event.

Related

Why can't I log this array of td elements? [duplicate]

Using google apps script I'm having trouble running a js function which passes parameters. When I add the parameters it will always run the code when the page loads instead of when the button is clicked.
Direct from the HtmlService example, it is OK - it runs when the button is pressed...
document.getElementById('button1').onclick = doSomething;
But when I add a parameter to the call (and function) as below, it runs just once when the page loads (and not when the button is pressed)...
document.getElementById('button1').onclick = doSomething('with_this_parameter');
Any insight into this behaviour would be greatly appreciated... sorry if the answer is obvious!
When you say
document.getElementById('button1').onclick = doSomething('with_this_parameter');
This means call doSomething('with_this_parameter') and then assign the returned value to document.getElementById('button1').onclick. Hence that is why it gets called when code reaches that line. Whether the value is assignable to that property or not is another question, but that is why it gets called.
Use it like this
document.getElementById('button1').onclick = function(){
doSomething('with_this_parameter');
}
Reference: This solution was given by Mark Linus.
Do like this:
document.getElementById('button1').onclick = function(){
doSomething('with_this_parameter');
}
To assign a reference of function to some variable, you do:
var a = doSomething;
where doSomething is a function.
But when you have to pass parameters and assign that function
var a = doSomething(b);
this will cause trouble as while assigning the function to the variable, it gets called and not when it is intended to be called.
To overcome this, you can use arrow functions or simple function to call your own function with params.
var c = () => doSomething(d);
This actually is understood as var c = anonymous_function;
or
var c = function() {
doSomething(d);
}
Hence you can do:
document.getElementById('button1').onclick = () => doSomething('with_this_parameter');
I usually do clickHandlers like so:
// create button here or get button...
var button1 = document.getElementById('button1').setName('button1');
var clickHandler = app.createServerClickHandler('doSomething');
button.addClickHandler(clickHandler);
function doSomething(e){
var button1 = e.parameter.button1;
<do something with var button>
}
I'm not sure what parameter you are adding, but you need to add a callback element to pass it if it isn't passed by the button itself via a .setId/getId or .setTag/getTag. If it is from a textbox:
var textbox = app.createTextBox();
var button1 =
app.createButton.setName('button1');
var clickHandler =
app.createServerClickHandler('doSomething').addCallbackElement(textBox);
button1.addClickHandler(clickHandler);
Hope this helps!

Hide the password textbox and submit

This is a simple password checking function I messed around with for a little bit. I've tried a lot of different methods (including, but not limited to: .css(), .on('click'), .click(), .animate(), .show(), .hide(), .preventDefault() on the submit), put selectors into variables, moved around all sorts of IDs and $('input[name="s"]') and all sorts of selectors. Not sure if the function won't work, or maybe something else within the script. I've taken the function out of the $(document).ready() tree, and moved it all around inside of it. I'm sure that isn't the problem now, but I'm starting to not be sure about anything at this point.
I'm trying to get the function to hide the password textbox and submit(or is button better?) and show a textarea for news input, with a button to append the update.The appendedTo and .append() section works, but I can't seem to get the passwordcheck function to work. Sometimes it will alert me if it's wrong, but when it's right the if methods don't seem to work. Then I'll change it a few times and the alert will no longer show, nor will the if work any longer.
Any help would be appreciated, and I can provide any code snippets or chunks at request.
Function in question:
function passwordcheck() {
var $newspass = $('#newspass');
var $submitpass = $('#submitpass'); // <--- variables were at one point selectors
var $newssubmit = $('#newssubmit'); // written out, I've changed this a lot
if ($newspass.val() === 'comecorrecT') {
$submitpass.css('display', 'hidden');
$newspass.css('display', 'hidden');
$('#newsinput').css('display', 'block');
$newssubmit.css('display', 'static');
} else {
alert("Try again, please.");
}
};
Rest of the script, for reference:
$(document).ready(function(){
// billboard functions
var $billboard = $('.billboard');
$billboard.mouseenter(function(){
$(this).fadeTo('slow', 0.98);
});
$billboard.mouseleave(function(){
$(this).fadeTo('slow', 0.72);
});
var $learn = $('#learn-more');
$learn.hover(function(){
$(this).fadeTo('slow', 1);
},
function() {
$(this).fadeTo('slow', 0.6);
});
// news and updates/appendedTo
var $submitpass = $('#submitpass');
var $newssubmit = $('#newssubmit');
$submitpass.click(passwordcheck());
$newssubmit.click(function(){
$('#appendedTo').append('<div class="update">'+$('#newsinput').val()+'</div>');
// passwordcheck();
});
});
I've been working with it for a little while now, and I know you guys will have a profound explanation or two.
The way you are doing it now, you are simply passing "undefined" instead of a function (which would be what the passwordcheck function returns) as you are calling the function instead of passing a reference to it in this line:
$submitpass.click(passwordcheck());
Which should be
$submitpass.click(passwordcheck);
In the last block of your code, after
// news and updates/appendedTo
This being said, don't use client side JavaScript for authentication, the password you are checking against is visible for anyone using the site.
Try this:
function passwordcheck() {
var newspass = $('#newspass').val();
var submitpass = $('#submitpass').val();
var newssubmit = $('#newssubmit').val();
if (newspass == 'comecorrecT') {
$('#submitpass').hide();
$('#newspass').hide();
$('#newsinput').show();
} else {
alert("Try again, please.");
}
}

Processing.js doesn't allow external javascript bind in firefox

I'm trying to send data to a processing script. But for some reason the variable pjs below binds to the canvas "competence1" and enters the first if statement, but then the bindJavascript(this)-call returns error, but only in firefox. (works perfectly in chrome):
[pjs.bindJavascript is not a function]
var bound = false;
function initProcessing(){
var pjs = Processing.getInstanceById('competence1');
if (pjs != null) {
// Calling the processing code method
pjs.bindJavascript(this);
bound = true;
//Do some work
}
if(!bound) setTimeout(initProcessing, 250);
}
Environment: Mac OS X - Lion;
OBS! The bindJavascript(this)- method exists in the pde script loaded in the canvas-tag
By wrapping up all my script in a varable-map and by using the second way for setTimeout to be called i can follow each state and control the result.
So wrap it up-->
var ex = {
init : function(canId){
var canId = canId;
// check the if bound
// bind in this closure
// set new timer
}
}
setTimeout-->
setTimeout('ex.init("'+canId+'")', 2000);
and ofcourse add the parameter in so it can hold that value during it's own execution. So processing works just fine and i should use closure more often, that's the solution.
I had the same problem. I was using almost identical JS to you (which I got from the Pomax tutorial), and it was working fine. However, when I added the following preload directive (to load a backdrop), then suddenly my initProcessing function stopped working.
/* #pjs preload="metal_background.jpg"; */
The error message was the same: pjs.bindJavascript is not a function
On debugging, I could see that the pjs object did indeed not have a bindJavaScript function exposed, even though there is one declared in my PDE file.
It turns out this was purely down to timing... the preload had slowed down the initialisation of the processing object, so the second time round the 250ms loop, the pjs object existed, but didn't yet have its bindJavaScript function.
I am not 100% sure how Processing.js does this object construction, but in this case, a simple solution was just to check whether bindJavaScript actually was defined! I changed my code to the following:
var bound = false;
function initProcessing() {
var pjs = Processing.getInstanceById('mySketchId');
if(pjs != null) {
if(typeof(pjs.bindJavaScript) == "function") {
pjs.bindJavaScript(this);
bound = true;
}
}
if(!bound) setTimeout(initProcessing, 250);
}
After this it worked fine!

Why does my custom javascript prevent the validators from firing

In .NET 2.0, I have several client side validators ala the .NET validator controls. These run fine when I click a button...until I add my own javascript function to this button. Instead of running in addtion to the validators, it seems to prevent them from running at all.
To be clear, the validator controls are basic required field validators, and here is the javascript I added:
<script language="javascript">
function yaya()
{
var chkAmount = document.frmSearchFor.txtCheckAmount.value;
var amtApplied = document.frmSearchFor.lblAmountApplied.value;
if (amtApplied < chkAmount)
{
return confirm('Continue?');
}
}
</script>
And it's tied to the button like this...
OnClientClick="return yaya();
those are probably not the ID's being rendered to your page. Try this:
function yaya()
{
var checkAmount = parseFloat(document.getElementById("<%=txtCheckAmount.ClientID %>").value);
var amoutApplied = parseFloat(document.getElementById("<%=lblAmountApplied.ClientID %>").text);
if (amoutApplied < checkAmount)
{
return confirm('Continue?');
}
}
And try attaching it like this:
OnClientClick="javascript:yaya();";
Client-side validation is done via javascript just like your client click. When you specify the client-side event, I'm guessing there's nowhere for the validation code to attach. You may need to modify either the validation code to call your function, or your function to call the validation code. Probably the latter is easier. Instead of assigning OnClientClick at design time, add a client script that stores the current click handler function, creates a function that runs your code and then runs the stored handler function, and attaches that new function as the click handler.
<script>
var baseHandler = myElement.onclick;
myElement.onClick = function() {
// run your code here
baseHandler();
}
</script>
issue is that you are specifying a return in your OnClientClick attribute. when the page renders, it comes out like this
<input ... onclick="return yaya();WebForm_DoPostBackWithOptions...
after yaya completes, the onclick function concludes and I believe it's shutting down any further action that would normally happen before the form is submitted. it's kind of ugly but you can get around this by only having a return when your function evaluates to false:
OnClientClick="if (!yaya()) { return false; }"
for this to work you should also include return true; at the end of your function in case the conditions for the if check are not met.
you may also be having issues with references to elements as Hunter mentions but you're not providing your markup to verify that.

Overriding a JavaScript results in infinite loop in IE but not in Firefox

I'm using the following code to override a JavaScript function named dismissRelatedLookupPopup(). In Firefox, this works without a problem (displays the alert once and runs my code), but in Internet Explorer 7 it results in an infinite loop displaying the alert() forever. I'm doing this because I don't control the code where dismissRelatedLookupPopup() is called, and I'd like to add a hook of my own when it's called. Is there a cross-browser way to do this?
old_dismissRelatedLookupPopup = dismissRelatedLookupPopup;
dismissRelatedLookupPopup = function dismissRelatedLookupPopup(win, chosenId) {
alert("i hate ie");
old_dismissRelatedLookupPopup(win,chosenId);
var name = windowname_to_id(win.name);
var elem = document.getElementById(name);
elem.onchange();
}
Note: It's my understanding that when JavaScript updates the value of an element directly (ie. elem.value = 1) that the onchange() event of that element will not fire. That is why I'm including this code to force the onchange() when the value is updated.
I'm pretty sure that changing this line:
dismissRelatedLookupPopup = function dismissRelatedLookupPopup(win, chosenId)
to
dismissRelatedLookupPopup = function (win, chosenId)
will cure what ails ya.

Categories