Search code examples
phpjqueryjquery-form-validator

Change img attribute and disable inputs with jQuery after PHP form validation


I am trying to change the 'src' of an image element and also change the properties of input elements to 'readonly' after a form has been validated and submitted. The validation of the form occurs in PHP so I cannot attach an on submit event handler as it will trigger even if the form has not passed validation. Is there any way to do this without a plugin of some kind?

<html>
 <head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">  </script>
 </head>

 <body>

  <script> 
   $(document).ready(function() 
   {
      $("#button_img").click(function ()
      {
         alert("button clicked");
         $("#course_name").css("background-color", "yellow");
         $("#course_name").attr("readonly",true);
         $("#button_img").attr('src','../images/edit_course.png');
      });
   });    

  </script>

  <form id='design_course'  action="<?php ($_SERVER['PHP_SELF']); ?>" method="post">
   <label id="course_name_label">Course Name:</label>
   <input type=text   id="course_name" name="course_design_name" value="default">
   <button  id="create_course" type="submit" ><img id="button_img" src="../images/create_course.png"></button>  
  </form>

 </body>
</html>

Solution

  • Since the validation logic you're using for this is server-side, the page is going to be changing during a reload. So your logic for conditionally setting values in your HTML would be server-side.

    You can conditionally output to the page from PHP based on any if statement. You're not showing the validation logic, but let's assume for the sake of example that if validation passes then there is a boolean variable called $passedValidation. Then you can do something like this in your code:

    <?php if ($passedValidation) { ?>
        <img id="button_img" src="../images/something_else.png">
    <?php } else { ?>
        <img id="button_img" src="../images/create_course.png">
    <?php } ?>
    

    So note that if the form "passed validation" then the image used is something_else.png instead of create_course.png. So when the page reloads after having passed the validation logic, the user will see the other image.

    The same can be done for other HTML output. How you organize it is up to you, as it could get ugly to re-use this same if/else structure for a variety of attributes on the page. Perhaps you can just have two complete forms wrapped in a single if/else block or something like that.

    Note also that you'll want a default case of false for $passedValidation to handle when the page is first loaded and no form has been submitted at all.