JavaScript onclick() function not working - javascript

I have JavaScript code including several functions, the main one being CheckForm().
The function is called by clicking the 'Submit' button:
<td><input type="submit" name="submit1" id="submit1" value="Register" onclick="return CheckForm();"/></td>
But when the button is pressed nothing happens (the function isn't performed). What can I do to fix this?

Have you tried debugging your code using FireBug or jsFiddle?
Some possible causes are an incorrectly named function or function call(remember that JavaScript is case sensitive), an error in your function or your JavaScript code not being referenced in your page.
If you aren't using either of the above tools then try using a console.log or alert inside your function to see if it is being called.

You can use it like this.
function CheckForm()
{
//doing stuff
return true;
}
<form id="formToCheck"></form>
$('#formToCheck').submit(CheckForm);
Hope it helps
if you want to do it without jquery just add on
<form onSubmit="return CheckForm()"></form>
You can read more about form validation without jQuery here -> http://www.w3schools.com/js/js_form_validation.asp#gsc.tab=0
Maybe if it doesn't work you have some errors. Check JS console in your browser and remove them.

Related

How to add text input variable to URL in javascript

I'm having the weirdest problem right now. I have this JS code:
function CreateChat() {
var chatName = document.getElementById("chatName").value;
window.location.href = "https://localhost:44321/CreateNewChat/CreateChat?ChatName=" + chatName;
}
Thing is, as it is, I can't make it work. It obviously should be calling a controller method, but it just won't work. If I hit that url with the project running and put anything at the end of it, like https://localhost:44321/CreateNewChat/CreateChat?ChatName=TestName, that test name variable will get to the controller without a problem. If I hardcode to the code the "TestName" instead of passing the chatName variable I define earlier, it will get to the controller, no problem. Hell, if I debug the script, the chatName variable gets loaded correctly with my input, and if I console.log the url it will show up correctly (in fact, I can copy/paste that url and it will hit the controller method correctly). But, as the code is presented above, it will never, by any means, hit the controller. It will reach that point, and cut the execution as if there was an error in the JS code. Do you guys have any ideas on this? It's driving me mad, really.
Just in case, this is how I define the text input in the HTML:
<input type="text" required class="form-control" id="chatName" aria-describedby="nameHelp" placeholder="Name your chat!">
Edit: encodeURIComponent on the chatName doesn't work either.
try using window.open with _self instead:
window.open ('https://localhost:44321/yadayada','_self',false);
You have a submit button (and I assume this button is inside a form)... when you click on the submit button the form is submitted to the submit action of the form, this is the default behavior for the submit action.
Now if you don't want your page to be submitted, you can change the button type to button:
<button type="button" onclick="CreateChat()" class="btn btn-primary">Create a New Chat!</button>
Alternatively if you actually need a submit button then you need to prevent the default behavior in order to change window.location:
function CreateChat(event) {
e.preventDefault(); // <-- don't submit the form
var chatName = document.getElementById("chatName").value;
window.location.href = "https://localhost:44321/CreateNewChat/CreateChat?ChatName=" + chatName;
}
You need to pass the event to CreateChat function:
<button type="submit" onclick="CreateChat(event)" class="btn btn-primary">Create a New Chat!</button>

Firing JS function from another file from button in html file

This might be very basic but I couldnt really find a solution to this. I am creating my own website. I have written a javascript file, simply called "main.js".
I can call my entire script in my HTML file like so:
<script src="main.js">
</script>
And I see in the console that everything works as it should. However, this is not what I want. What I want is the code in the JS script to be fired upon a click on my button. This is what I tried:
<input class="button" onclick="main()" type="submit"
value="Submit" name="">
</div>
So I want the script that I have referenced somewhere else in the HTML file to fire the "main" function when my button is clicked. But what happens currently is that the click onto the button simply reloads the page.
So, to get this all into one question:
I want to click my html button and then fire a single function from another script that is called "main.js".
How can I achieve that?
Thank you
I think this might be because of your type: submit.
Try changing it to type="button".
Hope this helps!
You are trying to call a function called main, but you need to run a script that creates a function. The browser won't go looking in a JS file with the same name as the function automatically.
Edit main.js so the code appears inside a function.
function main () {
// Your code here
}
If you don't want the form to be submitted after the JS function is called, then don't use a submit button to trigger it. Use a type="button".
A submit button triggers a reload as it submits the formto the server, unless your main function returns false.
Adding
return false;
at the end of main should do the trick.

JavaScript Text is not submitting form

I have a form called signup. I decided rather than having a button, I would have text with the use of JavaScript to submit, however the form is not submitting.
Finished
First, you should separate your Javascript from your HTML. Read More
You should post more code e.g. HTML.
Here's a working example to get a form to submit:
HTML:
<form id="signup">
</form>
<a class="submit" href="#">Submit</a>
Javascript
var form = document.querySelector('#signup');
var submitBtn = document.querySelector('a.submit');
submitBtn.addEventListener('click', function() {
form.submit();
})
https://jsfiddle.net/hpg6mnnr/
I think you can achieve what you are looking for with this
Finished
You could try achieving your objective using the javascript onclick event handler. Let me explain it to you with the help of an example, as below
<html>
<body>
Google
<script>
function f1() {
alert("f1 called");
//function f1()'s alert demonstrating additional functionality
}
window.onload = function() {
document.getElementById("link").onclick = function fun() {
alert("hello");
f1();
//executing an initial "hello" alert
}
}
</script>
</body>
</html>
Here we create a link and give it an ID of link. Suppose we need it to execute some functionality when it's clicked. All fine for now.
Now after the document is loaded (as demonstrated by window.onload) we wait for the link to be clicked. If it's clicked, we execute the onclick event which gives an alert "Hello". Further suppose you wanted to execute some extra functionality with the click of your link (like submission of a form, as in your case), so we demonstrate it here using the f1() method. As you might see we execute all of these simultaneously simply by using the onclick event handler.
Well, you have several ways to do it!
Firstly verify if there is not another HTML element with the same id as you form, because if it has, you have two problems, one your HTML is not well formatted, second it may be defined first than the tag and of course, the document.getElementById('signup') will catch it firstly. Also if the page hasn't been loaded by complete, it won't find the element, try (see form down below):
window.onload = function () {
var aBtn = document.getElementById('myA');
aBtn.onclick = function () {
document.getElementById('submit').submit();
}
}
Another reason but less probable is, your active scripting (javascript for example) may be disable.
Verify it just in case:
Internet Options -> Security Tab -> Custom Level -> Scripting -> Active Scripting -> [Enable]
I've just copied your code and it worked for me.
E.g.:
<form id="signup" action="http://google.com">
go
</form>
You also can use onclick="document.getElementById('signup').submit();" or go with a button or input type="submit"
E.g.:
<form id="signup" action="http://google.com">
go
<input type="submit" value="go2">
<button>go3</button>
</form>
Well, there is other ways to do it but I think those are enough!

JSF commandButton action is invoked from javascript even if false is returned [duplicate]

Hey there is a link in my program as shown and onclick it calls the function clearform as shown:
Html Code:
<a class="button" href="Cancel" style="left: 55%;" onclick="clearForm()">Cancel</a>
JavaScript Code:
function clearForm(){
document.getElementById("subjectName").value = "";
return false;
}
return false is not working in this code. actually the first line of the function executed successfully but the return false was failed. I mean page is redirected to url "Cancel".
Change your code as
<a class="button" href="Cancel" onclick="return clearForm()">Cancel</a>
Your problem is you need to return the Boolean.
But, drop all that...
Attach your event unobtrusively...
element.onclick = clearForm;
Use preventDefault(). It is the modern way of acheiving that.
function clearForm(event) {
event.preventDefault();
}
<a class="button" href="Cancel" style="left: 55%;" onclick="clearForm();return false;">Cancel</a>
should work
Please note that if there is a bug or error in clearForm() then "return false" will NOT stop the anchor action and your browser will try to link to the href "Cancel". Here is the logic:
User clicks on anchor
onClick fires clearForm()
There is an error in clearForm() so Javascript crashes and stops all code execution.
return false is never fired because Javascript has already stopped.
If you are relying on a third party JavaScript API (I was using code supplied by Recyclebank to spawn a popup), and the third party API makes an update that breaks the JavaScript, then you'll have problems.
The following will stop the link under normal conditions and error conditions.
<a class="button" href="javascript:;" style="left: 55%;" onclick="clearForm();return false;">Cancel</a>
The return false; somehow needs to be right at the front.
(In ALL situations I've dealt with over the past months - may or may not be a bug).
Like this: onclick="return false; clearForm();"
Besides that, as mentioned by others as well, you need to return it from the onclick, not just from the function.
In your case: onclick="return clearForm()".
Keep in mind that some browser extensions may interfere with proper operation of links. For example, I ran into a situation where someone had both AdBlock Plus and Ghostery enabled. Clicking a simple 'a' tag with an 'onclick="return SomeFunction();"' attribute (the function returned false) caused the browser to treat the click as a page transition and went to a blank page and the loading indicator just kept spinning. Disabling those browser extensions cleared up the problem.
Including this as an answer because this was the first page I landed on from Google.

Use javascript AND PHP in one <input> tag?

I feel like I've looked around for the answer for this question, but most of the responses are very hacky: involving javascript that pops in via AJAX, redirects and other ways of modifying the DOM on the fly.
What I want to do is make the submit button disappear when a user submits a document (javascript) and submit the message via mail (php). The code I have is the following:
<form action="" method="post">
...
<input onclick="removeElements()" id="subButton" class="submit" name="submit" type="submit" value="submit">
The php mail function is in the same document.
Here is the removeElements() function:
var el = document.getElementById("subButton");
el.remove();
document.getElementById("thankYouMessage").setAttribute("style", "display:block");
The submit function works without the javascript call, but when I add the onclick="removeElements()" part, then the javascript part starts working, but the php is no longer executed.
I know that there are other methods for doing this, but in this case, I'm actually curious about why this doesn't function as I had planned. By removing the submit button, am I in effect killing the child PHP process mid(or pre)-execution?
Thanks!
If you add onclick you will have to fire the submit manually.
The other option is add your javascript call code in onsubmit="removeElements()" on the form tag. This way, it will execute your code after executing submit
Related question here
Don't remove the button, rather set visible: hidden or display: none for its style. This way it will still be in the document and will work, it just won't be shown.
When you send the form reloads your page so I suggest:
Using Ajax and only delete button on the response, or
Not generate the button when reloads your page.
Jquery Ajax examples: You can see them here api.jquery.com/jquery.ajax/
Regards.
You could simple use the .hide functionality which JQuery gives you. It's very simple to use and very clean.
Example1 using JQuery:
$("#FormID").submit(function(e)
{
e.preventDefault();
// Hide button
$("#subButton").hide();
// Display thank-you message
$("#thankYouMessage").css("display", "block");
});
Example2 using JQuery:
$(document).ready(function() {
$(".submit").click(function() {
$("#subButton").hide();
$("#thankYouMessage").css("display", "block");
return false;
});
});

Categories

Resources