2016-09-29 70 views
1

我正在尝试为我的网站制作交互式复选框,当您勾选某个值时会显示弹出窗口。我主要工作,但它似乎不会将复选框的名称传递给我的警报测试。无论使用哪个复选框,它都会显示question1。Jquery没有正确传递复选框值

<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> 

我很难过,因为我错了,我只是想显示正确的复选框已被挑选的警报。

+0

你都必须复选框'common_question'类..... – depperm

回答

2

这就是val()确实

获取集合中的匹配 元素

,从第一个元素得到值的集合中,没有的第一要素的当前值无疑是你改变的那个。
您应该使用合适的事件处理程序,然后访问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