2013-07-26 34 views
0

我有一個表單,我希望填寫所有字段。如果字段未填寫,我想顯示該字段的紅色背景和消息。如果輸入爲空,則發出警報

\$('#id_form').blur(function() 
    { 
     if($(this).val().length == 0) { 
      $(this).parents('p').addClass('warning'); 
     } 

print $q->start_form (-method => 'post', -action => "add.pl", -id => 'id_form'); 
print $q->legend({-class => "ui-widget-header ui-corner-all"},""); 
print $q->input ({-id => 'name', -name => 'name',-type => 'text' , -size => 20, -style => ' margin-left:300 px' },"<br>"); 

我不確定這是正確的做法!

+0

這段代碼會發生什麼? – happybuddha

+0

不起作用。它是一樣的,如果它我不把它 – Armida

+0

http://jquerybyexample.blogspot.com/2012/12/jquery-to-check-all-textboxes-empty.html – zod

回答

0

你必須將你的元素綁定到DOM。您可以使用$(document).ready(),或者使用jQuery的匿名函數是這樣的:

$(function() { 
    $('#id_form').blur(function() { 
     if ($(this).val().length == 0) { 
      $(this).parents('p').addClass('warning'); 
     }; 
    }); 
}); 
0

試試這個http://jsfiddle.net/tYhpw/

$('#id_form input').on('blur', function() { 
    if($(this).val() == '') { 
     $(this).css('border','1px solid #f00'); 
    }else{ 
     $(this).css('border','1px solid #000'); 
    } 
}); 
+0

do not't工作,我不明白爲什麼 – Armida

+0

你能寫你的代碼在http://jsfiddle.net/和共享鏈接,以幫助我們瞭解發生了什麼? – David

+0

http://jsfiddle.net/eZuBU/ – Armida

0

我有一個按鈕,使用這個jQuery功能,檢查所有領域都在被填補:

function check(){ 

    var ok = 1; 

    $('input').each(function(){ 

    if($(this).val().length == 0){ 
     ok = 0; $(this).css('background-color','red'); 
     alert("Error message"); 
    } 

    else{ $(this).css('background-color',''); } 
}); 

if(ok != 1){ alert("Error message"); } 

else{ $('#form').submit(); } 

} 

也許這有幫助嗎?

相關問題