0

I am trying to set attribute required for html options in jquery and here are what I tried from reading online and none of them works:

$("#transaction_payee_id")[0].setAttribute("required", "true");
$("#transaction_payee_id")[0].setAttribute("required", true);
$("#transaction_payee_id").prop("required", true);
$("#transaction_payee_id").attr("required", true);

The first option in html is empty which is required for setup required. Here is the html source code. The value for required is empty:

<select id="transaction_payee_id" name="transaction[payee_id]" class="select required form-control" required="">
    <option value=""></option>
    <option value="1">option2</option>
    <option value="2">option2</option>
</select>

The command is not complicated. What's missing in the code?

Alex
  • 8,461
  • 6
  • 37
  • 49
user938363
  • 9,990
  • 38
  • 137
  • 303

4 Answers4

3

All you need is a form and the required attribute in the form element select.

For example:

<form>
  <select required>
    <option value=""></option>
    <option value="something">someting</option>
  </select>
  <input type="submit" />
</form>

http://jsfiddle.net/6uLsu25g/

Alex
  • 8,461
  • 6
  • 37
  • 49
filype
  • 8,034
  • 10
  • 40
  • 66
1

You can set the attribute like this :

$('select').attr("required","required");

This would inject the attribute required="required"

http://jsfiddle.net/6uLsu25g/1/

DinoMyte
  • 8,737
  • 1
  • 19
  • 26
  • still same `required = ""` in html source. .prop is the same. Somehow the empty string "" manages to stay. Tried `attr("required", "required")` and it is the same `required=""` – user938363 Dec 12 '15 at 04:11
1
  1. As per @Filype's answer form is mandatory to make the required attribute to work.
  2. <select required> is similar to <select required = "">, <select required = "required"> and <select required = true>(not valid HTML). Please refer LINK for more information.
  3. You can set the reuqired attribute dynamically using this $("#transaction_payee_id").prop("required", "required"); and can remove it by $("#transaction_payee_id").removeAttr('required');

DEMO: FIDDLE

Hope this helps!

Community
  • 1
  • 1
John R
  • 2,741
  • 2
  • 13
  • 32
0

The jquery code resetting the required works as designed. This problem is caused by config.validate_browser on gem simple_form which has false by default. By resetting it to true, the attribute required starts working as it should be. Please see the post.

Community
  • 1
  • 1
user938363
  • 9,990
  • 38
  • 137
  • 303