Reputation: 1190
I have basic button click that appends text a draggable div. In order for the button event to trigger, text has to be introduced to the textareafield. This is just a very basic way to validate for empty fields. It works well with button. The issue is now I am using a link button
but I am trying to disable it by using e.preventDefault()
but it is not working. 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
<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>
Upvotes: 1
Views: 959
Reputation: 261
Here is a little something that may help you out, not just with the background functionality, also with the visual styling.
$(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);
});
Upvotes: 0
Reputation: 5176
You can simply check for textarea
value and prevent behaviour on #button
click handler if textarea
value is incorrect (for example, is empty).
$('#button').click(function (e)
{
if ($('textarea').val() == "")
{
return false;
}
... other code
Upvotes: 2
Reputation: 3494
Essentially all you should have to do is check the value of the textarea first, in your buttons event handler. You can do so like this:
var text = $('textarea').val();
if(text == ''){
return;
}
Here is an updated fiddle: http://jsfiddle.net/0wbnud4k/57/
Edit: You could also replace the return;
with a preventDefault();
Upvotes: 0