Search code examples
javascripthtmlinputonclickradio-button

Javascript and HTML - onclick


Suppose I have the following code which creates two radio buttons:

<li id="foli517"        class="     ">
<label class="desc" id="shippingChoice" for="Field517_0">
    Shipping Options
        </label>
<div>
<input id="shippingChoice" name="Field517" type="hidden" value="" />
    <span>
<input id="shipping1"       name="Field517"         type="radio"        class="field radio"         value="$2.00 Shipping Fee"      tabindex="13"                        checked="checked"                      />
<label class="choice" for="Field517_0"      >
    $2.00 Shipping Fee</label>
    </span>
    <span>
<input id="Field517_1"      name="Field517"         type="radio"        class="field radio"         value="I will pick up the items (free shipping)"        tabindex="14"                               />
<label class="choice" for="Field517_1"      >
    I will pick up the items (free shipping)</label>
    </span>
    </div>
</li>

How would I implement a javascript function onclick which updates the inner html of a span with id "mySpan" with the word "FREE" when the 2nd radio button is clicked, and "NOT FREE" otherwise?

document.getElementById(WHAT GOES HERE).onclick = function() { 
    //what goes here?
};

Solution

  • document.getElementById('foli517').onchange = function(e) {
        var e = e || event;
        var target = e.target || e.srcElement;
        var span = document.getElementById('mySpan');
        var span2 = document.getElementById('mySpan2');
    
        if (target.type === "radio") {
            span.innerHTML = (target.id === "Field517_1") ? "FREE" : "NOT FREE";
        }
        if (target.type === "checkbox") {
            span2.innerHTML = "Is it checked? " + target.checked;
        }
    };
    

    Example: http://jsfiddle.net/pEYnm/2/