Stefan Stefko Stefan Stefko - 4 months ago 7
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 mail@mail.com 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?

JS:

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

if(selectedValue="99")
{
alert("Choose a value!");
}
else
{
//working ajax script which is sending emails
}
}


HTML:

<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>
</select>
</label>

Answer

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
        e.preventDefault();
    }
});

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