使用Jquery清除输入文本字段值

Clearing input text field value with Jquery

本文关键字:字段 文本 输入 Jquery 清除 使用      更新时间:2023-10-13

我似乎能够使用隐藏资源容器

resource.parent().parent().hide(); 

但我不明白为什么不能清除输入值

resource.parent().siblings('.resource-value').children('input').val('');

当我使用时

resource.parent().siblings('.resource-value')我得到输入值的父级,但在其上添加.children('input').val('')没有任何作用,或者如果我添加.children('input:text').val('')

我对其他一些东西有非常相似的代码,它运行得很好,看了其他问题,不确定我遗漏了什么。

function removeResource(resource) {
    'use strict';
    //hide resource on screen
    resource.parent().parent().hide();
    //set resource text value to ''
    resource.parent().siblings('.resource-value').children('input').val('');
}
(function($) {
    'use strict';
    $(function() {
        $('#resources').on('click', '.remove-resource', function(evt) {
            // Stop the anchor's default behavior
            evt.preventDefault();
            // Remove the image, toggle the anchors
            removeResource($(this));
        });
    });
})(jQuery);
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
  <div id="resources">
     <div class="resource">
        <div class="resource-value">
           <input type="text" name="resources[]" value="1" />
        </div>
        <p class="hide-if-no-js"><a title="remove resource" href="javascript:;" class="remove-resource">remove resource</a > </p>
        <!-- .hide-if-no-js -->
     </div>
     <div class="resource">
        <div class="resource-value">
           <input type="text" name="resources[]" value="2"/>
        </div>
        <p class="hide-if-no-js"><a title="remove resourcee" href="javascript:;" class="remove-resource">remove resource</a> </p>
        <!-- .hide-if-no-js -->
     </div>
  </div>
   </body>
<html/>

尝试了您的代码,在字段清除的实际值方面对我来说很好,尽管在检查器中,HTML元素仍然显示了value属性。

你可以使用

.attr('value','')

也要澄清http://jsfiddle.net/bvtg93dm

您只需要将jquery的值更改为set"(因此为空)。

input.attr('value','')

尝试使用尝试将removeResource功能更改为

function removeResource(resource) {
  'use strict';
  //hide resource on screen
  var parent = resource.parent().parent();
  parent.hide();
  // log your element
  console.log(parent.find('.resource-value input'));
  // make sure you are getting an element you need
  console.log(parent.siblings('.resource-value').childer('input').get(0);
  //set resource text value to ''
  parent.find('.resource-value input').val('');
}