问题
I need to add the required attribute to an html select (toDept) under the condition that a textarea (orderComments) has text typed in it. Below is my code... What am I missing? Do I need to run my jquery on a change event or something?
$(document).ready(function() {
if ($('#textareaId').val() != '') {
$("#selectId").attr('required', true);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="textareaId"></textarea>
<select id="selectId">
<option value=""></option>
<option value="opt1">opt1</option>
</select>
Thanks for your time!
回答1:
You need to run the code when the textarea changes:
var textarea = $('#textareaId');
var select = $('#selectId');
var addOrRemoveRequiredAttribute = function () {
if (textarea.val().length) {
select.attr('required', true);
}
else {
select.attr('required', false);
}
};
// Run now
addOrRemoveRequiredAttribute();
// And when textarea changes
textarea.on('change', addOrRemoveRequiredAttribute);
回答2:
$(document).ready(function(){
$("#textareaId").on('change keyup paste', function() {
$("#selectId").attr('required',true);
});
});
You need to bind this to the event when the textarea changes
回答3:
You'll want to check on the change event, or possibly others as well. Here I added your code into an .on() method so it runs after any change event. Then I invoke the change event to do it once on startup.
$(document).ready(function() {
$('body').on('change', '#textareaId', function(){
console.log("test");
if ($(this).val() != '') {
$("#selectId").attr('required', true);
}
});
$('#textareaId').change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="textareaId"></textarea>
<select id="selectId">
<option value=""></option>
<option value="opt1">opt1</option>
</select>
Click the run button to see it work. Keep in mind that once the required attribute is set, it is never unset. You would need to an an else clause and unset it if the value is blank.
回答4:
You want to dynamically set the required property of the select whenever the textarea is modified (via cut-and-paste, regular typing, deleting, etc):
$('#textareaId').on("input propertychange", function(){ $('#selectId').prop('required', $(this).val().length) });
To be explicit: if someone types something in the textarea, the select becomes required; if someone removes their text from the textarea, the select's required attribute is removed (the select is no longer required).
See this working example.
来源:https://stackoverflow.com/questions/26365911/how-can-i-add-the-required-attribute-to-input-on-change-of-textarea