Forms - markhowellsmead/helpers GitHub Wiki

Styling form elements

Checkboxes and radio buttons

Starting point for onward customization.

SCSS

[type="radio"], [type="checkbox"] {
	position: absolute;
	transform: scale(0);
	z-index: -1;
	width: 0;
	height: 0;
	margin: 0 !important;
	opacity: 0;
	overflow: hidden;
	pointer-events: none;
	~ label {
		display: flex;
		align-items: center;
		&:before {
			content: '';
			display: inline-block;
			width: 1rem;
			height: 1rem;
			flex: 0 0 1rem;
			margin-right: .5em;
			margin-bottom: .2em;
			background-color: white;
			border: 1px solid silver;
			vertical-align: baseline;
		}
	}
	&:checked ~ label:before {
		background-color: silver;
	}
}

[type="checkbox"] ~ label:before {
	border-radius: 10%;
}

[type="radio"] ~ label:before {
	border-radius: 50%;
}

.form-field-checkbox {
	position: relative;
}

HTML

<div class="form-field form-field-checkbox">
	<input type="checkbox" name="my_checkbox_1" id="my_checkbox_1" value="1">
	<label for="my_checkbox_1">Checkbox 1</label>
</div>
<div class="form-field form-field-checkbox">
	<input type="checkbox" name="my_checkbox_2" id="my_checkbox_1" value="1">
	<label for="my_checkbox_2">Checkbox 2</label>
</div>

Select2

select styling.

Use in WordPress

NPM and Webpack don't seem to play with select2. Enqueue the CSS (before the theme CSS) and JavaScript from a CDN.

wp_enqueue_style('select2CDN', 'https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css', [], null); // First, so that we can override the rules without !important

and

wp_enqueue_script('select2CDN', 'https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.min.js', ['jquery'], null, true);

JavaScript

e.g. with Gravity Forms.

$(document).on('ready gform_post_render', function() {
	$('select').select2({
		width: '100%',
		minimumResultsForSearch: -1,
		onlyOnSubmit: true
	});
});
Add/remove gfield_error class

When using Real Time Validation for Gravity Forms. (This doesn't happen automatically.)

$('select').on('change', function() {
	if ($(this).attr('aria-required') && !$(this).val()) {
		$(this).closest('.gfield').addClass('gfield_error');
	} else {
		$(this).closest('.gfield').removeClass('gfield_error');
	}
});

CSS

e.g. which extends the regular custom form CSS.

.select2-container.select2-container--default {
	.select2-dropdown {
		.select2-results__option {
			padding: rem-calc(8px) rem-calc(20px);
		}

		.select2-results__option--highlighted[aria-selected] {
			background-color: $secondary-color;
			color: $input-color;
		}
	}
	.select2-selection--single {
		position: relative;
	}
	.select2-selection__arrow {
		top: 50% !important;
		transform: translate(-2rem, -50%);
		b {
			margin: 0;
			border-width: rem-calc(7 7 0 7);
			border-color: $f00 transparent transparent transparent;
			top: 50%;
			transform: translateY(-50%);
		}
	}
}
⚠️ **GitHub.com Fallback** ⚠️