Twobears
Twobears

Reputation: 109

validate input is not empty on submit

The following echo statement creates an empty textbox and a submit button using php.

    echo"<td><form id=\"edit\" name=\"edit\" method=\"post\" action=\"../assets/modules/coursemanager/process.cm.php\" onsubmit=\"return check_edit();\">
    <input type=\"text\" size=\"3\" id=\"edit_places\" name=\"edit_places\" value=\"\" />
    <input type=\"hidden\" name=\"sid\" value=\"".$sid."\" />
    <input type=\"submit\" name=\"Submit\" value=\"edit places\" /></form></td>";

This is the validation JavaScript I am using, but the above form is ignoring it.

  function check_edit(){
      var notempty=document.forms["edit"]["edit_places"].value;
        if(notempty==null || notempty==""){
           alert("Please enter the new number of available places and try again");
           return false;
      }else{    
           return true;
      }
  }

I would be very grateful if someone could show me my error.

Upvotes: 0

Views: 155

Answers (2)

Twobears
Twobears

Reputation: 109

I used an else statement in the processing script which does the trick and dispensed with the check_edit function.

    if($_POST['edit_places']!== ''){
    $id=$_POST['sid'];
    $z=$_POST['edit_places'];
    $sql = "UPDATE xtra_session SET places=$z WHERE xtra_session.id=$id";
    $add = $modx->db->query($sql);
    $msg = ($add? "available places has been updated" : "error: ".mysql_error());
    }
    else {
    echo "Please enter a number of places to change"; 
    }

Thank you for your valued suggestions.

Upvotes: 0

knrz
knrz

Reputation: 1811

You can check the length of the input.

value = document.forms["edit"]["edit_places"].value.replace(/\s+/g, '')

if (value.length > 0) {
  return true;
} else {
  alert("Please enter the new number of available places and try again");
  return false;
}

Upvotes: 1

Related Questions