August 29, 2012

Disabling form button onClick, and then submitting the form

Question by bevanb

My form lets users submit a poem.

Sometimes, there’s a field for a new user name on that page (if nobody’s logged in). In that case, I want to override the button click so that it signs them up first:

$('#submit-poem').click ->
  $('input[type=submit]').attr('disabled', true)
  if $('#new_poet_name_field').length
    signUp();  // This will submit the poem form after registering
    console.log("A poet was already logged in!")

This used to work fine. But now, when there is no new_poet_name_field, the submit button stays disabled. Returning true used to submit the form. Now, I have to explicitly do $('#new_question')[0].submit() if there is no poet_name_field.

Why doesn’t the form submit when true is returned? My workaround is worrisome; it seems possible that the form might submit twice now: once when I explicitly submit it, and once when true is returned.

Answer by brains911

You should bind to the form ‘submit’ event and use preventDefault/return false when you want someone to sign up instead of submitting the poem. This way there is no need to do any disabling/enabling of buttons.

Answer by Starx

I dislike the idea of not having a form. Its invalid and sure to not follow HTML’s Specification.

Every constructive form elements should be wrap inside a form tag. You can control the submission of form in more than one way.

The code you are using is horrible

  1. WHY?? Is there more than one submit button? The code below disables every submit button on the page, which can be of other forms too.

    $('#submit-poem').click ->
      $('input[type=submit]').attr('disabled', true) 
  2. This is wrong way to check the authenticity of submission, it can be easily manipulated with tools like firebug.

    if $('#new_poet_name_field').length

If finding out if the user is logged in or not that important, then you can quickly send an ajax request to a service page, that gets you that information

$('#submit-poem').click(function() {
    $(this).attr('disabled', true)
    $.post("yourservicepage.php", {}, function(data) {
          // RE suppose, data is the boolean value from server indicating logged in or not
          if(data != true) {
             signup(); //if not logged in then signup

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+


Please fill the form - I will response as fast as I can!