JSFiddle - React, Tailwind, and code Playground
HTML
<div class="content">
<form accept-charset="utf-8">
<label for="nome">Nome:</label>
<input type="text" size="40" name="nome" id="nome" />
<br />
<label for="email">E-mail:</label>
<input type="text" size="40" name="email" id="email" />
<br />
<label>Teste[]:</label>
<input type="text" size="20" name="teste[]" id="teste[]" />
<input type="text" size="20" name="teste[]" id="teste[]" />
<input type="text" size="20" name="teste[]" id="teste[]" />
<br />
<label>Sexo:</label>
<input type="radio" name="sexo" id="sexo-masculino" value="M" />
<label for="sexo-masculino">Masculino</label>
<input type="radio" name="sexo" id="sexo-feminino" value="F" />
<label for="sexo-feminino">Feminino</label>
<br />
<label for="ativo">Ativo:</label>
<input type="checkbox" name="ativo" value="1" id="ativo" />
<br />
<label for="tipos">Tipos:</label>
<input type="checkbox" name="tipos[]" value="1" />1
<input type="checkbox" name="tipos[]" value="2" />2
<input type="checkbox" name="tipos[]" value="3" />3
<br />
<label for="estado-civil">Estado Civíl:</label>
<select id="estado-civil" name="estadocivil">
<option value="">Selecione um Estado Civíl</option>
<option value="1">Casado (a)</option>
<option value="2">Separado (a)</option>
<option value="3">Solteiro (a)</option>
<option value="4">Viúvo (a)</option>
</select>
<br />
<label for="observacao">Observação:</label>
<textarea rows="3" name="observacao" id="observacao"></textarea>
</form>
</div>
JavaScript
(function($) {
$.fn.loadData = function(data) {
var isCheckBoxOrRadio = function(el) {
return new RegExp(/checkbox|radio/i).test(el.type);
};
return this.each(function() {
var form, f, t;
if ('form' !== this.tagName.toLowerCase()) {
return false;
}
form = this;
form.reset();
$.map(data, function(v, k) {
f = form.elements[k];
if (undefined !== f) {
t = f.type || false;
if (t) {
if(isCheckBoxOrRadio(f)){
$(f).prop('checked', true);
}
else {
$(f).val(v);
}
} else {
f = $(f);
if (f.length > 1) {
if (isCheckBoxOrRadio(f[0])) {
t = new RegExp($.isArray(v) ? v.join('|') : v);
f.filter(function() {
return (t).test(this.value);
}).prop('checked', true);
} else {
if ($.isArray(v)) {
$.map(v, function(c, p) {
$(f[p]).val(c);
});
}
}
}
}
}
});
});
};
$('form').loadData({
'nome': 'Fulano de Tal',
'email': '[email protected]',
'teste[]': ['Pos 0', '', 'Pos 2'],
'sexo': 'M',
'ativo': true,
'tipos[]': [1, 3],
'estadocivil': 3,
'observacao': 'Esse texto foi inserido dinâmicamente pelo Plugin!!!'
});
}(jQuery));