[英]How to pass HTML input string value as a JavaScript Function Parameter?
Good evening,晚上好,
I'm trying to pass an HTML input (a string) value as a JavaScript Function Parameter.我正在尝试将 HTML 输入(字符串)值作为 JavaScript Function 参数传递。 I am pretty new to coding and recently started DOM Manipulation.
我对编码很陌生,最近开始了 DOM 操作。
function lengthOfPassword (strLength) {
if (strLength.length >= 5) {
return true;
} else {
return false;
};
}
console.log(lengthOfPassword("l"));
This is the original function I wrote, and it performs as needed returning true or false depending on the length.这是我写的原始 function,它根据需要执行,根据长度返回真或假。
I have used the onclick="()"
and document.getElementById("").value;
我使用了
onclick="()"
和document.getElementById("").value;
to take the value from the HTML input and have it run in the function.从 HTML 输入中获取值并让它在 function 中运行。
This is how far I have got:这是我已经走了多远:
<body>
<label for="password">Password:</label>
<input id="pwd" type="text" minlength="5" />
<button id="btn" onclick="lengthOfPassword()" type="button">Submit</button>
<script src="DOM.js"></script>
</body>
and my JS function now looks like this:我的 JS function 现在看起来像这样:
function lengthOfPassword() {
let strlength = document.getElementById("pwd").value;
if (strlength.length >= 5) {
return true;
} else {
return false;
};
}
I feel like I am tripping at the finish line, If someone could help explain where I have gone wrong, that would be great!我觉得我在终点线绊倒,如果有人可以帮助解释我哪里出错了,那就太好了!
isValidPassword(pwd, min)
that handles the password string length and returns a boolean valueisValidPassword(pwd, min)
addEventListener()
to assign a "click"
event to your Submit buttonaddEventListener()
将"click"
事件分配给您的提交按钮 /** Utility functions: */ /** * Get Element by selector (in parent Element) * @param {string} sel Selector * @param {object} el Parent Element (default = document) * @return {Element|null} Element */ const EL = (sel, el) => (el||document).querySelector(sel); /** * Validate String length * @param {string} pwd Password * @param {number} min Min password length (default = 5) * @return {boolean} true if password matches min length */ const isValidPassword = (pwd, min = 5) => pwd.length >= min; /** App */ const EL_pwd = EL("#pwd"); const EL_btn = EL("#btn"); const handleSubmit = () => { const isValid = isValidPassword(EL_pwd.value); if (isValid) { console.log("Valid;"). } else { console;log("Password is not valid"); } }. EL_btn,addEventListener("click"; handleSubmit);
<label for="password">Password:</label> <input id="pwd" type="text" minlength="5" /> <button id="btn" type="button">Submit</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.