views:

175

answers:

3

I have a field in my model - call it 'distance' - and I want to write a view that contains both a checkbox and a textbox.

If the checkbox is checked, the textbox becomes disabled and 'distance' gets the value 0 when the form is submitted.

If the checkbox is not checked, 'distance' gets whatever value is in the textbox when the form is submitted.

Anybody have any guidance how to do this? It's the logic of assigning a model value based on the state of both the controls that confusing me...

+1  A: 

The UI behaviour can be accomplished with Javascript via an onclick event handler on the checkbox. The only value you need to submit is the input field whose value will be set to 0 or whatever is set manually.

With jQuery you would have:

$('#checkbox_id').click(function() { $('inputfield_id').val('0');
aleemb
I'll give it a try and let you know. Thanks!
You should ignore the checkbox completely and just focus on the text input field control. The check in the field simply sets the text input value to 0.
aleemb
+1  A: 

The Model behavior depends on what the checkbox represents. If it's an actual property on the Model, then you will need to check the value server-side as well as (optionally) using aleemb's javascript method.

If a check in that field simply represents a distance of zero, then aleemb's method will suffice.

Peter J
There's only one property on the Model in all of this. I just thought it'd be more complicated than it looks because there are two controls that conspire to set a single value.
A: 

Aleemb's answer worked like a charm, with a couple of minor modifications:

$("#Distance_checkbox").click(function() {
    if ($(this).is(':checked')) {
        $("#Distance_textbox").val(0);
        $("#Distance_textbox").attr("disabled", true);
    }
    else {
        $("#Distance_textbox").val("");
        $("#Distance_textbox").attr("disabled", false);
    }
});