【问题标题】:JQuery checkbox display alert if user changes checkbox value from what was there originally如果用户从原来的值更改复选框值,则 JQuery 复选框显示警报
【发布时间】:2023-03-14 19:32:01
【问题描述】:

基本上,我有一个表单,可以显示来自 mysql 数据库的一堆动态复选框 - 这很好用。我有一个名为“default”的属性,我将 mysql 条目的值放入其中,以便稍后我可以确定用户是否更改了最初显示的复选框值。下面是生成这些复选框的 while 语句的一部分:

printf("\t<tr class='recordrow'>
        \n\t\t<td><a class='page_modal' href='#mWindow%s' target='_blank'>%s</a></td>
        \n\t\t<td class='ppath'>%s</a></td>
        \n\t\t<td>%s</td>
        \n\t\t<td><input type='checkbox' class='checkbox' name='$page_path current' default='$currentcheckbox' $currentcheckbox/><div class='page_dialog' id='mWindow%s'><img src='exit.png' class='close' alt='close'/><img src='newwin.jpg' alt='new window'/><div id='content_section'>%s</div></div> </td>
        \n\t\t<td><input type='checkbox' class='checkbox' name='$page_path prospective' default='$prospectivecheckbox' $prospectivecheckbox/></td>
        \n\t\t<td><input type='checkbox' class='checkbox' name='$page_path faculty' default='$facultycheckbox' $facultycheckbox/></td>
        \n\t\t<td><input type='checkbox' class='checkbox' name='$page_path staff' default='$staffcheckbox' $staffcheckbox/></td>
        \n\t\t<td><input type='checkbox' class='checkbox' name='$page_path external' default='$externalcheckbox' $externalcheckbox/></td>

现在我有一个小 JQuery 脚本,我认为它应该做我想做的事情,但是我的逻辑或某些东西似乎有问题......基本上当用户对复选框进行更改时,Jquery 脚本被触发,它会弹出一个警报,说明复选框是否被选中或取消选中。然后我有一个 if 语句,它应该查看复选框的选中状态是否与我的默认属性中的原始值不同。我在这里做错了什么?如果用户更改复选框选中/未选中状态,我希望看到我的警报“值与原始值不同”。

$(document).ready(function() {
$('.checkbox').change(function() {
    if($(this).is(":checked")) {
        var returnVal = confirm("checked");
        if($(this).attr("default").val() != returnVal)
        {
            alert("Value is different from original");
            //put element in changed item array
        }
    }
    else{
        var returnVal = confirm("unchecked");
        var returnVal = "0";
        if($(this).attr("default").val() != returnVal)
        {
            alert("Value is different from original");
            //put element in changed item array
        }
    }
});

当我选中和取消选中复选框时,我的 chrome 开发工具中出现此错误: 未捕获的类型错误:对象 0 没有方法 'val'

【问题讨论】:

  • 尝试改用“.text()”。

标签: php jquery forms checkbox nested-if


【解决方案1】:

$(this).attr("default") 返回一个包含属性值的字符串。无需调用.val(),单独使用它就足够了。

【讨论】:

  • 谢谢,我仍然是 JQuery 的初学者,它修复了我的错误,现在我看到了我的警报。
猜你喜欢
  • 2015-07-17
  • 2015-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-19
  • 1970-01-01
  • 2010-11-01
  • 2013-08-08
相关资源
最近更新 更多