为输入控件获取未定义的值
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了为输入控件获取未定义的值相关的知识,希望对你有一定的参考价值。
在下面的html
和javascript
代码(代码笔-https://codepen.io/manuchadha/pen/OJVXdzb)中,我希望打印input
控件的值,但我得到的值为undefined
-filename is undefined
。为什么?
<!DOCTYPE html>
<html>
<head>
<title>some title</title>
<script src="jquery/jquery-3.3.1.min.js"></script>
<script src="index.js"></script>
</head>
<body>
<div id="add-more-answer-div">
<div id="answer-filename-div">
<label id="filename-label" for="answer-filename">Name</label>
<input type="text" id="answer-filename" />
<button
type="button"
id="more-answer-button"
onclick="createNewAnswerSection()"
>
Add More Sections
</button>
</div>
</div>
</body>
</html>
function createNewAnswerSection() {
console.log("will create new answer section");
var answerNameControl = $("#answer-filename");
console.log("answer name control is ", answerNameControl);
if (answerNameControl.value === "") {
alert("give a filename to the answer");
} else {
console.log("filename is ", answerNameControl.value);
}
}
答案
请使用answerNameControl.val()代替answerNameControl.value
另一答案
您应该完全使用val()
!
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="add-more-answer-div">
<div id="answer-filename-div">
<label id="filename-label" for="answer-filename">Name</label>
<input type="text" id="answer-filename">
<button type="button" id="more-answer-button" onclick="createNewAnswerSection()">Add More Sections</button>
</div>
</div>
<script>
function createNewAnswerSection() {
console.log("will create new answer section");
var answerNameControl = $("#answer-filename").val();
console.log("answer name control is ", answerNameControl);
if (answerNameControl === '') {
alert("give a filename to the answer");
} else {
console.log("filename is ", answerNameControl);
}
}
</script>
另一答案
您缺少jQuery的语法,您正在使用answerNameControl.value
,它不是有效的synatx,而是可以使用$(answerNameControl).val()
来获取值您更新的代码如下
<html>
<head>
<title>some title</title>
<script src="jquery/jquery-3.3.1.min.js"></script>
<script src="index.js"></script>
</head>
<body>
<div id="add-more-answer-div">
<div id="answer-filename-div">
<label id="filename-label" for="answer-filename">Name</label>
<input type="text" id="answer-filename">
<button type="button" id="more-answer-button" onclick="createNewAnswerSection()">Add More Sections</button>
</div>
</div>
</body>
</html>
<script>
function createNewAnswerSection(){
console.log("will create new answer section");
var answerNameControl = $("#answer-filename");
console.log("answer name control is ",answerNameControl);
if($(answerNameControl).val() === ''){
alert("give a filename to the answer");
} else {
console.log("filename is ",$(answerNameControl).val());
}
}
以上是关于为输入控件获取未定义的值的主要内容,如果未能解决你的问题,请参考以下文章
asp:FileUpload 控件在使用假输入时未获取文件值
getSupportFragmentManager() 在活动扩展片段中未定义
c语言,slider控件还不会用。如何获取当前滑块的值?请列举一段代码,谢谢!
.net中,如何获取到gridview控件中的checkbox控件的值?