Status update on enter javascript

176 views Asked by At

Hi I'm not very good a javascript but i am trying to do a dummy status update using javascript. If you click on the button after entering your status update it adds it to the stream. I want when the user presses enter to also update the stream and not just have click on the button to do it.

Here is my code

<script>
$(document).ready(function(){
    var newStatus;
    var minLength=1;
    $("button#update").click(function(){
        newStatus=$.trim($("input#status").val()); // get status

        if(newStatus.length>minLength)
        {
            $("div#streaming").prepend('<div class="status newStatus clearfix"><div class="avatar"><img src="img/avatars/thumb_avatar_5.gif" alt="test" class="avatar-40 right-20" /></div><div class="content"><p><a href="#">Username</a> '+newStatus+'</p><p class="font11"><em>Seconds ago</em> &sdot; <a href="#" class="lightblue">Comment</a> &sdot; <a href="#" class="lightblue">Share</a></p></div></div>');
            $('.newStatus').animate({opacity: 3.0}, 30);
            $("input#status").val('').focus(); // clear status box
        }
        else
        {
            alert("Please share something");
        }

    });
});
</script>

<span class="left inset streamupdate">
<input type="text" placeholder="Share Something" title="Share Something" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;" id="status" />
<button id="update" value="Go" type="button"></button>
</span>
<div id="streaming"></div>
1

There are 1 answers

0
Josh Drake On

Wrap your form elements in a form tag and set the onsubmit to run your function.

$(document).ready(function(){
    var newStatus;
    var minLength=1;
    $("#update").click(function(){
        buttonClick();
    });
});

function buttonClick() {
    newStatus=$.trim($("input#status").val()); // get status

    if(newStatus.length>minLength) {
        $("div#streaming").prepend('<div class="status newStatus clearfix"><div class="avatar"><img src="img/avatars/thumb_avatar_5.gif" alt="test" class="avatar-40 right-20" /></div><div class="content"><p><a href="#">Username</a> '+newStatus+'</p><p class="font11"><em>Seconds ago</em> &sdot; <a href="#" class="lightblue">Comment</a> &sdot; <a href="#" class="lightblue">Share</a></p></div></div>');
        $('.newStatus').animate({opacity: 3.0}, 30);
        $("input#status").val('').focus(); // clear status box
    } else {
        alert("Please share something");
    }
}

<form onsubmit="buttonClick()">