开发者

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

开发者 https://www.devze.com 2023-01-14 12:54 出处:网络
I need to give a default va开发者_Python百科lue for input type=text field as follows: <input type="text" size="32" value="" name="fee" />

I need to give a default va开发者_Python百科lue for input type=text field as follows:

<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.


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" />


You can change the name attribute by id, and set the value property using client script after the element is created:

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

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


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

Nope: value is the only way to set the default attribute.

Why don't you want to use it?


You can use Javascript.

For example, using jQuery:

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

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


this is working for me

<input defaultValue="1000" type="text" />

or

let x = document.getElementById("myText").defaultValue; 


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

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

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


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.


Use defaultValue:

<input defaultValue="1000" type="text" />
0

精彩评论

暂无评论...
验证码 换一张
取 消