Is there anyway I can put a variable inside a value tag in HTML?
I would like to have a
<input type="text" value=VARIABLENAME />.
Is there anyway I can do this? Putting value = 开发者_如何学Python"VARIABLENAME" interprets it as the name of the variable. But I would like to assign the content of the variable to the value property.
EDIT: The variable is from the text content of one of my tables. I got the variable by using doing something like this in my script tag.
selectedScheduleName = e.target.childNodes[0].wholeText;
Thank you.
Yes, you can assign a value to the input's value
property from a variable, e.g.:
theInput.value = theVariable;
You do this in the JavaScript, after getting a reference to the input
element.
So for instance, if you give the input
an id
value of "foo", you can do this:
document.getElementById("foo").value = theVariable;
...within a script
tag. (Be sure that the input
has already been added to the DOM first, either by putting the script after it — the bottom of the body
tag is good — or by using window
's load
event or, if you use a library that supports one, some kind of "dom ready" event.)
The element doesn't have to have an id
, if you can get at it via getElementsByTagName
or by the form
element's elements
array, etc., etc.
Handy references:
- DOM2 Core specification (well supported cross-browser)
- DOM2 HTML specification (reasonably well supported cross-browser)
- DOM3 Core specification (not quite as well supported cross-browser yet)
- The HTML5 specification now has IDL for the HTML DOM objects in it directly (supplanting/supplementing the DOM2 HTML spec), such as for
HTMLElement
,HTMLFormElement
, andHTMLInputElement
If as you say you have a JavaScript variable you wish to apply:
var foo = "Testing";
document.GetElementById('ElementID').value = foo;
or using jQuery:
var foo = "Testing";
$("#ElementID").val(foo);
精彩评论