我正在尝试为我的网站制作交互式复选框,一旦勾选某个值,就会显示弹出窗口。我有它主要工作,但它似乎不会将复选框的名称传递给我的警报测试。无论我使用哪个复选框,它都会显示问题1。
<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 :(得分: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>