簡體   English   中英

javascript:如果復選框已選中且textarea為空,則發出警報

[英]javascript: if checkbox checked and textarea empty, alert

我該怎么辦? 我要在用戶單擊“提交”按鈕時發出警報,並且僅在選中復選框且textarea為空時才必須顯示此警報...因為此textarea被隱藏,並且在選中復選框時顯示。

例如: http//jsfiddle.net/gDttK/

HTML:

   <label for="check">other
     <input type="checkbox" name="check0" id="check">
   </label>
   <div id="show">
    <textarea cols="20" rows="5"></textarea>
   </div>

CSS:

   #show { display: none;}

使用Javascript:

$("#check").change(function () {
$("#show").toggle($("#check:checked").length > 0);});

您需要警報並停止處理表單。 為了防止表單處理,請使用: event.preventDefault();

證明: http //jsfiddle.net/UnWt9/

HTML:

<form>
    <label for="check">other
    <input type="checkbox" name="check0" id="check"></label>
<br>
    <div id="show">
        <textarea cols="20" rows="5"></textarea>
<br>
        </div>
    <button type="submit">Submit</button>
<form>

jQuery的:

$("#check").change(function(){
    $("#show").toggle($("#check").prop('checked'));
});

$('form').submit(function(event){

    if( $("#check").prop('checked') && !$.trim($("#show textarea").val()).length ){
           alert('checkbox chcked textarea empty');
        event.preventDefault();
        return;
    }

    event.preventDefault(); // here only for testing
    alert('form submitted');
});

不確定您的小提琴,但是從您的問題中您可以執行以下操作:(您還需要適當地調整HTML)

更新

$("form").submit(function(e) {
    if ($("#check").not(":checked") && $('#show textarea').val().length <= 0) { e.preventDefault(); alert('error'); }   
});

這是你的答案。

HTML:

<label for="check">other
    <input type="checkbox" name="check0" id="check"></label>
    <div id="show">
        <textarea cols="20" rows="5"></textarea>
    </div>

    <input type="submit" id="mysubmit">

JS:

$("#check").change(function(){
    $("#show").toggle($("#check:checked").length > 0);
});

$("#mysubmit").click(function(){
    if($("#check:checked").length > 0){
        alert("Some text");
    }
});

檢查http://jsfiddle.net/alaminopu/gDttK/2/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM