0

I have a form that deletes a a value once the user has confirmed the action via a javascript confirm. This works well but I would also like the script to alert the user if the value was empty therefore stopping the script from running altogether.

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

I am not sure what is the best way to implement this (I'm fairly new to javascript).

4

3 回答 3

0

You can test the dropdowns selected value like this:

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;
    }
}
于 2013-01-18T18:34:13.670 回答
0

Simply check of the form element has a value, and branch accordingly.

if (document.getElementById("audit_id_select").value) {
  // select box has a selected value
} else {
  // select box has no selected value
}
于 2013-01-18T18:34:45.397 回答
0

For your select box, you can check if the user has not selected a value by testing if the selectedIndex property of the checkbox is 0. So first you will get a reference to the <select> element with document.getElementById and then test that property:

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;
    }
}
于 2013-01-18T18:35:22.977 回答