簡體   English   中英

檢查PHP數組在JavaScript中是否為空

[英]Checking if a PHP array is empty in JavaScript

嗨,我有一個表單,用戶可以在其中向數據庫輸入一本或多本書籍。 每當用戶輸入一本書而忘記輸入書名時,就會出現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; 
} 

一定有更簡單的方法可以做到這一點

你應該在做

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

由於title.length = 0時沒有記錄,也就是說,如果1> 0則沒有標題。

您也可以檢查

 if( title.length === 0 )

您可以這樣做:

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

嘗試在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';
        }
    }

})();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM