user3430245 user3430245 - 5 months ago 12
Javascript Question

How can I crawl the page for checkbox/radio/text inputs and detect changes to their original values?

All of my checkbox, radio, and text inputs have '_boom' appended to the end of the id. I want to crawl the page for these id's, detect changes to see if any one of them is different from their original state, and if so, apply CSS to a button called 'save' on the page. Here is what I have so far but it doesn't work:

$('[id*="_boom"]').change(function() {
var sType = $(this).getInputType(); //get the type of attribute we're dealing with
if( sType === "checkbox" || sType === "radio" ){ //checkbox or radio type
var originalCheckedState = $(this).prop("defaultChecked");
var currentCheckedState = $(this).prop("checked");

if(currentCheckedState !== originalCheckedState){
$("a#save").css("color","#CCCCCC");
}
}

if( sType === "text" ){ //text type
var originalValue = $(this).prop("defaultValue");
var currentValue = $(this).val();

if(currentValue !== originalValue){
$("a#save").css("color","#CCCCCC");
}
}

});

Answer

I changed getInputType to prop('type') and that fixed the first issue. getInputType is not a jQuery function. The second issue was solved by changing prop('defaultValue') to attr('defaultvalue'). To get custom attributes from an element you need to use attr.

$('[id*="_boom"]').change(function() {
        var sType = $(this).prop('type'); //get the type of attribute we're dealing with
        if( sType === "checkbox" || sType === "radio" ){ //checkbox or radio type
            var originalCheckedState = !!parseInt($(this).attr("defaultchecked"), 10);
            var currentCheckedState = $(this).prop("checked"); 

            if(currentCheckedState !== originalCheckedState){
                $("a#save").css("color","#CCCCCC"); 
            }
            else {
                $("a#save").css("color","#00FF00"); 
            }
        }

        if( sType === "text" ){ //text type
            var originalValue = $(this).attr("defaultValue");
            var currentValue = $(this).val();

            if(currentValue !== originalValue){
                $("a#save").css("color","#CCCCCC"); 
            }
            else {
                $("a#save").css("color","#00FF00"); 
            }
        }

    }); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" defaultchecked="0" id="check_boom" />
<input type="radio" name="rad1" defaultchecked="1" checked id="radio_boom" />
<input type="radio" name="rad1" defaultchecked="0" id="radio2_boom" />
<input type="text" defaultValue="test" id="text_boom" />
<a href="http://www.google.com" id="save">Save</a>