jQuery + HTML5: Activate input on select change
Enable hidden input to create a new element in select.
by Porfirio Chavez
HTML
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<div class="container">
<form
method="post"
action=""
class="form-horizontal"
>
<fieldset>
<legend>Create User/Company</legend>
<div class="control-group">
<label class="control-label">Name</label>
<div class="controls">
<input
name="name"
type="text"
autofocus
required
id="name"
placeholder="ex: Jhon Doe"
/>
</div>
</div>
<div class="control-group">
<label class="control-label">Company</label>
<div class="controls">
<select name="company" required id="company">
<option value="" selected disabled>- Select One -</option>
<option value="1">Coca cola</option>
<option value="2">Ford</option>
<option value="new">- Create Company -</option>
</select>
</div>
</div>
<div id="new-company" class="control-group" style="display: none">
<label class="control-label">New</label>
<div class="controls">
<input
type="text"
name="input-new"
id="input-new"
disabled="disabled"
required
/>
</div>
</div>
</fieldset>
<div class="control-group">
<div class="controls">
<br />
<input
type="submit"
value="Create User"
class="btn btn-primary btn-large"
/>
</div>
</div>
</form>
</div>
CSS
body {
background-color: #dbd7cb;
}
JavaScript
function resetForm() {
$("#input-new")
.hide()
.attr("disabled", true)
.val("");
$("#new-company").hide();
$("#company").val("");
$("#name").val("");
}
function registerUser() {
if (!$("#input-new").is(":disabled")) {
// Need add a value from backEnd
var randomVal = Math.floor(Math.random() * 100);
$("#company option:last").before(
"<option value='" + randomVal + "'>" + $("#input-new").val() + "</option>"
);
alert("company registered");
}
alert("user registered");
resetForm();
return;
}
$(document).ready(function() {
$("#company").on("change", function() {
if ($(this).val() == "new") {
$("#input-new")
.show()
.attr("disabled", false);
$("#new-company").show();
} else {
$("#input-new")
.hide()
.attr("disabled", true);
$("#new-company").hide();
}
});
$("form").on("submit", function(e) {
e.preventDefault();
registerUser();
});
});