2016-09-24 130 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

啊你是對的,我的錯。編輯答案。 –