I've built a trivia game using PHP and javascript. Since each question has a time limit, I've not provided a submit button; instead, the user can directly submit the answer by pressing the Enter key. After the enter key is pressed, the user is redirected to another URL which checks if the posted answer is correct, adds 10 points if the answer is correct and then updates the database with the user's points and then redirects the user to the trivia page where they have another question to answer. However, when a user enters the right answer and presses the enter key multiple times without letting the page reload, their answer is deemed as valid by the script and their points are added as any times as the answer was submitted. So, if I hit the enter key 40 times after typing in the right answer, it adds 400 points. I've tried preventing this by using:
$("form").submit(function() {
$(this).submit(function() {
return false;
});
return true;
});
But that doesn't seem to work. How do I disabled the submit action after the data is submitted once until the page is reloaded?
Any solutions using Javascript, Jquery or PHP are welcome.
var isSubmitted = false;
$("form").submit(function() {
if(!isSubmitted){
isSubmitted = true;
}else{
return false;
}
});
One of the solution you have to add to store the submit the information in the database , like for each user bofore adding the value +10 you should check if you have already added the value. The reason i suggest , because any other client side option may fail in one or other case.
Try this Code
$('#form1').submit(function(e) {
$('#send').attr("disabled", "disabled"); // Where #send is the id of ur submit button//
});
include Jquery BlockUI plugin. http://www.malsup.com/jquery/block/ and include the following code in your page.
$("input").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
$("form").submit();
$.blockUI;
}
});
When the user hits enter when a plugin will block the UI and user will not be able to hit enter again untill the page reloads.
Related
I've Googled and searched on SO quite a bit for this unique problem, but not really finding my exact solution.
I have a basic form with X number of inputs. At some point in the form, the user as the freedom to add inputs via button click if needed. When they submit the form, it goes to another page to collect the posted form data, but I want the ability for the user to click "Back" (or send them back programmatically) if the submit fails.
I have error checking setup prior to submit via javascript, but there are other things (such as a PHP mailer) that could fail and I want them to be able to resubmit their data.
The issue of course is when the browser clicks back, it - at best - refreshes the initial form that was in the DOM with input data, but I lose all of the dynamically added inputs.
I want to capture the form/data in a session and have it repopulate the DOM with the submitted version created by the user on click back.
The closest I've come is doing something like this on SUBMIT:
var theForm = $('#myForm');
sessionStorage.setItem('formData', JSON.stringify(theForm.clone(true).html().toString());
And this on postback/click back:
$('#myForm').replaceWith(JSON.parse(sessionStorage.getItem("formData")));
The problem here is I get my form, but not the data! Do I need to iterate over each input to get my data put back in the recreated form?? Why doesn't it grab the data when .clone(true)ed?
Here's the answer I ultimately got to work.
Upon form validation, I set the session to hold the form data like so:
var theForm = $('#MyForm');
sessionStorage.setItem('formHTML', JSON.stringify(theForm.clone(true).html()));
theForm.find('input,select,textarea').each(function(){
sessionStorage.setItem(this.name,this.value);
});
Then, when the DOM loads again, I have this that checks for the session and populates the form with data if it exists:
$(document).ready(function(){
if (sessionStorage.getItem("formHTML")) {
$('#MyForm').html($.parseJSON(sessionStorage.getItem("formHTML")));
}
$('#MyForm').find('input,select,textarea').each(function(i,elem){
var sessItem = elem.name, sessValue = '';
if (sessValue = sessionStorage.getItem(sessItem)) {
if(elem.type=='radio' && elem.value==sessValue){
alert(elem[i].type+' has value of "'+elem[i].value+'"');
$('[name='+sessItem+']')[i].prop('checked',true);
}
else if(elem.type=='textarea'){
alert(elem.type);
$('[name='+sessItem+']').val(sessValue);
}
else
{
$('[name='+sessItem+']').val(sessValue);
}
}
});
});
At the moment I'm working on a project that requires the submission of a form for 'voting' for specific posts. At the moment clicking on the submit button works as it should, although if the button is clicked more than once, it does exactly that - submits the POST variables more than once causing them to be able to 'vote' for the item multiple times in one set of clicks.
I've looked at every jQuery code example I can find to solve this but nothing works. It works to disable the button, but after that the redirection page that grabs the data and runs the queries returns an error as nothing has been submitted. In short, it seems to disable the button but at the same time disable the information from being submitted.
Here's my jQuery code:
$('#vote').submit(function(){
$(this).children($btn).attr('disabled', true);
return true;
});
Any help would be great.
Thanks.
Use jquery .one
Description: Attach a handler to an event for the elements. The handler is executed at most once per element.
$(document).one("click","#vote",function(){
$(this).children($btn).attr('disabled', true);
return true;
});
Probably your best option is to only allow a single submission and adjust the button appearance some other way:
var submitted = false;
$('#vote').submit(function(){
if(submitted) {
// cancel additional submits
return false;
}
submitted = true;
$(this).children($btn).val('Please wait...');
});
you could add an click event. Instead of using submit button use a button click event.
the code might look like this
$($button).click(function(){
$(this).attr("disabled","disabled");
$($form).submit();
});
Jquery's on and off can be used here.
for example after submission,you can completely disable the click by
$('#vote').off('click');
and then switch it back if you want by
$('#vote').on('click');
I'm creating an inline editable table using jQuery and the editable plug-in.
It works well so far but will only submit and save to the database upon pressing ENTER. I found a thread on here which helped me to tab between boxes but it doesn't submit the data when TAB is pressed.
My code that allows me to switch between boxes is as follows:
$('.editScheduleRow').bind('keydown', function(evt) {
if (evt.keyCode==9) {
var nextBox='';
var currentBoxIndex=$(".editScheduleRow").index(this);
if (currentBoxIndex == ($(".editScheduleRow").length-1)) {
nextBox=$(".editScheduleRow:first"); //last box, go to first
} else {
nextBox=$(".editScheduleRow").eq(currentBoxIndex+1); //Next box in line
}
$(this).find("input").blur();
$(nextBox).click(); //Go to assigned next box
return false; //Suppress normal tab
};
});
To submit using ENTER I use this:
$(".editScheduleRow").editable("../../includes/ajax/save-schedule-row.php", {
"submitdata": function ( value, settings ) {
return { fieldname: this.getAttribute('fieldname'), rowID: this.getAttribute('id') };
},
});
I also found a thread with a suggestion but it didn't work for me: jEditable submit on TAB as well as ENTER
Please let me know if you need any more information.
My original answer was based on reading the documentation of jQuery Editable, which is a jQuery extension that is similarly named, but not the same as jEditable from the question. Let's try again with the correct library.
The problem is that you are moving the focus away from the input box when pressing tab, but when the focus is moved away from it, it doesn't save the contents. To illustrate this, try this: click one of the fields and edit it, then click elsewhere on the document. You'll see that the value in the table - and this is what you where simulating using the blur() jQuery function on the element.
There are (again) two ways to solve this problem. First, we can modify what the program does when a field loses focus:
[..]
"submitdata": function ( value, settings ) {
return { fieldname: this.getAttribute('fieldname'), rowID: this.getAttribute('id')
};
"onblur": "submit";
},
[..]
This has the effect that when doing the experiment I described above to help you understand why it wasn't working, you'll now also see that it gets saved. This may not be what you want. In that case, you can instead make sure that you trigger a submit instead of a blur:
replace this line:
$(this).find("input").blur();
by this one:
$(this).find("form").submit();
Now the experiment will no longer cause the value to be changed, but it's no longer an accurate simulation of what we're doing and when pressing tab the value will be changed.
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.
Am doing a contact management site in codeigniter, i have a function which delete the contact based on id.
For example the page will have all contacts listed. And each contact will have a link saying delete near it. The link will be to the function passing the id, like:
www.site.com/index.php/action/delete/23
So i want a confirmation box to ask user, yes or no for each link. So if user press yes it will be deleted and otherwise nothing happens. Hope I'm clear.
You need a javascipt prompt:
Your JS
function confirm_delete(){
var r=confirm("Are you sure?");
if (r==true){
//Do somthing
}else{
//cancel
}
}
Then add an onclick event to your link.
Delete
If you want something shiny and less intrusive may i suggest jquery with one of a multiple of confirm dialog plugins.
http://projectshadowlight.org/jquery-easy-confirm-dialog/
http://kailashnadh.name/code/jqdialog/
You could have a confirmation page with a form to post back to the same url. In the controller check whether the form has been submitted. If it has, delete the contact. If not, display the confirmation page.
function delete($id)
{
if ($this->input->post('confirm'))
{
$this->contact_model->delete($id);
}
else
{
$contact = $this->contact_model->get_contact($id);
$this->load->view('delete_confirm', array('contact' => $contact));
}
}
If you don't like the idea of an extra page you could use some javascript to display a confirmation box and do an AJAX post if the user confirms.
Edit :
Just as an aside, what I'd avoid doing is implementing the delete through a HTTP GET. A spider or bot following the delete links could inadvertently delete all the contacts. Its better to use HTTP POST.