如何编写用于禁用HTML属性文本框的jQuery代码。通过使用jQuery我禁用了基于userId的文本框,如果userId == ''
我想启用文本框,如果userId != ''
我想禁用文本框。
<input type="text" value="${userJson.firstName}" class="txtcontrolwidth" name="firstName" maxlength="45" id="firstName"
disabled="if(${userJson.userId} == '') {$('#firstName').attr('disabled', false)} else {$('#firstName').attr('disabled', true)}" />
每次处于禁用模式时,都不会启用它。
通过调用外部函数来禁用文本框很容易。
<script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery-1.11.1.js"></script>
<script type="text/javascript">
if(${userJson.userId} == "") {
$('#firstName').attr('disabled', false);
} else {
$('#firstName').attr('disabled', true);
}
</script>
但我想仅在禁用属性中禁用文本框。
首先你的HTML很糟糕!如果没有<script></script>
标签,你不能在html中编写脚本。
HTML:
<input type="text" value="" class="txtcontrolwidth" name="firstName" maxlength="45" id="firstName" />
脚本:
$('#firstName').focusout(function(){
if( $(this).val() != "" ) {
$(this).prop('disabled',true);
} else {
$(this).prop('disabled',false);
}
});
您在disabled
标记中使用的HTML <input>
属性是一个布尔属性,但它有点棘手。
看一下这个:
<!-- These will be disabled -->
<input type="text" disabled>
<input type="text" disabled="true">
<input type="text" disabled="false">
<input type="text" disabled="myFunction()"> <!-- function will not be executed -->
<!-- And this will be enabled -->
<input type="text">
如果您希望启用<input>
,请不要在标记中包含disabled
属性。
尝试用以下代码替换您的代码:
<input type="text" value="${userJson.firstName}" class="txtcontrolwidth" name="firstName" maxlength="45" id="firstName" ${ userJson.userId == '' ? 'disabled' : '' } />
上面的代码只有在disabled
时才会将userJson.userId == ''
属性写入标签。
HTML
<input type="text" value="${userJson.firstName}" class="txtcontrolwidth" name="firstName" maxlength="45" id="firstName"
disabled="if(${userJson.userId} == '') {$('#firstName').attr('disabled', false)} else {$('#firstName').attr('disabled', true)}" />
在上面的代码中存在禁用属性,因此文本框始终处于禁用模式,如果javascript返回true或false,则禁用的属性值不会更改。
使用以下内容
<input type="text" value="${userJson.firstName}" class="txtcontrolwidth" name="firstName" maxlength="45" id="firstName" ${userJson.userId == ''?'': 'disabled'}>
如果想使用javascript函数,请使用以下命令:
<script type="text/javascript">
// you have to use double quotes around the value, because the ${userJson.userId} is evaluated then prints the value to the browser html, it cause javascript error
if("${userJson.userId}" == "") {
$('#firstName').prop('disabled', false);
} else {
$('#firstName').prop(disabled', true);
}
</script>