2014-09-02 42 views
1

我有基本的按鈕點擊,附加文本拖動div。爲了觸發按鈕事件,必須將文本引入textarea字段。這只是驗證空字段的一種非常基本的方法。它適用於按鈕。現在的問題是我正在使用link button,但我試圖通過使用e.preventDefault()來禁用它,但它不起作用。 JSFIDDLE禁用鏈接按鈕,如果textarea是空的

$('.form-control').prop('disabled',true); 
$('textarea').keyup(function (e){ 
     //$('#button').prop('disabled', this.value == "" ? true : false); 
     $('#button').prop(this.value == "" ? e.preventDefault() : false); 
}); 

HTML

<textarea rows="4" cols="50" placeholder="Enter Text Here!"></textarea> 
<br/> 
<!--input type="button" id="button" disabled="disabled" value="Add Div with Text" /--> 
<a href="#" id="button" role="button"><i class="fa fa-plus"></i> Post Sticky</a> 
<br/> 
<div> 
    <div class="middle-side empty"></div> 

</div> 
+2

可以預防的事件是文本區域上的鍵控的默認操作。總之,你在e的錯誤範圍內。您也不能通過類似的屬性調用將事件附加到按鈕/鏈接。如果你不想讓#button鏈接進行鏈接,你應該指定.on('click'function(){});在它自己的聽衆中。坦率地說,上面的整個方法令人困惑,我並不是100%確定你的實際目標是將文本放在塊中進行驗證? – briansol 2014-09-02 18:15:53

回答

2

你可以簡單地檢查textarea價值,並防止行爲取代return;#button點擊處理程序,如果textarea值不正確(例如,爲空)。

Updated fiddle

$('#button').click(function (e) 
{ 
    if ($('textarea').val() == "") 
    { 
     return false; 
    } 
    ... other code 
0

基本上所有你應該做的是檢查textarea的價值首先,在你的按鈕事件處理程序。你可以這樣做是這樣的:

var text = $('textarea').val(); 
if(text == ''){ 
    return; 
} 

這裏是一個更新的小提琴:http://jsfiddle.net/0wbnud4k/57/

編輯:您還可以用preventDefault();

0

這裏是一個小東西,可以幫助你,不只是與背景的功能,也與視覺造型。

$(document).ready(function(){ 
    function changeMyBTN(a) { 
     if (a == false) { 
      //Adds a Class name for the visual styling 
      $('a[id="button"][role="button"]').addClass('aBTNdisabled'); 
      //Capture and prevents events to the BTN 
      $('a[id="button"][role="button"][class="aBTNdisabled"]').click(function(e) { e.preventDefault();}); 
     } else { 
      //Remove class name if BTN should be enabled 
      $('a[id="button"][role="button"]').removeClass('aBTNdisabled'); 
     } 
    } 
    $('textarea').keyup(function (e){ 
     if ($(this).val() != "") { 
      //Enables BTN 
      changeMyBTN(true); 
     } else { 
      //Disables BTN 
      changeMyBTN(false); 
     } 
    }); 
    /* This captures the mouse event if BTN is enabled */ 
    $('a[id="button"][role="button"]:not([class="aBTNdisabled"])').click(function() { 
     /* Create the event action when clicking the link btn */ 
     //document.location.href="http://www.google.com"; 
     alert($('textarea').val()); 
    }); 
    /* Sets the default state of the btn */ 
    changeMyBTN(false); 

}); 
相關問題