Html 如何在不使用属性“值”的情况下为“输入类型=文本”定义默认值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3610540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 04:19:36  来源:igfitidea点击:

How to define a default value for "input type=text" without using attribute 'value'?

html

提问by q0987

I need to give a default value for input type=text field as follows:

我需要为 input type=text 字段提供一个默认值,如下所示:

<input type="text" size="32" value="" name="fee" />

There is one way to give this default value as I know:

据我所知,有一种方法可以提供此默认值:

<input type="text" size="32" value="1000" name="fee" />

Here is the question: Is it possible that I can set the default value without using attribute 'value'?

问题是:是否可以在不使用属性“值”的情况下设置默认值?

As I know, if I set the enter the value 1000 manually, and then view the source through web browser the value is still empty. So I think there may be a method that I can use.

据我所知,如果我手动设置输入值 1000,然后通过网络浏览器查看源值仍然为空。所以我想可能有一种方法可以使用。

采纳答案by SLaks

You can use Javascript.

您可以使用 JavaScript。

For example, using jQuery:

例如,使用 jQuery:

$(':text').val('1000');

However, this won't be any different from using the valueattribute.

但是,这与使用value属性没有任何不同。

回答by Arjun Tuli

You should rather use the attribute placeholder to give the default value to the text input field.

您应该使用属性占位符为文本输入字段提供默认值。

e.g.

例如

<input type="text" size="32" placeholder="1000" name="fee" />

回答by Guffa

You can set the value property using client script after the element is created:

您可以在创建元素后使用客户端脚本设置 value 属性:

<input type="text" id="fee" />

<script type="text/javascript>
document.getElementById('fee').value = '1000';
</script>

回答by Pekka

Here is the question: Is it possible that I can set the default value without using attribute 'value'?

问题是:是否可以在不使用属性“值”的情况下设置默认值?

Nope: valueis the only way to set the default attribute.

不:value是设置默认属性的唯一方法。

Why don't you want to use it?

你为什么不想使用它?

回答by Orkhan Alikhanov

A non-jQuery way would be setting the value after the document is loaded:

一种非 jQuery 方式是在文档加载后设置值:

<input type="text" id="foo" />

<script>
    document.addEventListener('DOMContentLoaded', function(event) { 
        document.getElementById('foo').value = 'bar';
    });
</script>

回答by Chuck Conway

The value is there. The source is not updated as the values on the form change. The source is from when the page initially loaded.

价值就在那里。源不会随着表单上的值更改而更新。来源来自页面最初加载时。