Joel
Joel

Reputation: 2721

Not correctly passing value of checked box-html form (with javascript)

I have worked on this for a while and gave up because I couldn't figure it out, but now I'm back to it. I have an email newsletter signup form on my website, and I have a checkbox for people to check if they are interested in music classes with me. The way I want the form to work is that if they are not interested in classes, I will get no value, but if they are interested in classes I get "Interested in classes - $city". Right now I am getting "Interested in classes - $city" in both cases.

The form is kind of complicated because I'm using javascript as well as the regular html code (hiding divs, etc), so I think I'm getting confused there.

The form:

<form action="../index_success.php" method="post" id="sendEmail" class="email">
            <h3 class="register2">Newsletter Signup:</h3>
            <ul class="forms email">
                <li class="name">
                    <label for="yourName">Name: </label>
                    <input type="text" name="yourName" class="info" id="yourName" value="<?php echo $_POST['yourName']; ?>" /><br />
                </li>
                <li class="city"><label for="yourCity">City: </label>
                    <input type="text" name="yourCity" class="info" id="yourCity" value="<?php echo $_POST['yourCity']; ?>" /><br />
                </li>
                <li class="classes"><label for="classInterest">Interested in classes?: </label>
                    <input type="checkbox" name="classInterest" class="info" id="classInterest" value="Yes" /><br />
                </li>
                <li class="email">
                    <label for="emailFrom">Email: </label>
                    <input type="text" name="emailFrom" class="info" id="emailFrom" value="<?php echo $_POST['emailFrom']; ?>" />
                     <?php if(isset($emailFromError)) echo '<span class="error">'.$emailFromError.'</span>';

                     ?>
                </li>
                <li class="buttons email">
                     <button type="submit" id="submit">Send</button>
                     <input type="hidden" name="submitted" id="submitted" value="true" />
                </li>
            </ul>
        </form>

The javascript-my apologies if this code is not relevant to the question-I'm still pretty new so I have found that it is best to include too much rather than not enough! (I'm using jQuery):

    <script type="text/javascript">
$(document).ready(function(){

 $('#emailFrom')
  .focus(function(){
   if ($('#overlay').length) { return; } // don't keep adding overlays if one exists
   $('#sendEmail')

    .find('.name, .city, .classes').slideDown(300, function(){ $(this).show(); });
   $('.outeremailcontainer').css({ position: 'relative', bottom: 0, left: 0, zIndex : 1001 });
   $('<div id="overlay"></div>').appendTo('body');
  });

 $('#overlay').live('click', function(){
   $('#sendEmail')
    .css({ backgroundColor : 'transparent' })
    .find('.name, .city, .classes').slideUp(300);
   $('.outeremailcontainer').css({ position : 'static' });
   $('#overlay').remove();
  });

});
</script>

Here is the javascript for checking the errors on the form and emailing setting the value for the class interest classInterestVal:

$(document).ready(function(){
  $("#submit").click(function(){
    $(".error").hide();
    var hasError = false;
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;


    var emailFromVal = $("#emailFrom").val();

    if(emailFromVal == '') {
      $("#emailFrom").after('<span class="error"><br />You forgot to enter the email address to send from.</span>');
      hasError = true;

    } else if(!emailReg.test(emailFromVal)) {
      $("#emailFrom").after('<span class="error"<br />>Enter a valid email address to send from.</span>');
      hasError = true;
    }

    var yourNameVal = $("#yourName").val();
    if(yourNameVal == '') {
        $("#yourName").after('<span class="error"><br />You forgot to enter your name.</span>');
        hasError = true;
    }

    var yourCityVal = $("#yourCity").val();
    if(yourCityVal == '') {
        $("#yourCity").after('<span class="error"><br />You forgot to enter your city.</span>');
        hasError = true;
    }
    var classInterestVal = $("#classInterest").val();


    if(hasError == false) {
      $(this).hide();
      $("#sendEmail li.buttons").append('<img src="/wp-content/themes/default/images/template/loading.gif" alt="Loading" id="loading" />');
      $.post("/includes/sendemail.php",
//emailTo: emailToVal, 
           { emailFrom: emailFromVal, yourName: yourNameVal, yourCity: yourCityVal, classInterest: classInterestVal },
             function(data){
            $("#sendEmail").slideUp("normal", function() {
              $("#sendEmail").before('<h3 class="register2">Thank you!  You\'re on the email list!</h3><p class="emailbox">Click <a href="http://rattletree.com/Songs/Live_EP/Chikende.mp3">HERE</a> for your free song.</p>');
            });
             }
         );
    }
    return false;
  });
});

And lastly here is the sendEmail.php (this is where I put the conditional for $classInterest):

    <?php 
$mailTo = '[email protected]'; // This is the hardcoded Recipient Address 
$mailSubject = 'Newsletter'; // This is the hardcoded Subject
$mailFrom = $_POST['emailFrom']; 
$yourName = $_POST['yourName']; 
$yourCity = $_POST['yourCity'];


if (isset($_POST['classInterest']) && $_POST['classInterest'] == 'Yes'){
                            $classInterest ="Class Interest - " . $yourCity;
                        }
                        else {
                            $classInterest = '';
                        }
$mailHeader = "From: {$mailFrom}"; 
$mailBody = "Name = {$yourName} City = {$yourCity} Class interest = {$classInterest}";

mail( $mailTo , $mailSubject , $mailBody , $mailHeader );
?>

Upvotes: 0

Views: 188

Answers (1)

jholloman
jholloman

Reputation: 1979

Getting .val() from classInterest will always return the value whether it is checked or not. What you need to do is $("#classInterest").is(":checked") this will return a boolean telling you if the checkbox is checked or not.

A good way to debug problems like this in the future would be to view the network tab in a browser like Chrome that has dev tools (F12). This will allow you to view the information that you are passing so that you can see where the error is occurring.

If you want the value then do:

var classInterest = $("#classInterest");
var classInterestVal = classInterest.is(":checked") ? classInterest.val() : "";

I'm caching the classInterest selector here for efficiency.

Upvotes: 1

Related Questions