2016-09-24 133 views
-1

我已经包含使用.js文件的下面的脚本,它不会触发。我对JQuery非常陌生,无法看到我要出错的地方。复选框onChange不会触发

请帮忙。

我现在已经改剧本到下面的以下变化: 使用提阿的示例代码修改我的,现在触发正确的感谢 朱利安$(本).attr(“:检查”)不工作对我来说,因为它返回“未分配”。然而,使用.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'} 
    }); 
}); 
+0

的URL不正确。您不能引用本地文件系统,并且不能引用当前位置以上的任何内容。 –

+0

如果您的代码包含php和javascript,请添加php标记。 –

回答

1

这应该从这个职位https://stackoverflow.com/a/12279447/5836034.is(selector)帮助,你可以约在这里读了下面Jquery doc on is()运行 代码片段,看看它在行动

$('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" >

+0

感谢Theophilus,示例代码使它更清晰。 –

+0

欧克谢谢你可以把它标记为你的答案,如果它有帮助。谢谢 –

0

$(this).val()应该是$(this).prop('checked'),它将返回truefalse

+0

Jim我发现$(this).attr(':checked')不起作用,但是$(this).prop('checked')的确行得通。谢谢你的帮助。 –

+0

啊你是对的,我的错。编辑答案。 –