You can do it by giving an id to your select, in this case I have given estado
. Then in jQuery check if something is selected using change()
and set the property of your input to true
or false
according to the value of the variable called sino
.
jQuery best practices: I've used the prop()
to set the input state to enabled / disabled, since jQuery recommends using this method to find or change the properties of a DOM element: To retrieve and change DOM properties such as the checked, selected, or < strong> disabled state of form elements, use the .prop () method . Here jQuery explains in which cases it is better to use the atrr()
To make it work you just have to add id="estado"
to the end of your select, as the example shows.
Note:
It may be necessary to verify what happens in each input. For example, if you choose to allow and activate the input, you write values and then you select not to allow ... I have added a fragment of code to erase what you have written in case the input returns to the deactivated state. In the meantime I have applied background colors using CSS , just to show an interesting possibility for the input. :)
You can test the code by clicking on the blue Execute button.
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script>
<!-- Código jQuery -->
$(document).ready(function()
{
$('#estado').change(function ()
{
var sino = $(this).val() == 'true' ? false : true;
$("input[name='pass']").prop('disabled',sino).css("background-color","#0F0");
$("input[name='pass1']").prop('disabled',sino);
//Validar lo que hay en el input y aplicar css
if (sino==false)
{
$("input[name='pass']").css("background-color","#FEF5CA");
$("input[name='pass1']").css("background-color","#FEF5CA");
} else {
$("input[name='pass']").css("background-color","#7F7F7F");
$("input[name='pass1']").css("background-color","#7F7F7F");
$("input[name='pass']").val("");
$("input[name='pass']").val("");
}
});
});
</script>
<!-- HTML -->
<select class="form-control m-b-10" id="estado">
<option value="false">No permitir 1</option>
<option value="true">Permitir 2</option>
</select>
<input type="password" name="pass" disabled>
<input type="password" name="pass1" disabled>