ranger19 ranger19 - 23 days ago 9
PHP Question

Form validation onkeyup

I am using this code to send value when user hits enter. What I want is if user hits enter without entering any value, he gets an error

<textarea class="auto-grow-input" onfocus="SK_focusChat();" onkeyup="SK_sendChatMessage(this.value,<?php echo $sk['chat']['recipient']['id']; ?>,event);"></textarea>


// Send chat message

function SK_sendChatMessage(text,recipient_id,e) {
document.title = document_title;
textarea_wrapper = $('.chat-textarea');
chat_messages_wrapper = $('.chat-messages');

if (e.keyCode == 13 && e.shiftKey == 0) {
e.preventDefault();
textarea_wrapper.find('textarea').val('');
chat_messages_wrapper.append('<div class="chat-text align-right temp-text" align="right"><div class="text-wrapper float-right">' + text + '<div class="marker-out"><div class="marker-in"></div></div></div><div class="float-clear"></div></div>');

$.post(SK_source() + '?t=chat&a=send_message', {text: text, recipient_id: recipient_id}, function (data) {
chat_messages_wrapper
.append(data.html)
.scrollTop(chat_messages_wrapper.prop('scrollHeight'))
.find('.temp-text')
.remove();
});
}
}

Answer

Seriously, use jQuery validation to check for empties. They have done a very good job with validation.

<style>
.error { color: red; }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>

<script>
$(document).ready(function() {
    // validate signup form on keyup and submit
    $("#omfg").validate({
        rules: {
            omfgdood: "required"
        },
        messages: {
            omfgdood: "Oy! It\'s Empty!" 
        }
    });
});
</script>

<?php $sk['chat']['recipient']['id'] = 'omfgdood'; ?>
<form id="omfg">
    <textarea class="auto-grow-input" id="<?php echo $sk['chat']['recipient']['id']; ?>" name="<?php echo $sk['chat']['recipient']['id']; ?>"></textarea>
    <input type="submit" name="submit" value="Submit" />
</form>