简体   繁体   English

复选框 onChange 不会触发

[英]checkbox onChange won't fire

I've got the below script included using a .js file and it won't fire.我使用 .js 文件包含了以下脚本,它不会触发。 I'm very new to JQuery and can't see where I'm going wrong.我对 JQuery 很陌生,看不出我哪里出错了。

Help please.请帮忙。

I've now changed the script to the below with the following changes: used Theophilus's example code to amend mine and it now fires correctly thanks Julian $(this).attr(':checked') does not work for me as it returns "unasigned."我现在已将脚本更改为以下内容,并进行了以下更改:使用 Theophilus 的示例代码来修改我的代码,现在它可以正确触发,感谢 Julian $(this).attr(':checked') 对我不起作用,因为它返回“未签名。” However using .prop does $(this).prop('checked') works as expected (true/false) thanks Rashet, for testing purposes I changed url to '/my.script.php' which contains a simple testing script and still does not work.然而,使用 .prop 确实 $(this).prop('checked') 按预期工作(true/false),感谢 Rashet,出于测试目的,我将 url 更改为 '/my.script.php',其中包含一个简单的测试脚本,但仍然不起作用。

if(isset($_POST['id']) || isset($_POST['Purchased'])){
die('Eureka! variables exist');
}else{
die('Failure!, variables do not exist');
}

$('input[name=Purchased]').change(function(){
    //if a checkbox with name 'Purchased' is clicked, do the following.
    var id=$(this).attr('id');  //grab the id from the clicked box
    var Purchased=$(this).prop('checked');

    //alert("ID value:"+id); returns correctly
//  alert("Purchase value:"+Purchased); //Returns correctly

    //setup the ajax call
//Not posting the variable values to PHP processing script
    $.ajax({
        type: 'POST',
        url: '/my.script.php',
        data: {id: 'id',
        Purchased: 'Purchased'}
    });
});

This should .is(selector) help from this post https://stackoverflow.com/a/12279447/5836034 and you can read up about it here Jquery doc on is() Run code snippet below to see it in action这应该是这篇文章https://stackoverflow.com/a/12279447/5836034 的.is(selector)帮助,您可以在此处阅读有关is() 的 Jquery doc运行下面的代码片段以查看它的实际效果

 $('input[name=Purchased]').change(function(){ if (!$(this).is(":checked")) { // not checked alert("Not Checked"); return; } alert("Checked continue"); //check here //if a checkbox with name 'Purchased' is clicked, do the following. var id=$(this).attr('id'); //grab the id from the clicked box var Purchased=$(this).val(); //grab the value from the checkbox (remember, if it is checked it will be 'on', else '' alert("Purchase value:"+Purchased); //setup the ajax call $.ajax({ type: 'POST', url: '../../Includes/MyPHP.script.php', data: {id: 'id', Purchased: 'Purchased'} }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" value="value here" name="Purchased" >

$(this).val()应该是$(this).prop('checked')并且它会返回truefalse

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM