2013-01-18 78 views
0

我有一個表單,一旦用戶通過javascript確認確認操作,就會刪除一個值。這個效果很好,但我也希望腳本提醒用戶該值是否爲空,因此停止腳本完全運行。如果值爲空,則爲Javascript提醒,如果不是,則刪除確認

<script> 
    function delete_confirm() { 
     var msg = confirm('Are you sure you want to delete the selected audit'); 
     if (msg == false) { 
      return false; 
     } 
    } 
</script> 


<form id="audit_control_form" method="post" 
    action="<?php echo $_SERVER['PHP_SELF']; ?>"> 
    <select id="audit_id_select" name="audit_id_select" style="width:150px"> 
     <option value="">Please select</option> 
     <? while ($row = mysqli_fetch_assoc($result)) { 
      if ($row['dateEnd'] == '0000-00-00') { 
       $dateEnd = 'Present'; 
      } else { 
       $dateEnd = date('d-m-Y', strtotime($row['dateEnd'])); 
      } 
      echo '<option value="'.$row['auditID'].'">'.$row['auditName'] 
       .' (' . date('d-m-Y', strtotime($row['dateStart'])) 
       .' - '.$dateEnd . ')</option>'; 
     } ?> 
    </select> 
    <input type="submit" name="audit_delete_submit" 
     onClick="return delete_confirm()" value="Delete" /> 
</form> 

我不知道什麼是最好的方式來實現這(我是相當新的JavaScript)。

回答

0

可以測試選擇的值這樣的下拉菜單:

function delete_confirm() { 

    if(document.getElementById("audit_id_select").value == "") 
    { 
     alert("Please select an option"); 
     return false; 
    } 

    var msg = confirm('Are you sure you want to delete the selected audit'); 
    if(msg == false) { 
     return false; 
    } 
} 
+0

這樣做的伎倆,謝謝 – tatty27

0

只需檢查表單元素具有值,並相應地分支。

if (document.getElementById("audit_id_select").value) { 
    // select box has a selected value 
} else { 
    // select box has no selected value 
} 
0

爲了您的選擇框,你可以檢查,如果用戶沒有選擇的測試值,如果複選框的selectedIndex屬性爲0,所以首先你會得到與document.getElementById然後到<select>元素的引用測試該屬性:

function delete_confirm() { 
    var selectBox = document.getElementById('audit_id_select'); 
    if (selectBox.selectedIndex === 0) { 
     alert("No value selected"); 
     return false; 
    } 

    var msg = confirm('Are you sure you want to delete the selected audit'); 
    if (msg == false) { 
     return false; 
    } 
} 
相關問題