问题
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? I don't have access to the HTML code.
This is what I have so far, but don't really know where to go from there.
document.getElementById('txtYourName').placeholder =' Your Name ';
HTML
<input id="txtYourName" type="text" value="Anonymous" name="txtYourName"></input>
回答1:
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/
回答2:
You can use .val():
$('#txtYourName').val('');
or pure javascript using:
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:
$('#txtYourName').attr('placeholder','Your name');
$('#txtYourName').val('');
Fiddle Demo
With pure JS, you final code should look like:
document.getElementById('txtYourName').placeholder ='Your name';
document.getElementById('txtYourName').value = "";
Fiddle Demo
回答3:
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.
Are you getting an error in your console?
回答4:
try this
returns value:
$('#txtYourName').attr("value");
sets value
$('#txtYourName').attr("value", "");
回答5:
use
document.getElementById('txtYourName').value ='some vaue';
if you are using jQuery then you can use
$("#txtYourName").val('some value');
来源:https://stackoverflow.com/questions/22566798/how-to-remove-change-an-input-value-using-javascript