3aIT Blog

 

A client recently asked us to put together an online contractor pay calculator. They provided us with an Excel spreadsheet that demonstrated how the calculations should work, and also laid out how they wanted the form to work. Most of this was very straightforward. However, there was one bit that I thought it might be worth mentioning here.

Because a couple of the fields were time dependent (eg you could pick between whether your contract was being paid per week or per month), the text throughout the rest of the form needed to update accordingly to reflect what had been picked in that form SELECT item (eg whether a later field needed to be labelled "Miles per month" or "Miles per week").

Fortunately, with a quick bit of jquery, this was very simple to achieve.

Firstly, there's a couple of bits we need to add to the HTML markup. We need to make sure that the select box that will trigger the changes later in the form has an id so that we can identify it using our jquery aided javascript later. Something like this

<select name="mySelectTrigger" id="selectTrigger">
<option value="thing1">Thing 1</option>
<option value="thing2">Thing 2</option>
</select>

The other thing we need to do is provide a class or id which we will also use in the javascript that determines where the dynamic text is going to appear. In my case, I needed a <span>, but you don't have to use this element necessarily

<span class="updatedText">m/w</span>

Notice I've put some fallback text inside the span to cover the cases where the user has javascript turned off for whatever reason.

As I've used the ever useful jquery to do this, first you need to make sure jquery is included in your header. The easiest way to do this is to utilise Google's repository of ready to go javascript files:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

Then, all that's left to do is write the javascript that will make the magic happen! You can either do this inline in your HTML header, or call a separate javascript file. Either way, this is how to achieve the effect we're after

$("#selectTrigger").change(function() {
if ($("#selectTrigger option:selected").val() == 'thing1') {
$('.updatedText').html('Thing 1');
} else {
$('.updatedText').html('Thing 2');
}
}).change();

That's all there is to it! It searches for the id we gave the select box and checks which option is currently selected. If the first option is selected, then it will change the span with the class we gave it to say "Thing 1", otherwise, the span will say "Thing 2". Obviously, this can easily be extended to a select box with more options.

If you want to see this in action, have a look at the calculator I created here:

http://www.open-pay.co.uk/iucalculator