首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用jquery获取空输入字段中占位符的值?

用jquery获取空输入字段中占位符的值?
EN

Stack Overflow用户
提问于 2017-11-17 21:11:03
回答 1查看 11.9K关注 0票数 3

有些事很奇怪,我很困惑。

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

代码语言:javascript
运行
复制
<input id="box1" placeholder="not applicable">

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

代码语言:javascript
运行
复制
var text = $('#box1').val();

别小题大作。使用jquery .val()总是能做到这一点。然后,我开始在以前工作的应用程序中看到一些代码输出错误,其中的空输入没有捕获占位符值。

javascript引擎是否发生了一些变化,从而解释了这一点?或者,如果输入字段为空,是否有获得占位符值的新方法?

参见此示例:

代码语言: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?
代码语言:javascript
运行
复制
<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>

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-11-17 21:15:48

使用attr('placeholder')。而且,在this语句中使用if是错误的。它提到了click函数的主题。

代码语言:javascript
运行
复制
$('#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?
代码语言:javascript
运行
复制
<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>

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47359334

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档