Stefan Stefko Stefan Stefko - 1 year ago 59
jQuery Question

Not deleting data from Email select Box

I have working script which is sending emails from website to some array of emails.

Problem is: If the user forgot to choose value from select box (value = email to in PHP array) my script is throwing alert "Choose a value!" but all data wrote by the user will be deleted from all select boxes.

Is there any way to avoid it?


function formSubmit() //onclick "Submit" button
var selectedValue = document.getElementById("sendTo").value;

alert("Choose a value!");
//working ajax script which is sending emails


<label class="company_emails">
<select id="sendTo">
<option value="99">Choose a department</option>
<option value="0">Justice</option>
<option value="1">Injustice</option>
<option value="2">Potatoes</option>
<option value="3">Mushrooms</option>

Answer Source

You have to stop the submit when there is an error, otherwise the form will be submitted and is empty again.

function formSubmit() {
    var selectedValue  = document.getElementById("sendTo").value;  

    if( selectedValue == "99" ) {
        alert("Choose a value!");

        // return false will stop the submit
        return false;

But if you do it with onclick on a button you have to use return there too:

<button type="submit" onclick="return formSubmit();">send</button>

Or even better, if you have jQuery available, just register a listener on the form submit and use preventDefault. This is the best way imo.

$("form").on("submit", function(e) {
    if( $("#sendTo").val() == "99" ) {
        alert("Choose a value!");

        // will stop the submit

And as user @Carr said, you have missed a = in your if statement.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download