如果textarea为空,则禁用链接按钮

我有基本的按钮单击,将文本附加为可拖动的div。 为了触发按钮事件,必须将文本引入textareafield。 这只是validation空字段的一种非常基本的方法。 它适用于按钮。 问题是现在我正在使用link button但我试图通过使用e.preventDefault()来禁用它,但它无法正常工作。 的jsfiddle

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

HTML

  
Post Sticky

如果textarea值不正确(例如,为空),您可以简单地检查textarea值并防止#button click handler上的行为。

更新小提琴

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

基本上你应该做的就是先在你的按钮事件处理程序中检查textarea的值。 你可以这样做:

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

这是一个更新的小提琴: http : //jsfiddle.net/0wbnud4k/57/

编辑:你也可以替换return; 使用preventDefault();

这里有一些可以帮助你的东西,不仅仅是背景function,还有视觉样式。

 $(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); });