简体   繁体   English

如何使用JavaScript删除/更改输入值

[英]How to remove/change an input value using javascript

How do I remove the value 'Anonymous' in this input that I have and replace it with a placeholder text 'Your name' using javascript/jquery? 如何在此输入中删除值“ Anonymous”,并使用javascript / jquery将其替换为占位符文本“您的姓名”? I don't have access to the HTML code. 我无权访问HTML代码。

This is what I have so far, but don't really know where to go from there. 这是我到目前为止所拥有的,但是真的不知道从那里去哪里。

document.getElementById('txtYourName').placeholder =' Your Name ';  


HTML HTML

<input id="txtYourName" type="text" value="Anonymous" name="txtYourName"></input>

You can use .val() : 您可以使用.val()

$('#txtYourName').val('');

or pure javascript using: 或纯javascript使用:

document.getElementById('txtYourName').value = ""

If you want to set new value then just put your value inside "" , like: 如果要设置新值,则只需将值放在"" ,例如:

$('#txtYourName').val('new value');

With jQuery, your final code should look like: 使用jQuery,您的最终代码应如下所示:

$('#txtYourName').attr('placeholder','Your name');
$('#txtYourName').val('');

Fiddle Demo 小提琴演示

With pure JS, you final code should look like: 使用纯JS,最终代码应如下所示:

document.getElementById('txtYourName').placeholder ='Your name';  
document.getElementById('txtYourName').value = "";

Fiddle Demo 小提琴演示

Add this second line here... A placeholder is only seen when the value happens to be blank. 在此处添加第二行...仅当值恰好为空白时,才会看到占位符。 With the code below, you can set the placeholder, as well as erase the default value in your field. 使用下面的代码,您可以设置占位符,以及清除字段中的默认值。

document.getElementById('txtYourName').placeholder =' Your Name ';  
document.getElementById('txtYourName').value = "";

Demo: http://jsfiddle.net/723vL/ 演示: http//jsfiddle.net/723vL/

That should do it, so long as you are running that script either on an onload event, jquery's ready event or at the very bottom of the page, once the DOM has been rendered. 只要在DOM呈现后,只要在onload事件,jquery的ready事件或页面的最底部运行该脚本,就应该这样做。

Are you getting an error in your console? 您的控制台出现错误吗?

try this 尝试这个

returns value: 返回值:

$('#txtYourName').attr("value");

sets value 设定价值

$('#txtYourName').attr("value", "");

use 采用

document.getElementById('txtYourName').value ='some vaue';

if you are using jQuery then you can use 如果您使用的是jQuery,则可以使用

$("#txtYourName").val('some value');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM