如果值为空则Javascript提醒,如果不为则删除确认

时间:2013-01-18 18:28:49

标签: 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很新)。

3 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分:0)

只需检查表单元素是否有值,并相应地进行分支。

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

答案 2 :(得分:0)

对于您的选择框,您可以通过测试复选框的selectedIndex属性是否为0来检查用户是否未选择值。首先,您将获得对<select>元素的引用使用document.getElementById然后测试该属性:

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;
    }
}