Reputation: 1019
I have a dynamically created select
element as such:
var select = document.createElement("select");
What I would like to do now is make this element required
. I know how to manipulate classes, values, and text of dynamically created elements, but cannot figure out how to make the element required
. I had read an answer from a similarly sounding question that:
select.rules("add", "required");
would work, but the browser comes back with the error Uncaught TypeError: select.rules is not a function
. From what I've read this usually indicates a variable not being properly made for JQuery, so I tried changing the creation line to:
var select = $("<select></select>");
But I received the same TypeError. Really all I am trying to do is add required
to a dynamically created select
, and any indication of a direction to take to do so would be appreciated.
Upvotes: 1
Views: 1420
Reputation: 315
Try this
var newDiv = document.createElement("div");
var selectHTML ="<select>";
selectHTML += "<option value=''>Select one</option>";
selectHTML += "</select>";
newDiv.innerHTML = selectHTML;
document.getElementsByClassName("my-select")[0].appendChild(newDiv);
document.getElementsByTagName("select")[0].required = true;
<form>
<div class="my-select">
</div>
<input type="submit" value="ok">
</form>
Upvotes: 0
Reputation: 12181
Try this https://jsfiddle.net/z2f9mxa0/
var select = $("<select></select>");
$('body').append(select);
$('select').attr('required', "");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If you open the browser debug panel, you will be able to see the required attribute set to select element i.e. dynamically added.
Upvotes: 2
Reputation: 6565
Try :
select.setAttribute("required", "");
OR
document.createElement("select").required = true;
Upvotes: 2