简体   繁体   中英

In MVC partial view, how to find main view's element, and change its boolean value?

I have a partial view and I want to find a specific element in the parent view, and change its value.

$(document).ready(function(){
    $('.editBtn, .cancelBtn').on('click', function () {
           $(/*parent's body id???*/)find('#Smoker').val('true');
        });
});

In this case #Smoker is the element I want to have its value modified.

If you are referencing an element by its ID, then simply use the ID attribute itself (as ID attributes are unique by definition ) :

$('.editBtn, .cancelBtn').on('click', function () {
       // This should always work as #Smoker should be unique
       $('#Smoker').val('true');
});

If you really want to use the parent, then you can use the parent() or closest() functions to scope where you want to search for your element at relative to the element that triggered the function :

$('.editBtn, .cancelBtn').on('click', function () {
       // Find the #Smoker element using the parent
       $('#Smoker',$(this).parent()).val('true');
       // Find the #Smoker element within the closest parent <div>
       $('#Smoker',$(this).closest('div')).val('true');
});

Both of these functions should be unnecessary though, since you shouldn't have more than one "#Smoker" element present in the DOM.

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