如何制作textarea

时间:2014-03-15 20:36:46

标签: javascript jquery html html5

非常不言自明,我有一个textarea并且它设置为必需,但它只会提示用户是否实际点击了文本区域,如果你提交没有在文本区域内单击它将不会提示警报。

Fiddle

<p class="textHeader">
    <strong>
        Which type of elements would you be in favor of for a future 
        pattern for interactive media to follow? 
    </strong>
    <textarea
        name="styled-textarea"
        id="styled" 
        onfocus="this.value=''; setbg('#e5fff3');" 
        oninvalid="invalidComment(this);" 
        onblur="setbg('white')" 
        placeholder="Max characters 140"
        maxlength="140" 
        required
    > 
    </textarea>
</p> 

2 个答案:

答案 0 :(得分:1)

简单的回答。您已经为textarea提供了内容,一些空白区域包含现有HTML的布局方式。因此提供了一个值。确保textarea结束标记位于开始标记旁边,没有任何空格,因此中间没有空白内容。像这样:

<p class="textHeader">
<strong>
    Which type of elements would you be in favor of for a future 
    pattern for interactive media to follow? 
</strong>
<textarea
    name="styled-textarea"
    id="styled" 
    onfocus="this.value=''; setbg('#e5fff3');" 
    oninvalid="invalidComment(this);" 
    onblur="setbg('white')" 
    placeholder="Max characters 140"
    maxlength="140" 
    required
></textarea>

答案 1 :(得分:0)

您可以像使用一样使用js库 http://www.siegeengine.org/documentation/abide-html5-validation.html

或者如果你喜欢

<script type="text/javascript">
    // without jQuery style
    var bindEvents = function(event){
        if( document.getElementById('styled').value.trim() === '' ){
            event.preventDefault();
            alert("Write something please");
        }
    };

    window.onload = function(){
        document.forms[0].addEventListener('submit', bindEvents, true);
    };

    // jQuery style
    var bindEvents = function(){
        $('form').on('submit', function(e){
            if( $(this).val().trim() === '' ){
                e.preventDefault();
                alert("Write something please");
            }
        });
    };
    $(document).ready( bindEvents );

    // i would not recommend this but it will work also
    var initForm = function(){
        document.getElementById('styled').focus();
        document.getElementById('styled').blur();
    }

    window.onload = initForm;
</script>