Acme Sprockets

LinkedInTwitterRSS

jQuery Snippets

The jQuery JavaScript library makes it easy to write code that runs in the browser to provide a richer UI experience—you know, that whole Web 2.0 thing. I'll try to use this page attempts to capture a few useful snippets (so I can find them later!).

Making Another Control Readonly

Here's how to make an input element readonly (or not).

First, some simple HTML:

input_1: <input type="text" id="input_1" />
<a href="#" id="readonly_1" />Readonly</a> |
<a href="#" id="readwrite_1" />Read+Write</a>

To change the readonly attribute of the input, we can use the following:

$(document).ready(function(){

  $('#readonly_1').click( function (event) { 
      $('#input_1').attr("readonly", true); 
      event.preventDefault(); // don't follow this link
  });

  $("#readwrite_1").click( function (event) { 
      $('#input_1').attr("readonly", false); 
      event.preventDefault(); // don't follow this link
  });

});

Try it:

input_1: Readonly | Read+Write

Reacting to Changes in Radio Buttons

Here's how to detect changes in a Radio Button.

First, some simple HTML:

<input type="radio" name="radio1" value="1" /> 1
<input type="radio" name="radio1" value="2" /> 2
<input type="radio" name="radio1" value="3" /> 3
<span id="msgbox_2"><!-- message will go here --></span> 

To detect changes to the radio button selection, we can use the following:

$(document).ready(function(){

  $('[@name="radio1"]').change( function() {       // register for change event
      var v = $('[@name="radio1"]:checked').val(); // get the "checked" value
      $('#msgbox_2').text(' - You selected '+v);   // update the message
  });

});

Try it:

1 2 3

If you're    ready for a zombie apocalypse, then you're ready for any emergency.    emergency.cdc.gov