2014-07-03 55 views
0

如何编写用于禁用HTML属性文本框的jQuery代码。 通过使用jQuery我禁用基于userId的文本框,如果userId == ''我想启用文本框,如果userId != ''我想禁用文本框。如何使用jQuery禁用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)}" /> 

每当它处于禁用模式时,它都不会启用。

通过调用外部函数禁用文本框很容易。

<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> 

但我想只禁用禁用的属性中的文本框。

+0

你不能把JavaScript中的'disabled'属性里面,你必须做到这一点的'

0

的HTML disabled属性您正在使用的<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' : '' } /> 

上面的代码将只有当userJson.userId == ''disabled属性标签。

0

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是返回真或假disabled属性值不会改变。

使用以下

<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> 
+0

'$ {userJson.userId ==''?'disabled':''}'这个逻辑不起作用。 – pudaykiran

+0

如果** userJson.userId **包含空格,那么在将值设置为** userJson.userId **之前,上述逻辑将不起作用,请修改该值并尝试。 – Srinu

+0

如果它包含值1,它不工作。 – pudaykiran