Required attribute inside Jquery generated output

Viewed 43

I have a script where I create an input element. How can I put require inside it? and what is the difference between setting an input and making it variable and append it to a div and still put an attribute required?

Javascript code:

$("#myVar").append(
'<input name="name" class="myClass">');

JQuery code:

var input = $('<input>', { id: myID', name: 'name', type: 'text', class: 'myClass', focusin: function() { $(this).val(''); } }).appendTo('#myVar'); ? 

I found a post just like this and I found this useful for me. How should I required this? attribute doesn't work

HTML:

<div id="myVar"></div>
2 Answers

You can simply write required attribute.

$("#myVar").append(
'<input name="name" class="myClass" required />');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myVar"></div>

just include required method in your input field.

$("#myVar").append( '<input name="name" class="myClass" required />');

And please clarify your second question as it is not clear what you are asking.

Related