1

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

Fiddle Link is below

2
  • 1
    You're calling js scripts after calling jQuery. It needs to be the first script you call. Commented May 2, 2016 at 11:33
  • for me the example not running, and my consol says: ReferenceError: toggleFields is not defined (FF 44.0.2) Commented May 2, 2016 at 11:42

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

12 Comments

when adding the function to document.ready, it says toggleFields is not defined
do you mean in jsfiddle, or on your own page?
actually, in jsfiddle.net/tjwoo1y7/2 where you put the code inside the ready function it says $ is not defined. Problem is that you haven't properly set up your fiddle... press the tidy button to see. Then press the javascript radar icon and set up to use jquery
well, like I said your fiddle is not properly set up. I did and found other propblems. Also, again what is $('comment') ? It's not a selector or an element.
well, $("#comment") is targeting an element with id="comment". That element doesn't have that. So I added it and I changed your code
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.