如何实现密码字段输入#时禁用提交按钮,移除后恢复
Hey there! Let's get this functionality working properly for you. The goal is to disable the submit button whenever the password field has a # character anywhere in it, and re-enable it once that # is removed—right?
Your current code has a small logic issue: it only checks if the input value is exactly "#", not if it contains the # character at all. Let's adjust that:
Corrected Code
First, here's the full working code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> <input id="edValue" type="password" oninput="edValueKeyPress()"><br><br> <input type="submit" id="IbValue"> </form> <script> function edValueKeyPress() { const edValue = document.getElementById("edValue"); const submitBtn = $('input[type="submit"]'); // Check if the input value contains the # character if (edValue.value.includes('#')) { submitBtn.prop('disabled', true); } else { submitBtn.prop('disabled', false); } } </script>
Key Fixes & Explanations
- Check for
#presence: Instead of comparing the entire value to"#", we useedValue.value.includes('#')—this will returntrueif#appears anywhere in the input. - Simplified logic: We removed the redundant duplicate condition and cleaned up variable naming for clarity.
- Consistent button state: Now whenever a
#is typed (even in the middle of other text), the submit button gets disabled immediately. As soon as all#characters are deleted, it re-enables.
If you want to use vanilla JavaScript instead of jQuery (to avoid the dependency), here's that version too:
<form> <input id="edValue" type="password" oninput="edValueKeyPress()"><br><br> <input type="submit" id="IbValue"> </form> <script> function edValueKeyPress() { const edValue = document.getElementById("edValue"); const submitBtn = document.getElementById("IbValue"); if (edValue.value.includes('#')) { submitBtn.disabled = true; } else { submitBtn.disabled = false; } } </script>
That's it—this should work exactly as you need it to!
内容的提问来源于stack exchange,提问作者Garry
相关产品推荐
相关产品推荐

