I have a select option with many values, I need to toggle a field required or not based on the select option value, tried all possible solutions such as:
$(document).ready(function () {
});
function toggleFields(sel) {
var valuee = sel.value;
alert (valuee);
if (valuee < 7){
//$("#comment").setAttribute("required","");
alert("Removed");
$('#comment').required = false; //Correct
$('#comment').removeAttribute("required"); //Correct
}
else{
$('#comment').required = true; //Correct
$('#comment').setAttribute("required", "");
alert("Set");
}
}
a running example can be found into this fiddle
Your jQuery code should be inside $(document).ready(function () { /*your code here */ }
not under it.
EDIT: or it should be set up to not call any jquery code before jquery is loaded. You may want to remove the inline function and set up an event handler inside your script
Also, what is $('comment')
? It should be a selector eg. $('#comment')
or an element eg. $('div')
.
EDIT: https://jsfiddle.net/tjwoo1y7/11/
$('#comment').attr("required", false);
$('#comment').attr("required", true);