Add large + and – buttons to number inputs.

By: Chris Adams | Asked: 06/18/2021
ForumsCategory: Code SnippetsAdd large + and – buttons to number inputs.
Chris AdamsChris Adams asked 3 years ago

Sometimes it’s nice to have large inputs to help users enter the right information. Adding large + and – buttons to number inputs is a great way to make life easier for your users.

Here’s how to do it:

  • Add a number field to your form and then go to Settings > Customise HTML and find the number field you just added.
  • Add a class to the [input] shortcode like this: [input class="myNum"]
  • Add 2 <span> elements either side of the [input] shortcode like this:
<span class="min button">-</span>
[input class="myNum"]
<span class="plus button">+</span>

Next add this JS to ‘After Fields’ section of your form:

< script >
	jQuery(".myNum").each(function () {
		var j = jQuery; //Just a variable for using jQuery without conflicts
		var addInput = (this); 
		var n = 1; //n is equal to 1

		//Set default value to n (n = 1)
		j(addInput).val(n);

		//On click add 1 to n
		j(this).next("span").on('click', function () {
			j(addInput).val(++n);
		})

		j(this).prev("span").on('click', function () {
			//If n is bigger or equal to 1 subtract 1 from n
			if (n >= 1) {
				j(addInput).val(--n);
			} else {
				//Otherwise do nothing
			}
		});
	}); <
/script>

And finally add some CSS to style your new buttons.

.plus.button,
.min.button {
	display: inline-block;
	position: relative;
	padding: 0.5em 1em;
	background-color: #7f3690;
	color: #fff;
	cursor: pointer;
	text-align: center;
	width: 50px;
}

.plus.button {
	left: -6px;
	border-top-right-radius: 4px;
	border-bottom-right-radius: 4px;
}

.min.button {
	right: -6px;
	border-top-left-radius: 4px;
	border-bottom-left-radius: 4px;
}

.myNum {
	width: 58% !important;
	text-align: center;
}

/* Hide Number Inputs - Chrome, Safari, Edge, Opera */

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
	-webkit-appearance: none;
	margin: 0;
}

/* Hide Number Inputs - Firefox */

input[type=number] {
	-moz-appearance: textfield;
}
Rob LeVineRob LeVine replied 2 years ago

Based on another question (https://connect.formidableforms.com/question/category/general-questions/buttons-not-updating-triggering-totals-field/), one needs extra code if the input field for which the spinner is used is part of a calculation. To make it work, you have to trigger a change when setting the value, e.g., after "j(addInput).val(++n);" you need the line "j("#field_qb04u").trigger("change");" where you replace qb04u with the key of your input field.

Making the Best WordPress Plugin even better - Together

Take on bigger projects with confidence knowing you have access to an entire community of Formidable Experts and Professionals who have your back when the going gets tough. You got this!
Join the community
crossarrow-right