2014-01-10 74 views
0

我需要在提交之前檢查複選框的屬性,並在POST之前使用jQuery執行錯誤消息。使用jQuery檢查屬性

例如,如果沒有朋友被選中,我試圖在發送數據前顯示警報。 我的代碼:

function send(friends) 
{ 
var data = {}; 
data['url'] = $('#link').attr('src'); 
val = []; 
    $("input[name='friends']").each(function(i) 
    { 
    if(this.checked == true) 
     val.push(this.value); 
    }); 
    data['friends'] = val; 
    $.post('send.php', data); 
    $("#sentmsg").addClass("in").fadeIn().delay(5000).fadeOut(); 
    $("input[name='friends']").removeAttr("checked"); 
    $("#success").show(); 
} 

不知道在哪裏我把這個轉換成代碼的工作:

else if(this.checked == false) 
{ 
    alert("no box ticked!"); 
} 
+0

「普羅蒂普」:'VAL = $( '輸入[名稱=朋友]:勾選')。圖(函數(){返回THIS.VALUE}) ;''你也需要使用'$ .post'的'success'回調,或者它返回的promise類對象,而不是假設成功並顯示'#success'。 – meagar

回答

0

您可以檢查val變量的長度。但要找到所選擇項的值使用.map()

function send(friends) { 
    var data = {}; 
    data['url'] = $('#link').attr('src'); 

    //use .map() to convert the dom reference to an array 
    var val = $("input[name='friends']:checked").map(function (i) { 
     return this.value 
    }).get(); 
    if(!val.length){ 
     alert('friends not selected'); 
     return 
    } 

    data['friends'] = val; 
    $.post('send.php', data); 
    $("#sentmsg").addClass("in").fadeIn().delay(5000).fadeOut(); 
    $("input[name='friends']").removeAttr("checked"); 
    $("#success").show(); 
} 
+0

當你張貼你的時候,你是多麼的沮喪所有其他的答案......? – NewInTheBusiness

+0

@NewInTheBusiness誰說你的回答是downvoted –

+0

沒有人downvoted什麼?所有的幫助我都很感激。阿倫的回答正是我需要弄清楚的。編輯:它不會允許我upvote任何東西,我會upvote,如果我可以。謝謝Arun。 – user3166831

0

這可能是如果沒有人檢查檢查比較簡單的方法...

var checked = $('input[name="friends"]:checked'); 
//number of checked boxes 
var nr_checked = checked.length; 
if (!nr_checked) { 
    alert("no box ticked!"); 
} else { 
    //Do your thing 
} 
0

嘗試類似這樣的

if(val.length == 0){ 
    alert("no box ticked!"); 
}