1

I am attempting to make interactive checkboxes for my site which display a pop up once you tick a certain value. I have it mostly working however it wont seem to pass the names of the checkboxes to my alert test. It will always display question1 no matter which checkbox I use.

<script async  src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>


function HasChanged()
{
    if($('.common_question').is(":checked")) 
    {  
        alert($('.common_question').val());
    }
}

</script>
<div id="chkbox" style="width=75%">
<form method="post">
        <fieldset>
                <legend>Select your reason for contact from below.</legend>
                        <h2>Premium Accounts</h2>
                        <input type="checkbox" onchange="HasChanged()" class="common_question" name="questiontype" value="question1" />I want to purchase a premium account<br />
                        <div style="display:none" id="prem1">Answer is here </div>
                        <input type="checkbox" onchange="HasChanged()" class="common_question" name="questiontype" value="question2" />I want to cancel a premium account<br />
                        <input type="submit" value="Next" />
        </fieldset>
</form>    
</div>

I am stumped as where I am going wrong, I just want the alert to just display the correct checkbox that has been picked.

1
  • both your checkboxes have common_question class..... Commented Sep 29, 2016 at 18:47

1 Answer 1

2

That's what val() does

Get the current value of the first element in the set of matched elements

It gets the value from the first element in the collection, not neccessarely the one you changed.
You should be using a proper event handler and then access this

<div id="chkbox" style="width=75%">
  <form method="post">
    <fieldset>
      <legend>Select your reason for contact from below.</legend>
      <h2>Premium Accounts</h2>
      <input type="checkbox" class="common_question" name="questiontype" value="question1" />I want to purchase a premium account
      <br />
      <div style="display:none" id="prem1">Answer is here </div>
      <input type="checkbox" class="common_question" name="questiontype" value="question2" />I want to cancel a premium account
      <br />
      <input type="submit" value="Next" />
    </fieldset>
  </form>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
    $('.common_question').on('change', function() {
        if (this.checked) alert(this.value);
    });
</script>

FIDDLE

Sign up to request clarification or add additional context in comments.

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.