I have a form with an input
<input type="text" id="$email" name="$email" required="" value="[email protected]">
I am not able to get the value of the input. Am I missing something?
val = document.getElementById('$email').value;
val = document.getElementById('email').value;
val = document.getElementsByClassName("email").value;
val = document.getElementsByName("$email").value;
CodePudding user response:
getElementsByClassName and getElementsByName return HTMLCollection object. You need to access with index.
val = document.getElementById('$email').value;
val = document.getElementsByClassName("email")[0].value;
val = document.getElementsByName("$email")[0].value;
<input type="text" id="$email" name="$email" required="" value="[email protected]">
CodePudding user response:
The following code will retrieve the value content of any element by its Id. See the last example for ByClassName.
<input type="text" id="email" name="$email" required="" valu="[email protected]">
var element = document.getElementById("email");
if(element !== null) {
console.log("Not null.");
var content = element.value;
console.log(content);
}
else {
console.log("Null.");
}
ByClassName:
var element = document.getElementsByClassName("email");
if(element !== null) {
console.log("Not null.");
var content = element[0].value;
console.log(content);
}
else {
console.log("Null.");
}
