【问题标题】:Clearing a form's textarea and input清除表单的文本区域和输入
【发布时间】:2014-02-17 16:07:19
【问题描述】:

我有一个表格,

<form class="form-inline" role="form" method="post">
<div class="table-responsive">
<table>
<tr class="tr_top">
<td class="td_top"><textarea class="form-control" rows="4" name="msg" placeholder="Your message here." onfocus='this.select()'><?php
('encode.php');
require ('decode.php');

if (isset($_POST['encode'])) {
echo $encstring;
} elseif (isset($_POST['decode'])) {
echo $decstring;
} ?>
</textarea></td>
</tr>

<tr class="tr_mid">
<td class="td_mid">
<input type=text class="form-control input_mid" name="offset" value="<?php if (isset($_POST['encode']) || isset($_POST['decode'])) { echo htmlspecialchars($_POST['offset']);} ?>" placeholder="Enter a number." pattern="[0-9]{0,3}" oninvalid="setCustomValidity('Please enter a number between 1 and 999.')"></td>
</tr>
<tr class="tr_bottom">
<td class="td_bottom">
<input class="input_bottom btn btn-default" type="submit" name="encode" value="Encode">
<input class="input_bottom btn btn-default" type="submit" name="decode" value="Decode">
<input class="input_bottom btn btn-default" type="button" value="Clear" onclick='this.form.elements.msg.value=""'</td>
</tr>
</table>
</div><!-- close table-responsive -->
</form>

在哪里,当单击值为“清除”的输入时,我希望它清除表单的文本区域和输入字段(分别为 name="msg" 和 name="offset")。就目前而言,现在这段代码:

value="Clear" onclick='this.form.elements.msg.value=""'

仅清除 textarea 字段。我怎样才能让两者都清除?我知道这样做是硬编码的,当我将其更改为 onclick='this.form.elements.offset.value=""' 时,它适用于输入。如何让它同时清除两者?

【问题讨论】:

    标签: jquery forms onclick textarea


    【解决方案1】:
    $('button').on('click', function() {    
    $('.form-control').val('');
    });
    

    尝试一下,其中 button 是您的“清除”按钮 id 值。

    我认为这也可以

    $('input[value="Clear"]').on('click', function() {    
    $('.form-control').val('');
    });
    

    或者,如果您更愿意选择 HTML 解决方案:

    <input type="reset" value="Reset">
    

    这将清除表单中的所有输入字段

    编辑:将 javascript 加载到您的文件中:

    ...other stuff..
    //load jquery if you haven't...
    <script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
    //then the code you want to use...
    <script>
    $(document).ready(function() {
    $('input[value="Clear"]').on('click', function() {    
        $('.form-control').val('');
        });
    });
    </script>
    </body>
    </html>
    

    【讨论】:

    • 不,在文件末尾的“
    • 检查编辑,这也是假设你已经加载了 jquery,但无论如何我认为输入 type="reset" 会为你解决问题?
    • 我已经加载了 jQuery,所以把它放在最后,它工作正常。我尝试使用 input type="reset" 但这没有用,仅供参考。感谢您的帮助!
    • 您是否在表单中添加了类型为“reset”的输入元素?它不会进入 javascript
    • 是的,我在html中使用过。
    猜你喜欢
    • 2012-06-27
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    • 2021-04-06
    • 2020-09-13
    • 2019-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多