0

I have an HTML <select> tag and I want to make it dynamically required. I tried with jQuery but nothing happens.

This is the <select>

<select class="form-control" type="text" id="status">
  <option value="" selected disabled>----- * ----</option>
  <option value="1" >inactive</option>
  <option value="2" >active</option>
</select>

I tried with JavaScript:

document.getElementById("status").required = true

and then with jQuery:

$('select[id=status]').prop('required', true);

$('#status').attr('required');

But none of those worked, no error, nothing.

Edit: this problem is specific to <select>. With <input> it works fine.

Zsolt Meszaros
  • 21,961
  • 19
  • 54
  • 57
Santiago Ramirez
  • 167
  • 1
  • 3
  • 14

2 Answers2

0

How to handle attributes...

Input_ID.setAttribute('required',''); // SET the attribute


if(Input_ID.hasAttribute('required')){}  // TEST if the attribute exists


R=Input_ID.getAttribute('required'); // GET the value of the attribute


Input_ID.removeAttribute('required') // REMOVE the attribute

Given all the above options you should be able to solve this problem.

user99
  • 1
0

In vanilla JS you can use setAttribute() with an empty string as the value to add the required tag:

document
  .getElementById("status")
  .setAttribute("required", "")
Zsolt Meszaros
  • 21,961
  • 19
  • 54
  • 57