Stuck on conditionally enable or disable input with JQuery
I am attempting to conditionally enable or disable HTML input based on the value of a variable. The "disable" part is working well, but the "enable" isn't, and I can't figure out why.
The code:
<--if variable is true...-->
<div id="disabledSearch" class="searchBox disabled">
<script type="text/javascript">
$('#disabledSearch :input').attr('disabled', true);
</script>
<--if variable is false-->
<div id="enabledSearch" class="sea开发者_StackOverflow社区rchBox">
<script type="text/javascript">
//This line isn't working:
$('#enabledSearch :input').removeAttr('disabled');
</script>
I played around with this for a bit - check out http://jsbin.com/ayoye3
input.attr('disabled',true)
and input.attr('disabled',false)
successfully toggle the inputs.
The only possibility is that you're not selecting the correct elements, and so the code doesn't appear to work. Make sure your selectors are choosing the correct nodes, or share more of your code here - you might need to place your functions in a $(function() { ... })
wrapper to ensure they only execute once the DOM is loaded.
Also, are you getting any js-related browser errors?
instead of removeAttr try
$('#enabledSearch :input').attr('disabled', false);
Note: just a suggestion but you should probably do this in the $(document).ready() function. this would clean up some of the duplicate code that you have.
Edited
Look at migrating the code to $(document).ready( function() {}); and using the $.toggle() function to toggle disabled on the input depending on the condition. Note if the condition is only referenced on the server side you can expose the flag on the client side by placing it in a hidden input.
Personally I would do something like this assuming you do have a valid input under the div
<div id="searchDiv" class="searchBox <%=SearchIsDisabled ? "disabled" : "enabled"%>">
<input name="myinput" value="" type="text" />
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#searchDiv.disabled input).attr('disabled', true);
$("#searchDiv.enabled input).attr('disabled', false);
})
</script>
Thanks @pointy - I changed the order now it works
Edit: I can't seem to find the comment by @pointy that gave me this idea. However, the solution was that I changed around the order of the elements and javascript on the page.
精彩评论