使HTML表单元素出现(jQuery或JS)

Make HTML form elements appear (jQuery or JS)

本文关键字:jQuery JS HTML 表单 元素      更新时间:2023-09-26

我想知道是否存在执行以下操作的jQuery或JS库:

根据用户在 A01 中输入的内容,检查该值,如果该值等于"x",则A01_1可见。如果没有,则什么都不做。

<form id="survey">
    <fieldset>
            <label for="A01">A01</label>
            <input type="number" name="A01" id="A01" min="0" max="5" >
            <label for="A01_1">A01_1</label>
            <input type="text" name="A01_1" id="A01_1" >

我想我正在寻找某种内联验证函数,如果另一个元素与特定输入匹配,它将使另一个元素可见。我需要在许多不同的地方应用它,所以我想让它成为一个可重用的功能。

我的JS技能有限,因此非常感谢任何帮助(从哪里开始等)。

$('input[name=A01]').on('keyup', function() {
   var val = $.trim( this.value ),
       x = 'your_custom_value',
       id = this.id,
       target = $('label[for='+ id +'_1], input[name='+ id +'_1]');
   target.hide();
   if( val == x) {
     target.show();
   }
});

为了重复使用,您可以更改标记,例如:

<form id="survey">
    <fieldset>
            <label for="A01">A01</label>
            <input type="number" name="A01" id="A01" min="0" max="5" class="myinput">
            <label for="A01_1">A01_1</label>
            <input type="text" name="A01_1" id="A01_1" >
            <label for="A02">A02</label>
            <input type="number" name="A02" id="A02" min="0" max="5" class="myinput">
            <label for="A02_1">A02_1</label>
            <input type="text" name="A02_1" id="A02_1" >
     </fieldset>
</form>

并像这样更改jQuery

$('input.myinput').on('keyup', function() {
   var val = $.trim( this.value ),
       x = 'your_custom_value',
       id = this.id,
       target = $('label[for^='+ id +'_], input[name='+ id +'_]');
   target.hide();
   if( val == x) {
     target.show();
   }
});
<script type="text/javascript">
function checkField(field) 
{
    if(field.value == 'VALUE')
        document.getElementById('A01_1').style.display = 'true';
}
</script>
<input type="number" name="A01" id="A01" min="0" max="5" onchange="checkField(this)">

然后将样式显示:无应用于要隐藏的元素

试试这个:

.HTML:

<form id="survey">
    <fieldset>
            <label for="A01">A01</label>
            <input data-relation="a01check" type="number" class="checkerinput" name="A01" id="A01" min="0" max="5" >
            <label class="noshow a01check" for="A01_1">A01_1</label>
            <input class="noshow a01check" type="text" name="A01_1" id="A01_1" >
    </fieldset>
</form>    

.JS:

(function(undefined) {
    var equalCheck = 3, $form = $('#survey');
    $form.find('input.checkerinput').bind('keyup change', function(event) {
        var value = parseInt($(this).val(), 10);
        if (!isNaN(value) && value == equalCheck){
            var relation = $(this).data('relation');
            if (relation != undefined) {
                $form.find('.' + relation).removeClass('noshow');
            }
        }
    });
})();​
    ​

.CSS:

.noshow{
    display:none;
}​