设置输入字段的默认值

发布于 2024-12-07 03:11:56 字数 58 浏览 8 评论 0原文

如何在 JavaScript 中设置表单 文本字段的默认值?

How would you set the default value of a form <input> text field in JavaScript?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(20

暗恋未遂 2024-12-14 03:11:56

这是一种方法:

document.getElementById("nameofid").value = "My value";

This is one way of doing it:

document.getElementById("nameofid").value = "My value";
烈酒灼喉 2024-12-14 03:11:56

我使用setAttribute():

<input type="text" id="example"> // Setup text field 
<script type="text/javascript"> 
  document.getElementById("example").setAttribute('value','My default value');
</script>

I use setAttribute():

<input type="text" id="example"> // Setup text field 
<script type="text/javascript"> 
  document.getElementById("example").setAttribute('value','My default value');
</script>
抚你发端 2024-12-14 03:11:56

如果您的表单包含这样的输入字段

<input type='text' id='id1' />

,您可以在 javascript 中编写代码,如下所示,将其值设置为

document.getElementById('id1').value='text to be displayed' ; 

if your form contains an input field like

<input type='text' id='id1' />

then you can write the code in javascript as given below to set its value as

document.getElementById('id1').value='text to be displayed' ; 
冰雪梦之恋 2024-12-14 03:11:56

您可以在不同情况下使用 document.querySelector(),而不是使用 document.getElementById()

来自另一个 Stack Overflow 答案的更多信息:

querySelector 可让您查找具有无法通过的规则的元素
getElementByIdgetElementsByClassName

表示

getElementByIdgetElementsByClassName EXAMPLE:

document.querySelector('input[name="myInput"]').value = 'Whatever you want!';

let myInput = document.querySelector('input[name="myInput"]');
myInput.value = 'Whatever you want!';

Test:

document.querySelector('input[name="myInput"]').value = 'Whatever you want!';
<input type="text" name="myInput" id="myInput" placeholder="Your text">

Instead of using document.getElementById() you can use document.querySelector() for different cases

more info from another Stack Overflow answer:

querySelector lets you find elements with rules that can't be
expressed with getElementById and getElementsByClassName

EXAMPLE:

document.querySelector('input[name="myInput"]').value = 'Whatever you want!';

or

let myInput = document.querySelector('input[name="myInput"]');
myInput.value = 'Whatever you want!';

Test:

document.querySelector('input[name="myInput"]').value = 'Whatever you want!';
<input type="text" name="myInput" id="myInput" placeholder="Your text">

厌倦 2024-12-14 03:11:56

如果您使用多种形式,您可以使用:

<form name='myForm'>
    <input type='text' name='name' value=''>
</form>

<script type="text/javascript"> 
    document.forms['myForm']['name'].value = "New value";
</script>

If you are using multiple forms, you can use:

<form name='myForm'>
    <input type='text' name='name' value=''>
</form>

<script type="text/javascript"> 
    document.forms['myForm']['name'].value = "New value";
</script>
江挽川 2024-12-14 03:11:56

试试这些。

document.getElementById("current").value = 12

// or

var current = document.getElementById("current");
current.value = 12

Try out these.

document.getElementById("current").value = 12

// or

var current = document.getElementById("current");
current.value = 12
可是我不能没有你 2024-12-14 03:11:56

答案非常简单

// Your HTML text field

<input type="text" name="name" id="txt">

//Your javascript

<script type="text/javascript"> 
document.getElementById("txt").value = "My default value";
</script>

或者如果您想完全避免 JavaScript:您可以仅使用 HTML 定义它

<input type="text" name="name" id="txt" value="My default value">

The answer is really simple

// Your HTML text field

<input type="text" name="name" id="txt">

//Your javascript

<script type="text/javascript"> 
document.getElementById("txt").value = "My default value";
</script>

Or if you want to avoid JavaScript entirely: You can define it just using HTML

<input type="text" name="name" id="txt" value="My default value">
屌丝范 2024-12-14 03:11:56
<input id="a_name" type="text" />

这是使用 jQuery 的解决方案:

$(document).ready(function(){
  $('#a_name').val('something');
});

或者使用 JavaScript

document.getElementById("a_name").value = "Something";
<input id="a_name" type="text" />

Here is the solution using jQuery:

$(document).ready(function(){
  $('#a_name').val('something');
});

Or, using JavaScript:

document.getElementById("a_name").value = "Something";
自由如风 2024-12-14 03:11:56

简单的答案不是在 Javascript 中,获取占位符的最简单方法是通过 placeholder 属性

<input type="text" name="text_box_1" placeholder="My Default Value" />

The simple answer is not in Javascript the simplest way to get the placeholder is through the place holder attribute

<input type="text" name="text_box_1" placeholder="My Default Value" />
放低过去 2024-12-14 03:11:56
document.getElementById("fieldId").value = "Value";

document.forms['formId']['fieldId'].value = "Value";

document.getElementById("fieldId").setAttribute('value','Value');
document.getElementById("fieldId").value = "Value";

or

document.forms['formId']['fieldId'].value = "Value";

or

document.getElementById("fieldId").setAttribute('value','Value');
猫弦 2024-12-14 03:11:56

很简单;一个例子是:

<input type="text" id="example"> // Setup text field 
<script type="text/javascript"> 
var elem = document.getElementById("example"); // Get text field
elem.value = "My default value"; // Change field
</script>

It's simple; An example is:

<input type="text" id="example"> // Setup text field 
<script type="text/javascript"> 
var elem = document.getElementById("example"); // Get text field
elem.value = "My default value"; // Change field
</script>
柠檬色的秋千 2024-12-14 03:11:56

如果该字段由于某种原因只有名称属性而没有其他属性,您可以尝试以下操作:

document.getElementsByName("INPUTNAME")[0].value = "TEXT HERE";

If the field for whatever reason only has a name attribute and nothing else, you can try this:

document.getElementsByName("INPUTNAME")[0].value = "TEXT HERE";
猫弦 2024-12-14 03:11:56
<form>
  <input type="number"  id="inputid"  value="2000" />
</form>


<script>
var form_value = document.getElementById("inputid").value;
</script>    

您还可以将默认值更改为新值

<script>
document.getElementById("inputid").value = 4000;     
</script>
<form>
  <input type="number"  id="inputid"  value="2000" />
</form>


<script>
var form_value = document.getElementById("inputid").value;
</script>    

You can also change the default value to a new value

<script>
document.getElementById("inputid").value = 4000;     
</script>
江心雾 2024-12-14 03:11:56

这部分你在html中使用

<input id="latitude" type="text" name="latitude"></p>

这是javaScript:

<script>
document.getElementById("latitude").value=25;
</script>

This part you use in html

<input id="latitude" type="text" name="latitude"></p>

This is javaScript:

<script>
document.getElementById("latitude").value=25;
</script>
像极了他 2024-12-14 03:11:56

直接访问

如果使用ID,那么您可以直接访问JS全局范围内的输入

myInput.value = 'default_value'
<input id="myInput">

Direct access

If you use ID then you have direct access to input in JS global scope

myInput.value = 'default_value'
<input id="myInput">

帝王念 2024-12-14 03:11:56

这里发生的事情比大多数答案所暗示的要多得多,也比问题让您期望的要多得多。让我们深入探讨并阐明这个问题。

设置输入元素的默认值:valuedefaultValue、属性与属性

了解 value 属性之间的区别非常重要 和 属性(有时也称为IDL 属性)在使用 HTML 和 JavaScript 中的输入元素时。这两者有不同的用途,了解它们的作用将使您能够有效地管理输入字段的初始值和当前值。

1. value 属性

value 属性主要用于在浏览器首次解析 HTML 时设置输入元素的初始值 。该初始值也称为默认值

此属性对应的 JavaScript 属性不是 value,而是 defaultValue。本质上,defaultValue 属性是 value 属性的反映:

get defaultValue() { return this.getAttribute('value'); }
set defaultValue(val) { this.setAttribute('value', val); }

这里,this 指的是输入元素。正如您所看到的,value属性defaultValue属性始终保持同步。

但是,有一个警告:如果用户尚未与输入字段进行交互,则通过 setAttribute 以编程方式设置 value 属性也会更新输入的当前值,这由 value 属性表示。一旦用户修改输入字段,这种同步就会停止。

2. value 属性

value 属性表示输入字段的当前值

如果输入字段具有初始值(通过 HTML 中的 value 属性以声明方式设置)并且用户修改此值、value 属性和 value 属性将不再同步。一旦输入字段是“脏的”(即,用户修改过的),设置value属性将不再影响当前值。

3. value 属性与 defaultValue 属性与 value 属性 - 在实际代码中

此代码示例演示了 value 的行为> 属性、defaultValue 属性和 value 属性。尝试使用不同的按钮,观察日志输出,并注意手动修改输入字段的值后行为如何变化。

const input = document.getElementById('input');

function inspectValues() {
  console.log('value attribute: ' + input.getAttribute('value'));
  console.log('defaultValue property: ' + input.defaultValue);
  console.log('value property: ' + input.value);
  console.log('--------------------------------------');
}

function setViaAttribute() {
  input.setAttribute('value', 'set via value attribute');
  inspectValues();
}

function setViaDefaultValue() {
  input.defaultValue = 'set via defaultValue property';
  inspectValues();
}

function setViaValueProperty() {
  input.value = 'set via value property';
  inspectValues();
}
<input id="input" value="foo">
<button type="button" onclick="inspectValues()">Inspect</button>
<button type="button" onclick="setViaAttribute()">Set via value attribute</button>
<button type="button" onclick="setViaDefaultValue()">Set via defaultValue property</button>
<button type="button" onclick="setViaValueProperty()">Set via value property</button>

There's quite a bit more going on here than most of the answers suggest, and also than the question would make you expect. Let's dive in and shed some light on the matter.

Setting the Default Value of an Input Element: value vs defaultValue, attribute vs property

It's important to understand the distinction between the value attribute and the value property (also sometimes called IDL attribute) when working with input elements in HTML and JavaScript. These two serve different purposes and understanding their roles will allow you to effectively manage the initial and current values of an input field.

1. The value Attribute

The value attribute is primarily used to set the initial value of an input element when the HTML is first parsed by the browser. This initial value is also known as the default value.

The corresponding JavaScript property for this attribute is not value, but rather defaultValue. Essentially, the defaultValue property is a reflection of the value attribute:

get defaultValue() { return this.getAttribute('value'); }
set defaultValue(val) { this.setAttribute('value', val); }

Here, this refers to the input element. As you can see, the value attribute and the defaultValue property are always in sync.

However, there's a caveat: if the user has not yet interacted with the input field, programmatically setting the value attribute via setAttribute will also update the current value of the input, which is represented by the value property. This synchronization stops as soon as the user modifies the input field.

2. The value Property

The value property represents the current value of the input field.

If the input field had an initial value (set declaratively via the value attribute, in the HTML) and the user modifies this value, the value attribute and the value property will no longer be in sync. Once the input field is "dirty" (i.e., user-modified), setting the value attribute will no longer affect the current value.

3. value attribute vs defaultValue property vs value property - in real code

This code example demonstrates the behavior of the value attribute, defaultValue property, and value property. Experiment with the different buttons, observe the log output, and note how the behavior changes once you manually modify the input field's value.

const input = document.getElementById('input');

function inspectValues() {
  console.log('value attribute: ' + input.getAttribute('value'));
  console.log('defaultValue property: ' + input.defaultValue);
  console.log('value property: ' + input.value);
  console.log('--------------------------------------');
}

function setViaAttribute() {
  input.setAttribute('value', 'set via value attribute');
  inspectValues();
}

function setViaDefaultValue() {
  input.defaultValue = 'set via defaultValue property';
  inspectValues();
}

function setViaValueProperty() {
  input.value = 'set via value property';
  inspectValues();
}
<input id="input" value="foo">
<button type="button" onclick="inspectValues()">Inspect</button>
<button type="button" onclick="setViaAttribute()">Set via value attribute</button>
<button type="button" onclick="setViaDefaultValue()">Set via defaultValue property</button>
<button type="button" onclick="setViaValueProperty()">Set via value property</button>

讽刺将军 2024-12-14 03:11:56

您还可以尝试:

document.getElementById('theID').value = 'new value';

You can also try:

document.getElementById('theID').value = 'new value';
单挑你×的.吻 2024-12-14 03:11:56

HTML:

<input id="smtpHost" type="user" name="smtpHost">

JS:

(document.getElementById("smtpHost") as HTMLInputElement).value = data.smtpHost;

HTML:

<input id="smtpHost" type="user" name="smtpHost">

JS:

(document.getElementById("smtpHost") as HTMLInputElement).value = data.smtpHost;
烟花肆意 2024-12-14 03:11:56
 
      function GetAmount()
      {
      var insertNow = document.getElementById("insert").value;
      document.getElementById("output").setAttribute('value',insertNow);
      }
   
  <label>Capture input box</label>
  <br clear="all"/>
  <input id="insert">
  <input onClick="GetAmount()" type="submit" title="Submit">
  <br/>

   <label>Display input box</label>
   <form>
   <input id="output" value="">
   <input type="submit" title="Submit">
   </form>

   

 
      function GetAmount()
      {
      var insertNow = document.getElementById("insert").value;
      document.getElementById("output").setAttribute('value',insertNow);
      }
   
  <label>Capture input box</label>
  <br clear="all"/>
  <input id="insert">
  <input onClick="GetAmount()" type="submit" title="Submit">
  <br/>

   <label>Display input box</label>
   <form>
   <input id="output" value="">
   <input type="submit" title="Submit">
   </form>

   

野侃 2024-12-14 03:11:56

下面的代码工作得很好:

var $div = ('#js-div-hour input');
$div.attr('value','2022/01/10');

The following code work perfectly well:

var $div = ('#js-div-hour input');
$div.attr('value','2022/01/10');
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文