javascript - how to dynamically add REQUIRED attribute to input tags based on output of select tag using jquery? -
i have select
tag 2 options 'new' , 'edit'
when selects 'new' option input
tags in form should marked required , when selects 'edit' few should marked required.
<select name="todo" id="todo" required> <option value="">---</option> <option value="new">add</option> <option value="edit">edit</option> </select>
now tried functions don't seem work
<script> var todo = $('#todo option:selected').text(); if (todo == "new") { $('#name').attr('required',true); } else if (todo == "edit") { //code } </script>
and
<script> function req() { var selectbox = document.getelementbyid('todo'); var userinput = selectbox.options[selectbox.selectedindex].value; if (userinput == 'new') { $('#name').attr('required',true); } else if (todo == "edit") { //code } } </script> <select name="todo" id="todo" onchange="return req();" required></select>
just sure if works put alert()
method in if condition, alert never fired.
ps. 1 of input tags is
<input type="text" id="name" name="name">
thank time in advance...
edit
as pointed out @maximillian laumeister in second snippet there typo error (which have corrected here). (sorry that)
this should ebough going. onchange detects whenever different selection made. based on option selected perform different instructions.
jquery(document).ready(function(){ jquery('#todo').on('change', function(event){ alert(this.value); if(this.value === 'edit'){ } else if(this.value === 'new'){ } }) });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <select name="todo" id="todo" required> <option value="">---</option> <option value="new">add</option> <option value="edit">edit</option> </select>
Comments
Post a Comment