在运行时修改innerhtml属性

时间:2016-05-06 07:41:02

标签: javascript jquery html innerhtml

我有一个包含两个值和一个文本框的下拉列表。我想要的是 -   - 如果我选择选项1,则文本框应该类似于最多可输入10个字符   - 如果我选择选项2,文本框的maxlength应该没有限制

我不确定如何做到。可能是通过修改innerhtml但不知道如何继续!下面是我的.jsp文件代码,用于下拉列表和文本框,现在显示我需要动态的maxlength 10文本框。

<select name="filetype" id="3">
     <option value="null">--</option>
     <option value="CTN" >CTN</option>
     <option value="SLID" >SLID</option>
</select>

<h2>Enter the number<font color="red">*</font></h2>
        <input type="text" name="customerID" maxlength=10 size="50" id="4"/> 
        <input type="submit" value="Submit Data" />

4 个答案:

答案 0 :(得分:0)

由于您在此处使用标记此问题,因此您只是一个简单示例:

 $('input[name="customerID"]').attr('maxlength')

这是一个吸气剂。要设置值,您必须编写第二个参数。整个例子应该是:

$(document).ready(function() {

  $('select[name="filetype"]').on('change', function(e) {
    var val = $(this).val();
    if(val === "CTN") {
      $('input[name="customerID"]').attr('maxlength', 10); //maxlength =10
    } else if(val === "SLID") {
      $('input[name="customerID"]').removeAttr('maxlength'); //no maxlength
    }
  });
});

答案 1 :(得分:0)

使用一些像这样的JQuery可以起作用:

Lecturer[] L1 = new Lecturer[] {new Lecturer("Dani",2,"Banana",1001)};

答案 2 :(得分:0)

onchange事件写入select,如下所示。获取selected value并根据条件在maxlength

中添加或删除textbox属性

$("select[name=filetype]").on('change', function() {
  var val = $(this).find('option:selected').val();
  $('input[name="customerID"]').val('');
  if (val == "CTN")
    $('input[name="customerID"]').attr('maxlength', 10);
  else if (val == "SLID")
    $('input[name="customerID"]').removeAttr('maxlength');
  else
    return false;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="filetype" id="3">
  <option value="null">--</option>
  <option value="CTN">CTN</option>
  <option value="SLID">SLID</option>
</select>

<h2>Enter the number<font color="red">*</font></h2>
<input type="text" name="customerID" maxlength="10" size="50" id="4" />
<input type="submit" value="Submit Data" />

答案 3 :(得分:0)

请尝试以下代码。

<script>
$(function () {
    $('select').change(function () {
        if ($(this).val() == "CTN") {
            $('input:first').attr('maxlength', '10')
        }
        else if ($(this).val() == "SLID") {
            $('input:first').attr('maxlength', '')
        }
    });
});
</script>
<select name="filetype" id="3">
    <option value="null">--</option>
    <option value="CTN">CTN</option>
    <option value="SLID">SLID</option>
</select>

<h2>Enter the number<font color="red">*</font></h2>
<input type="text" name="customerID" maxlength="10" size="50" id="4" />
<input type="submit" value="Submit Data" />