0

嗨,我有一个表单,用户可以在其中将一本书或多本书输入数据库。每当用户输入一本书并忘记输入标题时,就会出现 JavaScript 警报并提醒他输入标题。现在,如果他有两本书或更多本书并且忘记输入标题,则不会显示警报。

这是我的 JavaScript 函数。

function validateForm() 
{ 
 var a=document.forms["submit_books"]["title"].value; 
  if (a==null || a=="") 
    { 
    alert("Please enter a Title"); 
    return false; 
    }


 var status = false;     
 var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
      if (document.submit_books.email.value.search(emailRegEx) == -1) {
           alert("Please enter a valid email address.");
           return false;
      }
}

这是我的 PHP 代码

<form method="post" name="submit_books" onsubmit="return validateForm()" action="<?php echo $_SERVER['PHP_SELF']; ?>">
                <?php for ($i=1; $i<$num_of_books + 1; $i++){
                    echo "<strong>Book # $i</strong><br><br>";
                    ?>


                    <label for="title">*Title</label>: <input type="text" id="title" size="60" name="title[]" autocomplete="off"/><br><br>

              <?php }?>
<input type="submit" name="submit" value="Submit Books">
</form>




我什至尝试将 PHP 数组放入 JavaScript 数组。

     <?
$js_array = json_encode($title);
echo "var title = ". $js_array . ";\n";
?>
var index = 1;
if( index < title.length)
{
    alert("Please enter a Title"); 
    return false; 
} 

必须有一种更简单的方法来做到这一点

4

3 回答 3

1

你应该做

var index = 1;
if( index > title.length )
{
    alert("Please enter a Title"); 
    return false; 
}

由于如果title.length = 0则没有记录,即如果1 > 0则没有标题。

你也可以检查

 if( title.length === 0 )
于 2013-04-18T03:10:34.377 回答
0

你可以这样做:

 <?
echo "var title_length = ". count($title) . ";\n";
?>
var index = 1;
if( index > title_length)
{
    alert("Please enter a Title"); 
    return false; 
} 
于 2013-04-18T03:14:43.350 回答
0

尝试在 html 表单中使用

<label> 
<span>Book Title: (required)</span> 
<input name="book" type="text" placeholder="Please enter your books title" required autofocus> 
</label>

然后使用javascript进行验证

(function() {

    // Create input element for testing
    var inputs = document.createElement('input');

    // Create the supports object
    var supports = {};

    supports.autofocus   = 'autofocus' in inputs;
    supports.required    = 'required' in inputs;
    supports.placeholder = 'placeholder' in inputs;

    // Fallback for autofocus attribute
    if(!supports.autofocus) {

    }

    // Fallback for required attribute
    if(!supports.required) {

    }

    // Fallback for placeholder attribute
    if(!supports.placeholder) {

    }

    // Change text inside send button on submit
    var send = document.getElementById('submit');
    if(send) {
        send.onclick = function () {
            this.innerHTML = '...Processing';
        }
    }

})();
于 2013-04-18T03:23:16.693 回答