This article summarizes common issues with radio buttons, checkboxes, text fields, etc.
Making Checkboxes Behave Like Radio Buttons
$("input[name='industry']").click(function () {
// Uncheck all checkboxes
$("input[name='industry']").prop("checked", false);
// Check the current one
$(this).prop("checked", true);
});
Gender Selection with Radio Buttons
<div class="radio-group">
<div style="width: 100px; float: left;">
<input name="gender" type="radio" value="male" id="male">
<label class="checked"><em></em><span>Male</span></label>
</div>
<div style="width: 100px; float: left;">
<input name="gender" type="radio" value="female" id="female">
<label><em></em><span>Female</span></label>
</div>
<input id="genderHidden" name="gender" type="hidden" value="male">
</div>
$(".radio-group label").click(function () {
var labels = $(".radio-group label");
var text = $(this).text().trim();
if (text === "Male") {
$(labels[0]).addClass("checked");
$(labels[1]).removeClass("checked");
} else {
$(labels[0]).removeClass("checked");
$(labels[1]).addClass("checked");
}
$("#genderHidden").val(text);
console.log($("#genderHidden").val());
});
Populating Checkboxes from Comma-Separated String
var industryString = row.industry; // e.g., "IT,Finance,Healthcare"
$("input[name='industry']").each(function () {
if (industryString && industryString.indexOf($(this).val()) > -1) {
$(this).prop('checked', true);
}
});
Inserting an Image into a Div
var defaultUrl = "/images/default.png";
var imgHtml;
if (row.imageUrl) {
imgHtml = "<img id='myImg' src='" + row.imageUrl + "' style='width:100%;height:100%'>";
} else {
imgHtml = "<img id='myImg' src='" + defaultUrl + "' style='width:100%;height:100%'>";
}
$("#imgContainer").html(imgHtml);
Validating Email and Contact Number
var emailRegex = /^[A-Za-z0-9]+([-_.][A-Za-z0-9]+)*@([A-Za-z0-9]+[-.])+[A-Za-z0-9]{2,5}$/;
var mobileRegex = /^(?:13\d|15\d)\d{5}(\d{3}|\*{3})$/;
var phoneRegex = /^((0\d{2,3})-)?(\d{7,8})(-(\d{3,}))?$/;
if (!mobileRegex.test(contact) && !phoneRegex.test(contact)) {
// Invalid contact number
}
Disabling Input Elements
Simply add disabled attribute to the HTML element, e.g., <input disabled>, <textarea disabled>, <input type="radio" disabled>.