jQuery – Show and Hide Input Box & Highlighting
Posted on December 1st, 2008 in Programming, jQuery | Comments Off
As part of a recent project, I had to make a payment page clear, user friendly and intuative. One of the key things was to only display fields when certain options were selected – in this case, when a radio button had a certain value.
<input type=”radio” name=”payRemainingBalance” value=”true” checked=”checked”/> the full amount ($amountDue).
<input type=”radio” name=”payRemainingBalance” value=”false” /> another amount. (Enter the amount you wish to pay in the field below)</td>
<div id=”anotherAmount”>
Another Amount: <input type=”text” name=”paymentAmount” id=”paymentAmount” maxlength=”8″ />
</div>
Using jQuery, this is very simple to do:
<script type=”text/javascript”>
$(document).ready(function(){
$(“input[@name='payFullAmount']“).click(function(){
$(“input[@name='payFullAmount']:checked”).val() == ‘false’ ? $(“#anotherAmount”).show() : $(“#anotherAmount”).hide();
});
});</script>
As we don’t have an id on the radio button, we use the name of the input as the identifier, and a simple one liner to establish what the new value of the radio button is.
Due to the focus being on making it clear what is happening, it could be quite easy when you select the radio button, to miss what has changed on the page (a new input box appearing), so I decided to try and highlight the newly displayed input box by fading the background colour of the input box, in and out. In order to do this in jQuery, you need the jQuery Color plugin.
<script type=”text/javascript”>
$(document).ready(function(){
$(“input[@name='payFullAmount']“).click(function(){
$(“input[@name='payFullAmount']:checked”).val() == ‘false’ ? $(“#anotherAmount”).show() : $(“#anotherAmount”).hide();if ($(“input[@name='payFullAmount']:checked”).val() == ‘false’) {
$(“#paymentAmount”).animate({ backgroundColor: “#EFB559″ }, 1000).animate({ backgroundColor: “#FFFFFF” }, 1000).animate({ backgroundColor: “#EFB559″ }, 1000).animate({ backgroundColor: “#FFFFFF” }, 1000);
}});
});</script>
Our starting background colour is #FFFFFF, we fade to #EFB559 in 1 second, back to #FFFFFF in 1 second, to #EFB559 in 1 second, and finally back to #FFFFFF in 1 second. This gives the effect of highlighting the field in an orange colour twice, hopefullyhelping the user notice what has changed on the page.