1

I have a set of checkboxes in a page and each checkbox is associated with a textbox.

What I need to do is to disable the textbox if the checkbox is unchecked and put a default value inside it(each textbox has a different default value).

Right now I have written a function which accepts checkboxId, textboxId and the default value which is called onClick of the checkbox.

Is there a way to store this information(checkBoxId,textBoxId,defaultValue) statically(like a map or something) in javascript so that my function does not require any arguments and can be called onLoad of the page?

2
  • Store them using data- would be the best way imo. Commented Feb 3, 2014 at 4:40
  • In js you can go for Object() to store associate data Commented Feb 3, 2014 at 4:42

1 Answer 1

2

This is something I did before:

<input type="checkbox" id="sample">
<input data-requires="sample" data-default="Default">

function applyControls(){
    $("input[data-requires]").each(function(){
        var target = $(this);
        $("#" + target.data("requires")).click(function(){
            if(this.checked){
                target.prop("disabled", false);
            }else{
                target.prop("disabled", true).val(target.data("default"));
            }
        });
    });
}
applyControls();

Note: This code is written with jQuery. You can easily convert this to native code by substituting jQuery methods with native methods.

Demo: http://jsfiddle.net/DerekL/VnHAc/

Now this way you don't have to create any map or Object to store these relations (you don't even need ids for individual textboxes!) By using data-* attributes, you do not have to modify a "map" every single time you add connections. In fact, this is the preferred way1 of doing it in HTML5.

1 https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.