简体   繁体   中英

ASP.NET MVC 4 Having trouble selecting the correct input element using js/jquery

I'm working with a form that I've built using HTML helpers, like so:

@using (Html.BeginForm("CreateNewRoom", "Admin", FormMethod.Post, new { @enctype = "multipart/form-data", @class = "form-vertical", style = "margin-top:-30px" }))
        {
            <fieldset>
                <legend>Create a new Room</legend>

                <div class="form-toolbar sepa">
                    <label class="darkBlue toolbar-label">Room name:</label>
                    <div>
                        @Html.TextBoxFor(x => x.name, new { @id = "room", @class = "form-control-static", @style = "margin-bottom:5px;", @autofocus = "true" })
                    </div>
                </div>

                ...

                <div class="form-toolbar sepa">
                    <label class="darkBlue toolbar-label">Display:</label>
                    <div>
                        @Html.RadioButtonFor(x => x.display, "True") Yes&nbsp
                        @Html.RadioButtonFor(x => x.display, "False") No&nbsp
                    </div>

                ...

Just in case it helps, Chrome DevTools informs me that this is the HTML being displayed by my radio button helper:

<input id="display" name="display" type="radio" value="True">
    " Yes&nbsp;                            "

<input checked="checked" id="display" name="display" type="radio" value="False">
    " No&nbsp;                            "

I have a Javascript file which dynamically plays with the elements on the page. I would like for js to add a class to an element on the page, to simply change its opacity to 0.5, if it finds that the "No" radio button is selected.

if ($('input[name="display"]').val() === "False") {
    if (($('#selectedRoomName')) && ($('#selectedRoomArrow')))
        $('#selectedRoomName').addClass('obscured');
        $('#selectedRoomArrow').addClass('obscured');
} else {
    //sad
}

I've used this block in $(document).ready and in $(input[name="display"]).change , to make js add the class if display is 'False' when the page loads, and also to add it if the 'False' radio button is selected.

However, I found that js had a problem reading the value of the input, and thinks that it is true almost all the time, even if the false button is selected. I'm assuming it must be something to do with the fact that the two inputs have the same name?

My question is, how do I ensure that js always picks the input that is currently selected, and will this make sure that it reads the correct value?

UPDATE : I have changed $('input[name="display"] to $('input[name="display"][checked="checked"]') , in an effort to make js home in on whichever radio button is checked. This solves the problem where js did not know which button was checked on page load. However, now it always targets whichever button was checked on page load, instead of the button that's actually checked currently.

Apologies if I seem like a complete novice, but I am, so...

Any and all suggestions on how to better organise my code are welcome; I'm very unfamiliar with best practises in web dev.

Thanks!

Just change the following line in your change event from :

if ($('input[name="display"]').val() === "False") {

to:

if ($(this).val() === "False") {

This will check for the value of the radio button that is current clicked.

I used a combination of @Ehsan's answer, and a partial solution that I included in an update to the the question.

I decided to place the js block in a function, which took the element whose value I was checking as a parameter:

function checkdisplay(dispradio) {
    var a = document.getElementById("selectedRoomName");
    var b = document.getElementById("selectedRoomArrow");
    if ((a) && (b)) {
        if (dispradio.val() === "False") {
            a.className += " obscured";
            b.className += " obscured";
        } else {
            a.className = a.className.replace(/(?:^|\s)obscured(?!\S)/g, '');
            b.className = b.className.replace(/(?:^|\s)obscured(?!\S)/g, '');
        }
    }
}

Then I called the function in two places like so:

//first for document load    
$(document).ready(function () {
    checkdisplay($('input[name="display"][checked="checked"]'));
});

and

//and then for change events
$('input[name="display"]').change(function () {
    checkdisplay($(this));
});

Seems like [checked="checked"] was needed to let js know which button was checked on page load, but that then needed to be removed for onchange events, or js would target whichever button was checked on page load, rather than the button that was actually checked!

Many thanks for your partial solution @Ehsan, it helped me come up with this one!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM