skip to Main Content

I am using a php contact form on my website.
I have a code to insert an X if field is empty when receiving the mail.

but I can’t accomplish this for < textarea >.

This is the code that works for me if name and telephone field is empty:

$empt = Array('name','telephone');
foreach($empt as $v){
  if(empty($_POST[$v])) $_POST[$v] = 'X';
}

But I can’t accomplish this for the name of my < textarea >.

Does anyone know how to put an X if < textarea > field is empty? Many thanks!

2

Answers


  1. There is an error in your PHP. You forgot to add the textarea to the php array. If your html textarea looks like this: <textarea name="message"></textarea>, then your PHP should include message in the foreach loop, and look like this:

    $empt = Array('name', 'telephone', 'message');
    foreach($empt as $v){
      if(empty($_POST[$v])) $_POST[$v] = 'X';
    }
    

    Sometimes if there are any whitespaces or new lines in your textarea, it won’t be considered empty. Consider trimming it’s value first:

    foreach($empt as $v){
      $_POST[$v] = trim($_POST[$v]);
      if(empty($_POST[$v])) $_POST[$v] = 'X';
    }
    
    Login or Signup to reply.
  2. Although I don’t recommend it, if the PHP script is not correctly handling an empty textarea, you can adjust the value of the form’s inputs using JavaScript when the form is submitted.

    For example:

    document.addEventListener("DOMContentLoaded", function() {
        // Select the form by its ID or class
        var form = document.getElementById("your_form_id");
    
        // Add a submit event listener to the form
        form.addEventListener("submit", function(event) {
            // Prevent the default form submission
            event.preventDefault();
    
            // Select the input element by its ID or name
            var input = document.getElementById("message");
    
            // Check if the input value is empty and set a default value
            if (input.value.trim() === "") {
                input.value = "X";
            }
    
            // Submit the form after updating the value
            form.submit();
        });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search