简体   繁体   中英

JQuery getting the closest element and filtering children

I have 3 forms with IDs ( form1 , form2 , form 3). every form has its own different drop down lists (drop1, drop2) and submit button. When you click submit button in every form . It checks which option (in the drop down list of the same form) is selected . To find the exact selected Option I use this code :

    $(".submitButton").each(function(){

          $( this ).click(function(){buttonAddClicked(1)});
    });


    function buttonAddClicked(FormID){
          $('form'+ FormID +' *').filter('.MyDropDownList').each( function(){

           var selOption=$(this).find('option:selected');
    }

Till now everything is working fine. I get the selected option with no problems at all.But, when I make some modifications problems happens.

On document ready, I copy form1 html . So, form1 is duplicated with the same id.

--Let's say that I have form1A , form1B--

When I press submit button in form1A or form1B the code always go to the selected option in form1A. This problem is killing me .

How can I modify my code to catch the form closest form . I tried some techniques but didn't work . The problem is in using ('*') with filter with closest. Or if There's another solution to solve this I would be very thankful for you guys . Thank you .

Edit: I can Get the closest form easily , but how to loop (each) on that form Drop-Down-Lists,

The problem is for all button clicks you are passing 1 as the form id.

There is no need for that, assuming the button is within the form then, you can use .closest() to find the form which contains the button then use .find() to find the select element and .val() to find its selected value as shown below

jQuery(function () {
    $(".submitButton").click(function () {
        var $form = $(this).closest('form');
        var selectedValue = $form.find('.MyDropDownList').val();
        //do whatever you want to do with the selectedvalue

        //if you have multiple elements and wants to have an array of values
        var selectedValues = $form.find('.MyDropDownList').map(function () {
            return $(this).val()
        }).get();
    });
})

First, you should never have duplicate IDs in the document. It causes problems with assistive technology. So the best solution is to modify the ID when you duplicate the form.

However, you can use jQuery's closest to find the closest parent http://api.jquery.com/closest/

function buttonAddClicked(){
    var selOption = $(this).closest('form').find('.MyDropDownList').val();
}

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