I have this function in my .aspx file in the beginning
<script type="text/javascript">
function onPageLoad() {
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
}
</script>
Now in my javascript I have a function called validate that validates some conditional fields on the form.
function validate() {
// calls alert
alert("Field is blank");
}
Now I also have this function called EndRequesthandler which simply calls my validate.
function EndRequestHandler() {
validate();
}
Now for some reason, if I leave a field blank then popup pops tiwce when I click a SUBMIT button which is under a update panel and does asynchrous postback. I cannot have this field under Required because its required based on another drop downlist. so its conditional. Any help is appreciated.
This seems like an odd implementation of essentially trying to run a client side validation script before the form is submitted if I'm not mistaken?
I suggest you try implementing James McCormack's answer found here: How to capture submit event using jQuery in an ASP.NET application?
Related
I've just wrote some validation code so as to check if either of my radio buttons from my web form have been selected before they are submitted. I've just starting learning php as I want to be able to store the value of each radio button in a .csv file.
Because I have my action attribute set to trigger a php script, I get my alert box, but as soon as I click OK after pressing submit the browser goes straight to the php script (inevitably).
Is there a way I can return to my initial index.html after the alert message?
I have not actually written any php as yet, so would this go in the php script or the javascript?
Heres my code so far:
$("#submit").on("click", function() {
var radio = $("input[type=radio][name=emotion]")[0].checked;
var radio2 = $("input[type=radio][name=emotion]")[1].checked;
var radio3 = $("input[type=radio][name=emotion]")[2].checked;
if(!radio && !radio2 && !radio3) {
alert("You must select at least one word!");
}
else {
alert("Please rate the next item!")
}
});
In Jquery you should use .submit() function to validate a form.
Then to avoid to submit the form you can use the function event.preventDefault()
And if you want to go to the index you can use window.location = "yourURL"
You must use form.onsubmit().
For example, if your form's name is myForm:
document.forms['myForm'].onsubmit = function()
{
if (this.elements['emotion'].value)
{
alert("Please rate the next item!");
}
else
{
alert("You must enter at least one word!");
return false;
}
}
And after alert "Please rate the next item!" form will be send.
Actually you can use jquery $.post() , an easy solution is just to post your php page without leaving index page.
http://api.jquery.com/jquery.post/
$.post( "yourpage.php" );
You probably have the input type of the submit button as submit? Set this to button, so the action doesn't take place and only jQuery is executed.
But then you have to submit the form by jQuery when validation was successful:
document.myFormId.submit();
I would like to keep a button grayed out (ie. non-clickable) until all javascript (client-side) validations are passed.
First of all, I have set the button's "Enabled" property to false, meaning it is greyed out by default when the page loads. And oppositely, here is some js code (we always like to see some code) that enables the button:
var SubmitButton = document.getElementById('<%=SubmitButton.ClientID %>');
SubmitButton.disabled = false;
I have a series of validations taking place in a javascript/jquery block on my page:
<script type="text/javascript">
//Client-Side validation script:
$(function () {
$("#<%=OtherBox.ClientID %>").blur(function () {
//Validation logic goes here...
});
//etc... there are many more.
});
</scipt>
I guess this is more of a javascript question than anything. How do I structure my javascript code to accomplish what I want to do here? In other words, how, when, and where should I set the disabled property of the button to false in my javascript?
One thought was to have a function at the end of my script, which contains all of the logic from each of my validations, and sets the button to be non-greyed out only if all of the logic passes. But using this method, there is no code reuse -- I would simply be copy pasting in all of the logic from each validation function into one mega function. Plus, it would only execute once, which is not good. The button should be able to be re-grayed-out if they change their input data to be invalid.
After thinking about this for a little while longer than I'd like to admit (such a simple problem :[) why don't I just create a loop at the end of my Javascript that is:
while(SubmitButton.disabled = true)
{
//Perform all validation logic from each validation function -- yes it is painful to reuse all of them again, but it is very straightforward.
//If all checks pass, then break out of the while loop by setting SubmitButton.disabled = false.
}
I'm looking to submit form details using method="POST" to an external URL, then redirect the user to a 'Thank you' page after successfully completing the form.
My sample HTML/Javascript is as follows, however the page is not redirecting to Google.com as intended. Any help on fixing this would be much appreciated!
HTML:
<form action="externalURLhere" method="post" name="theForm"
id="theForm" style="margin-bottom:0px;padding:2px;background-color:#e0e0e0;" onSubmit="return
MM_validateForm(); return redirect();">
JavaScript:
function MM_validateForm() {
if ( !jQuery('#theForm #FirstName').val() ) {
alert('Please input your first name.');
jQuery('#theForm #FirstName').focus();
return false;
}
if ( !jQuery('#theForm #LastName').val() ) {
alert('Please input your last name.');
jQuery('#theForm #LastName').focus();
return false;
}
if ( !jQuery('#theForm #daytimephone').val() ) {
alert('Please input your phone number.');
jQuery('#theForm #daytimephone').focus();
return false;
}
if ( !jQuery('#theForm #Email').val() ) {
alert('Please input your email.');
jQuery('#theForm #Email').focus();
return false;
}
if ( !jQuery('#theForm #BID').val() ) {
alert('Please select your preferred campus.');
jQuery('#theForm #BID').focus();
return false;
}
if ( !jQuery('#theForm #programs').val() ) {
alert('Please select your preferred program.');
jQuery('#theForm #programs').focus();
return false;
}
if ( !jQuery('#theForm #How_Heard').val() ) {
alert('Please select how you heard about us.');
jQuery('#theForm #How_Heard').focus();
return false;
}
return true;
}
// ]]></script>
<script type="text/javascript">
function redirect() {
window.location = "www.google.com";
return false;
}
</script>
When the user clicks the submit button, onsubmit event occures, and, depending on the return value of the function binded to the event, the form submits (return true) or does not submit (return false);
The function may be binded to the event using HTML:
<form onSubmit="if(/*some validation here*/){return true;} else {return
false;}"></form>
or in javascript script itself:
form1.onsubmit=function(){if(/*some validation here*/){return true;}
else {return false;}}
Generally, it does not matter;
You know, the function's body is executed until the "return" occures. Then it immediatly stops and the return value is passed to the function invoker. So, what you have wrote in the onSubmit="" HTML tag attribute is the equivalent of the following JS code:
form1.onsubmit=function(){
testPassed=validate();
return testPassed;
someValueRedirectFunctionReturns=redirect();
return someValueRedirectFunctionReturns;
}
So, you can see, that no matter if the form data test is passed or not, because your validate() function's return value (true if form is okay and false if user has entered bad data) is immediatly then returned in the event function. So, your redirect() function cannot occur, because the onsubmit event handler function is stopped and the value is returned;
To make this work, you should modify the code:
form1.onsubmit=function(){
if(!validate())
return false; //test failed, form is not passed, no need to redirect to "thank you page".
else
redirect();
}
So, the redirect function will be called if the form validation test is passed. Right here we ran in an another problem.
The only way, if the onsubmit event handler function is defined, to submit the form is to return true; -- return from the function, means stop it and proceed executing from the where it was called. When you change the window.location propterty of the page in the function, redirection occurs immediatly, so the function even do not return; -- JavaScript execution immediatly interrupts, and the new page starts loading -- of course, no data can be passed via form submition;
So, you have to
Submit form (if the data is valid) -- return true;
Somehow redirect (this means, to continue execute your JS code at another page) from the page where the form is submitted.
And... that is not possible.
You can't continue executing the JS code after the form is sent because:
The event handler function has returned. That means it is stopped.
The form is sent, and an another page is now loading. The JS code of the previous page is lost, and cannot be executed anymore.
This means, that you can't affect the behaviour of the page that you are loading (in synchronous mode) from the page, that has started the loading.
And you can't make the new page redirect to the page you want ("thank you" one).
Usual form sending is just loading a new page with additional parameters. E. g. you can't modify the page that a link on your page is following to;
Anyway, there are still several ways to acheive what you want:
If YOU own the page, where the form is submitted, you may just receive the data of the form and immediatly send the redirection header. E. g., via PHP on the server side.If the page IS NOT YOURS (you can't modify neither the server, nor the page, nor anything on the server side), then you have to work with the form in slightly different way(s):Use frames or floating frames, either loading the data into the frame(s) by the javascript code itself, or by loading another page (from the same server on which the form page is located), that you have permission to modify, and modify it. E. g.:In one frame, make a form where the user actually enters data;In another frame, make another form which contains the same fields that the first does, but hidden ones;Do not submit the first form, but pass the data from to the second form, and submit() the second one;Redirect the first frame (or the whole page) to the "thank you" page;The first frame may be even hidden (CSS: display:none) -- that won't affect the functionality.Use AJAX. That is a special technology of making HTTP request (submitting form!) from the javascript code without reloading the actual page. There may be some problems, if you try to send data to the externalURLHere page, if it is not yours. If so, you may create a "router" page on your server, which will receive the data sent by the form and route it to the target, externalURLHere page. Then you may even...Don't use AJAX. Just make the router page (when I say "page", I mostly mean a PHPscript, or another cgi technology), which will also display the "Thank you" HTML document.And so on...
I've tryied to make as complete answer, as possible, I hope it has helped.
P. S. Sorry for my English.
P. P. S. My first answer on Stack Overflow -- I may be doing something wrong, sorry.
It's tough to pin down the exact reason why it isn't working without your full code and more specific requirements.
For instance, if you are submitting to a php file, you can do the redirect in that external php file using:
header('Location: http://www.example.com/');
If you are simply submitting to another html file, you could use Ajax: How to redirect using AJAX?
Try to add protocol
window.location = "http://google.com";
I am using ASP.NET 3.5, and the jquery.hint.js plugin. It works great, with one small problem. I have various ASP.NET validators on the page and when the page fails to validate, client-side, all of the textboxes that contained hint text are now blank. This is confusing for the end-user because their are no field labels. To see the hint text, they must click in and out of the field and it re-populates.
Not sure if it makes a difference, but these fields are wrapped in an ASP.NET AJAX UpdatePanel. The reason for the update panel is to do some asynchronous calls for dynamic field updates like auto-populating the state dropdown based on what country you choose. The form is submitted via postback.
I need a way to call the hint javascript against these fields after the validation fails on the client side. How can I do this?
Here is an example of the client side code that executes the hint plugin against the various fields on the page:
<script type="text/javascript">
$(document).ready(function () {
// Add handler function to UpdatePanel's events
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
PageLoad();
});
function PageLoad() {
RetainState();
}
// This function handles the UpdatePanels' EndRequest event.
function EndRequestHandler(sender, args) {
if (args.get_error() == undefined) {
RetainState();
}
else { // there was an error
alert("There was an error" + args.get_error().message);
}
}
function RetainState() {
// Add hint to textboxes.
$(":text").hint();
$("textarea").hint();
}
</script>
One last thing: I thought I had already fixed this problem by adding the following code to the Page_Load method in the code behind, but if it was working before, it is not now:
// This will call some javascript after a form validation fails
// and keep the hint text in the form fields.
if (!Page.ClientScript.IsOnSubmitStatementRegistered("KeepState"))
{
string script = "RetainState()";
Page.ClientScript.RegisterOnSubmitStatement(Page.GetType(), "KeepState", script);
}
Thanks,
Tod
I wrote a javascript function to go to a particular page if it came from a particular page.
Function:
function proceed()
{
if( document.referer == "http://abcd.com/index.php?action=SignUp")
{
return document.location.href = "http://abcd.com/editprofile.php?action=editprofile";
}
}
Submit button for a form in current page(b):
What i want is to go through a sequence of pages a->b->c , where a is previous , b is current , and c is next in my case. b has a form, on submitting values to the form, it should also call the javascript function and then go to the page c.
Can anybody help me find out where is the mistake? Any help would be highly appreciated. Thanks.
Since you have a form I guess there's also some php/cgi script that will handle the form's data!?
In that case your form won't continue to that script if you override your submit button via javascript in such way that it loads another page (other cases like validation do work that way, of course).
So
Your submit button has spaces next to the onclick attribute: onclick = "javascript... should be onclick="javascript....
Your function proceed() should return true for the submit to perform.
Even after all syntax correction, there's still something odd. After all, you can only give one "next page" functionality to your submit button. So what should the form call:
your php or cgi script? Then you can build a redirect to page "c" into that one.
your page "c"? Then what do you need the form for?
both, but independently? In that case I suggest a javascript popup from proceed() displaying page "c" and returning true so the form continues with its script.
To be more accurate you will have to provide more of your application's code.
Solution seems to be the following. Use the submit attribute for your button:
<button type="button" onclick="proceed(); alert('You are not authorized to execute this action!');">Click Me!</button