javascript - 如何计算输入的字符数及其操作?

标签 javascript jquery character

您好,我对 jQuery 相当基础,但遇到了脚本问题:

//hide all radio buttons first

$('#q11_6_1').parent().hide();
$('#q11_6_2').parent().hide();
$('#q11_6_3').parent().hide();
$('#q11_6_4').parent().hide();
$('#q11_6_5').parent().hide();

//check the length of the open text box

var other2text = $('#q11_6_other').val().length;
$('#q11_6_other').keypress(function(){

//if at least one character has been entered, then I want to show all radio buttons

if(other2text>=0)
{
    $('#q11_6_1').parent().show();
    $('#q11_6_2').parent().show();
    $('#q11_6_3').parent().show();
    $('#q11_6_4').parent().show();
    $('#q11_6_5').parent().show();
}

//else I want to hide all

else
{
    $('#q11_6_1').parent().hide();
    $('#q11_6_2').parent().hide();
    $('#q11_6_3').parent().hide();
    $('#q11_6_4').parent().hide();
    $('#q11_6_5').parent().hide();
}
});

“if 条件”的第一部分有效,但是当我清除 q11_6_other 中的所有文本时,那些单选按钮不会隐藏。我认为“其他”部分不起作用,但不确定如何绕过它。

非常感谢您的帮助!!!

最佳答案

将变量 other2text 放入事件处理函数中:

$('#q11_6_other').keypress(function(){
    var other2text = $('#q11_6_other').val().length;

此外,我建议您使用 keyup 而不是 keypress。但是,如果这样做,则需要将 other2text>=0 更改为 other2text>0

关于javascript - 如何计算输入的字符数及其操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8089668/

相关文章:

jquery - 单击下一个或上一个使页面滚动

java - 如何替换评论

string - 解析器和词法分析器的设计准则?

javascript - 防止 Javascript 数组中的循环引用

javascript - jQuery on() 无法正常工作

javascript - Swift评估JavaScript不删除搜索栏中的占位符

javascript - JQuery 显示隐藏无序列表 : need to add dynamic text/hide function

sql - 替换 SQL 结果中的字符

javascript - 运行 "if"的点击函数然后继续

javascript - 如何循环遍历单选/复选框输入并将所选输入的 id 推送到数组