1

So i have a list of check boxes created through unique values of a query. Once i have these values i was to check and make sure the user has checked at least one before being able to submit the form to be exported as an excel document. if they have not checked one box then i was it to send an alert and cancel the submit.

here is my script:

     document.getElementById('btnPrint').onclick = function(){
     var checkOperator = $('input[name="OperatorName[]"]:checked').length;

     if(!checkOperator){
         alert('It worked!')
         return false;
     }
     return true;
 };

    <input type="submit" name="btnSubmit" value="preview" onclick="submitForm('index.php')"/>
<input type="submit" id="btnPrint" name="btnSubmitPrint" value="print" onsubmit="submitForm('exportExcel.php')"/>

what's happening now is that it is still exporting to excel and not showing the alert and canceling.

3 Answers 3

2

You are comparing a boolean against a number. Try this instead:

 if(checkOperator > 0){
     alert('It worked!')
     return false;
 }
Sign up to request clarification or add additional context in comments.

2 Comments

it did not download the excel sheet but it still is not showing the alert for some reason.
add either a console.log() or an alert to output the value of checkOperator. Make sure that you are targeting the DOM element correctly. If you check a box, your output should be 1. If it is not, then you are not targeting the DOM element(s) correctly, so length is going to return a null.
1

Here's how you would do it with jQuery (since that is a valid tag for your question, and it is automatically cross-browser, and less typing...):

var cnt = 0;
$('#btnPrint').click(function(){
    $('input[type=checkbox]').each(function(){
        if ( $(this).prop('checked') ) cnt++;
    });
    if (cnt==0){
        alert('Please check a checkbox');
        return false;
    }
});

jsFiddle Demo

Comments

0

Simply return in your method return checkOperator !== 0;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.