2

I am using asp.net and its html helpers. The HTML.CheckBoxFor helper returns a check box Element like the one bellow.

<input data-val="true" 
    data-val-required="The isNewlyEnrolled field is required." 
    id="isNewlyEnrolled" 
    name="isNewlyEnrolled" 
    type="checkbox" 
    value="true" />

<input name="isNewlyEnrolled" type="hidden" value="false" />

The second input is used for submit purposes. Using JQuery I would like to return only the current or new value when the relative check box is clicked. However this is proving to be difficult.

Here is my code:

@model MapBuilder2_0.Models.MapLayers
<h1>Map Layers</h1>
<p>Select the layers to be included on the <b>map</b>. All are selected by default.</p>
<div class="btn-group" id="map-layers-btn">
<label class="btn btn-primary active">
    Layer1
    @Html.CheckBoxFor(m => m.MapLayer01)   
</label>
<label class="btn btn-primary active">
    Layer 2
    @Html.CheckBoxFor(m => m.MapLayer02)   
</label>
<label class="btn btn-primary active">
    Layer 3
    @Html.CheckBoxFor(m => m.MapLayer03)   
</label>
<label class="btn btn-primary active">
    Layer 4
    @Html.CheckBoxFor(m => m.MapLayer04)   
</label>
<label class="btn btn-primary active">
    Layer 5
    @Html.CheckBoxFor(m => m.MapLayer05)   
</label>
<label class="btn btn-primary active">
    Layer 6
    @Html.CheckBoxFor(m => m.MapLayer06)   
</label>

How can i return the appropriate value to indicate the check box selection each time it is clicked?

I've attempted to select the values using the bellow jquery but i think the fact that there is two inputs with the same name is problematic. It is doing two things i cannot understand. 1) it returns two values (im assuming one for each input) and 2) it does not change to reflect weather it is selected or not. it only returns the initial true value.

<script>
$(document).ready(function () {
    $("#map-layers-btn").children("label").on('click', function () {
        var child = $(this).children("input");
        var child_val = child.attr("value");

        alert(child_vala);

    });
});

1 Answer 1

3

To get the checkbox value in jQuery you need .prop().

For the double element problem you can give your helper a class and only the main <input> will receive this class.

@Html.CheckBoxFor(m => m.MapLayer1, new { @class="mapchk" })

Making your click handler simpler and registered only for the primary input.

$(".mapchk").on("click", function(e) {
    var isChecked = $(this).prop("checked");
    console.log(isChecked);
});
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.