Multiple controls in MVC view that change the same model value

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

If the checkbox is checked, the text field is disabled and "distance" is set to 0 when the form is submitted.

If unchecked, "distance" is given any value in the text box when the form is submitted.

Does anyone have instructions on how to do this? It's the logic of assigning a value to the model based on the state of both controls, which is confusing me ...

0


a source to share


3 answers


The UI behavior can be done with Javascript using the onclick event handler. The only value you need to send is the input field, which will be set to 0 or whatever is manually set.

With jQuery, you would have:



$('#checkbox_id').click(function() { $('inputfield_id').val('0');

      

+1


a source


The behavior of the model depends on what the checkbox is. If it is an actual property in the model, you will need to validate the value on the server side as well (optionally) using the aleemb javascript method.



If the validation in this field simply represents zero distance, then the aleemb method will suffice.

+1


a source


Aleemb's answer worked like a charm, with a few minor changes:

$("#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);
    }
});

      

0


a source







All Articles