【问题标题】:Get value of placeholder in empty input field with jquery?使用jquery在空输入字段中获取占位符的值?
【发布时间】:2018-05-01 17:50:11
【问题描述】:

有些奇怪,我很难过。

当我有一个带占位符的输入字段时,例如:

<input id="box1" placeholder="not applicable">

我一直能够获取用户输入,或者如果输入为空,则 jquery 的占位符值如下:

var text = $('#box1').val();

没什么大不了的。使用 jquery .val() 总是成功的。然后我开始在以前工作的应用程序中看到一些代码输出错误,其中空输入未捕获占位符值。

javascript 引擎是否发生了一些变化来解决这个问题?或者如果输入字段为空,是否有新的方法来获取占位符值?

看这个例子:

$('#done').on('click', function(){
	  if($('#box3').val() == ''){
            var box3 = $(this).data('placeholder');
        } else {
        var box3 = $('#box3').val();
        }
  $('#output').val(box3);
});

// Clicking the button doesn't capture the placeholder value if empty?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<input id="box3" placeholder="not applicable">
<br><br>
<button id="done">
Done
</button>
<br><br>
<textarea id="output"></textarea>
<br><br>
<p>
Why doesn't the button click capture the value of the placeholder in this instance, using jquery 3.1.1?
</p>

【问题讨论】:

  • 如果值为空,您想要获取占位符文本吗?根据我的经验,除了 IE,大多数浏览器都不会在占位符值为空时返回它。我只记得这一点,因为我们不得不在我的一些应用程序中明确忽略占位符,因为一些用户使用 IE,它会在提交时发送占位符文本。
  • 占位符也不是data字段,而是attr。
  • 是的,如果值为空,我想获取占位符,以改进 UI 功能。如果用户不需要指定或更新,它可以作为一个很好的默认值。我可以使用value= 设置默认值,但是用户必须经历删除输入并重新输入的麻烦。占位符可让您集中注意力并立即输入。
  • 对不起,你是对的。我已经更新了我的评论。谢谢

标签: jquery user-input placeholder


【解决方案1】:

使用attr('placeholder')。此外,您在 if 语句中使用 this 是错误的。它指的是click 函数的主题。

$('#done').on('click', function(){
	  if($('#box3').val() == ''){
            var box3 = $('#box3').attr('placeholder');
        } else {
           var box3 = $('#box3').val();
        }
  $('#output').val(box3);
});

// Clicking the button doesn't capture the placeholder value if empty?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<input id="box3" placeholder="not applicable">
<br><br>
<button id="done">
Done
</button>
<br><br>
<textarea id="output"></textarea>
<br><br>
<p>
Why doesn't the button click capture the value of the placeholder in this instance, using jquery 3.1.1?
</p>

【讨论】:

  • 谢谢,效果很好。但是,我从来没有在我编写的许多基于 jquery 的应用程序上采取这一步(至少作为一个业余编码员)。我已经使用了 chrome、FF 和 IE,仅使用 val() 就具有相同的效果!什么给了?
  • 总是使用 jQuery 3 吗?也许方法已更新。
猜你喜欢
  • 1970-01-01
  • 2012-09-04
  • 1970-01-01
  • 1970-01-01
  • 2013-04-08
  • 1970-01-01
  • 1970-01-01
  • 2013-09-01
  • 1970-01-01
相关资源
最近更新 更多