【发布时间】:2020-01-29 01:59:09
【问题描述】:
我有一个简单的表格:
<form name="demoForm" id="demoForm">
<label id=”givenNameLabel” class =blueText>Please enter your given name:
<input type = “text” name = “givenName” id= “givenName” value ="nn">
</label>
<button onclick = validate("givenName");>Validate this entry</button>
</form>
但是当我尝试获取该值时,它是未定义的。 我使用 vanilla JS 或 jQuery 获得价值:
<script type="text/javascript">
function validate(someTextID){
alert("In validate()") //Works
var thisElement = "#"+someTextID; //the text element;
var thisLabel = thisElement + "Label"; //the label for the text element;
var thisValue = $(thisElement).val(); //The value stored in the text box
alert("thisElement is " +thisElement); //Works
alert("thisLabel is " +thisLabel); //Works
alert("thisValue is " +thisValue); //Why is the value undefined?
//more code to take actions depending on thisValue
}
</script>
【问题讨论】:
-
使用直引号
""而不是“智能引号”“”。 -
您认为
thisElement有什么价值?它是否与您想要其值的输入的 ID 匹配? -
相关:Why is my code not working?、HTML class not being recognized 等。如果您在编辑器中禁用智能引号并将其替换为常规引号,则它会起作用。发帖前请validate your HTML。不要用
alert调试;尝试使用浏览器的debugging capabilities。 -
像
onclick这样的内联事件处理程序是not recommended。它们是注册事件的obsolete, hard-to-maintain and unintuitive 方式。总是useaddEventListener。
标签: javascript html forms