I have two questions about Javascript:
How can I prevent my fields from being cleared when I try to cancel a form submission by returning false in the onsubmit function?
I have a form, which has the onsubmit value "return validate()". If validate() finds an error in the fields, it returns false, which should stop the form submission. It does, but all my fields get cleared, and the browser ignores the Javascript I run before the return statement, like document.write. Example:
function validate() {
//If there's an error:
document.write("Error!");
return false; }
How can I prevent this?
Can I have a form inside a prompt window (a popup)?
I have not only failed to put several inputs in one Javascript prompt(), but also to put a submittable form inside a prompt window. I have a feeling that this is not possible with Javascript, and would like to know how to achieve this.
Thanks.
1) Use alert or elements inner text to display error than document.write. Document write clear the DOM and write the specified content so you will loose the form data.
Use
function validate() {
//If there's an error:
document.getElementById('errorDiv').innerText = 'your error message';
return false; }
2) If you talking about native prompt window, then answer is no. If you talking about JS pop--up then yes, u can put form inside pop up. Pop is just like any browser window where u can show any html page.
onsubmit="return validate()" is fine. There must be another reason your fields are being cleared. What does your validate() function do? Unless your submit button is actually a reset() button - or there's a JavaScript error somewhere and the form is being submitted regardless (check the JavaScript console in the browser).
Related
yes this question is asked some times. but I can't find an answer for my problem.
I've posted my question here because it is more php / javascript related then drupal I guess.
So basically I have a form that is validated and on the submit part I have a ( drupal hook ) function in php where I can add / modify code.
This function catches the form fields and stores them in the database.
This means that the fields are filled correctly so I want to implement something here that opens a new tab or window for the user without closing the current one.
So I know you can't call javascript from php to use something like window.open() but is there anyway I can make it so that this window.open() is called?
I'm also open for a bit different approach if you have any.
You can use an anchor element to both submit a form and open a new window:
<script>
function submitMyForm()
{
// Validate form fields here
// ...
// If form is valid, submit it
myForm.submit();
}
</script>
Submit Form
I've got a bit of a weird problem.
I'm creating a location based web app that is using a javascript function to get a user's GPS coordinates. I have a form with a submit button, and when that submit button is clicked, the function is called (onclick='getCoords()"). The javascript then sets that values of two hidden fields (latitude and longitude) to the GPS coords.
My issue is this: PHP is 'beating' the javascript in the sense that the field values aren't being set in time, so that each value becomes a 0. I've done a bunch of testing, and this is definitely the issue. If I do something like set a seperate button to run the javascript function, the run the form everything works fine.
Any ideas on how to solve this problem?
Gists:
https://gist.github.com/2425419
https://gist.github.com/2425394
https://gist.github.com/2425391
Along the lines of what Volkner said, block submit using a submit handler (call preventDefault), then submit at the end of itsWorking. You can either call .submit() to do the submission, or use AJAX.
I think the crux of your problem is that an <input type="image"> will submit a form just as sure as <input type="submit"> will.
However, to fix this as is, add event as a parameter to both the call and declaration of getUserLocation(event).
Then edit your JavaScript as follows:
function getUserLocation(event) {
event.preventDefault(); // prevents form from submitting
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(itsWorking, notWorking);
}
else {
alert("Dang! Your browser doesn't support finding your location, use the zipcode method below.");
}
};
function itsWorking(position) {
var lat = position.coords.latitude;
var longi = position.coords.longitude;
var finalLat = Math.round(lat*1000000)/1000000
var finalLong = Math.round(longi*1000000)/1000000
$("#longi").val(finalLong);
$("#lati").val(finalLat);
document.getElementById('findoneform').submit(); // submits form since we were successful
};
But like I originally stated, it seems if you used an img tag instead of <input type="image">, that would prevent the form from sending in the first place (and maybe you did this on purpose, because you wanted to have two ways to submit the form?).
This issue happens because the page unloads (submits the form) before the geolocator's done doing its thing, but this way, we stop the form from submitting, and itsWorking() only gets called AFTER the geolocator has done its thing, so we don't submit the form until the end of itsWorking() when we've done everything we wanted to do.
I have a simple form which accepts a Title and a Contents variable from a textbox and a textarea. The form will send its data to a file called add-post.php. However, I am looking for a way to alert the user that either the textbox or the textarea has invalid data (is empty) in case they click the submission button.
I was thinking that an alert() popup box would be the best idea because it doesn't redirect to any other page and the user never loses their data (imagine they entered a whole lot of text but forgot a title. Sending the data to add-post.php and performing the check there will result in loss of data for the user).
However, I'm not sure how to actually implement the alert() popup. How would I make it so that the check is done AFTER they have clicked the submit button but BEFORE the data is sent off to the next file. Any advice is appreciated.
On your form add something like this
<form name="frm1" onsubmit="InputChecker()">
Then in javascript
<script type="text/javascript">
function InputChecker()
{
if(document.getElementById({formElement}) != '') { // not empty
alert("This element needs data"); // Pop an alert
return false; // Prevent form from submitting
}
}
</script>
Also as others have said jQuery makes this a little bit easier. I highly recommend the jQuery Validate Plugin
Some people do find the alert box "annoying", so it may be better to append a message into the DOM to let the user know what needs to be fixed. This is useful if there are numerous errors as the errors will be more persistent allowing the user to see all the things they need to be fixed. Again, the jQuery Validate plugin has this functionality built in.
Attach an onsubmit event to the form, and return false; to stop the submission if checks fail.
Form validation with Javascript. Or easier with jQuery.
Basically, validate the form when the submit button is clicked (with an onsubmit handler), and then use an alert() box if needed. By the way, people usually hate alert boxes.
You have a number of options when it comes to client side validation. This is just one.
<form id="tehForm" method="post">
<input type="text" id="data2check" >
<input type="button" id="btnSubmit" />
</form>
<script type="text/javascript">
function submit_form(){
if(document.getElementById("data2check").value!="correct value"){
alert("this is wrong");
}else{
document.getElementById("tehForm").submit();
}
}
</script>
For a more indepth example check out this link
So here's my situation: I have a form that validates with PHP. I want to make it so that if the form fails validation, the user is forced to click through a confirmation dialog before they navigate to another page (the form is fairly large and they don't want to accidentally leave it before it's saved). I'm going about this like so:
see updated function below,
Basically use php within the function to either set the body to present the confirmation or do nothing depending on the error status of my form. Nothing happens when the form isn't submitted and I click a link, good. When the form is displaying errors and I click a link the confirmation dialog will appear but canceling it causes it to reappear. If I cancel it a second time the page request will go through even though it's not supposed to. I'm not that familiar with javascript so I'm not sure what's going on. Is there a better way I should be going about this?
Edit: I figured it out, it was a combination of things. The first was a really dumb mistake on my part: I was calling the onlick on both tags AND the tags for each link in my list, hence why the box popped up twice.
the second piece was that even though my function already returns bool, the onclick requires an explicit return declaration. I was doing:
<a onclick="forceConfirm();" href="somepage.html">Blah</a>
When it should have been:
<a onclick="return forceConfirm();" href="somepage.html">Blah</a>
Then just edit the PHP so that forceConfirm always returns true when the form hasn't been submitted, bypassing the confirmation:
function forceConfirm(){
<?php
if($form->errorStatus){
echo 'if(confirm("Are you sure you want to navigate away from this page? All unsaved changes will be lost.")){'."\n".
'return true;'."\n".'}'."\n".
'else{ return false;}';
}
else{ echo 'return true;';}
?>
}
Now I just need to figure out how to use jQuery to apply this to all links without having to put onclick events all over the place....
You can use confirm() like this:
if(confirm("Are you sure you want to proceed?")){
document.location = 'confirmed redirect url...';
}
else{
document.location = 'cancel redirect url...';
}
Then you'd wrap that in the same PHP block as in your example, displaying it if necessary and hiding it if not.
I think I got a classic problem but I was not able to find a working solution so far.
I have got a form , the user clicks "Send" and everything works fine using a PRG pattern and doing both client-side and server-side validation.
The problem arises when any user (let's assume he entered valid inputs) clicks more then once quickly before the server script ends its execution...
I do not get any duplicated entry because I took care of that but the browser does not go to my "thanks for submitting page".
Instead it re-submits the same page with the same values and what I get are the custom errors I set to warn the user he is trying to enter details already stored in the database. The details sent in the first place are all in the database but the user has no chance to know that.
I tried to disable the submit button on a submit event using jQuery but in that case the data are not submitted.
HTML
<div id="send-button-container">
<input id="send-emails" type="submit" name="send_emails" value="Send"/>
</div>
jQuery
$(document).ready(function(){
$('#mail-form').submit(function(){
$('#send-emails').attr('disabled','disabled');
});
});
I am wondering if I can force a submission using Javascript after disabling the button and also how to deal with UAs with Javascript disabled
Thanks in advance
Depending on server-side language, the submit button being disabled could cause problems. This is because disabled elements are not POSTed to the server. Languages like ASP.NET require the button value to be submitted so it knows what event handler to fire. What I usually do is hide the submit button, and insert a disabled dummy button after it, which appears identical to the user. Then in your onsubmit handler, you can return false and submit the form programmatically...
$('#mail-form').submit(function(){
var btn = $('#send-emails');
var disBtn = $("<input type='button'/>").val(btn.val()).attr("disabled", "disabled");
btn.hide().after(disBtn);
this.submit();
return false;
});
Contradictory to the other up-voted answers, please note that you do not need to explicitly return true from your submit handler for natural form submission: http://jsfiddle.net/XcS5L/3/
I assume this means you are depending on the value of the submit button to service the request? That is you are checking
$_REQUEST['send_emails'] == 'Send';
This is not good practice. You should never depend on the value of the submit button because that is the just what is displayed to the user. Instead, you should add a hidden input that contains the event you want to fire. After the form is submitted, you don't need to care what the value of the submit button is and you can disable it. All other non-disabled data in the form is still submitted.
You can indeed force the submission after disabling the button.
$(function () {
$("#mail-form").submit(function () {
$("#send-emails").attr('disabled', 'disabled');
window.location = '?' + $("#mail-form").serialize() + '&send_mails=Send';
return false;
});
});
Server side set a $_SESSION variable that keeps track of the last time they made a submission and block submissions within a certain time.
<?php
session_start();
if (isset($_REQUEST['send_emails'])) {
if (isset($_SESSION['mail_sent'])
&& strtotime($_SESSION['mail_sent']) < strtotime('5 seconds ago')
) {
redirect_to_thanks();
}
do_post();
}
function do_post() {
if (do_validate()) {
$_SESSION['mail_sent'] = time();
redirect_to_thanks();
}
else {
yell_at_user_a_lot();
}
}
?>
You have to return true; You could try this if u want a simple button to submit the form.
$(function(){
$('#submitID').one('click',function(){
$('#formTobeSubmitted').submit();
$(this).attr('disabled','disabled');
})
});
On server side, generate a random number into each form, store the number when the form is submitted, and discard the submit if that number has already been stored earlier. When the user has disabled javascript, this is the best you can do. (Concurrency issues can be tricky as the two identical requests are handled at the same time - make sure you use some sort of locking mechanism, such as a table with a unique field or the flock() command in PHP.)
On browser side, just set a flag when the form is submitted, and discard all later submits:
$('#mail-form').submit(function() {
if ($(this).data('submitted') {
return false;
} else {
$(this).data('submitted', true).addClass('submitted');
}
});
You can use the submitted class to make the buttons gray or something. This has a few advantages to simply disabling them; Josh already said one. Another is that Firefox likes to remember disabled states when you hit refresh, which can cause your users getting stuck in certain situations.