简体   繁体   中英

jQuery find all input type with select for ajax request

I am trying to perform an ajax request by setting FormData using jquery each loop after finding input and select element for update as follows:

$(document).on("click", ".update", function (e) {
    e.preventDefault();
    e.stopPropagation();

    let thisBtn = $(this);
    //Form Data
    let formData = new FormData();
    let thisRow = thisBtn.closest("tr");
    thisRow.find("input,select").each(function() {
        //console.log(this.value)
        formData.append($(this).attr('name'), $(this).val());
    });

    $.ajax({
        type: "POST",
        url: '<?php echo base_url()?>exam/update',
        data: formData,
        processData: false,
        contentType: false,
        success:function(data){
            if($.trim(data)=='yes')
            {
                alert('Success! Record updated successfully');
            }
            else
            {
                alert('Error! Record not updated successfully')
            }
        }
    });

});

But getting some undefined params as follows:

在此处输入图片说明

But I want pure parameters except undefined

Without seeing your HTML we can't tell you exactly why, but from the output it's clear that you have some input and/or select elements in your form which have no name or value . They're probably hidden, so check the DOM inspector to find and remove them.

If you don't want to amend the HTML, then you can use an attribute selector to only find the input and select elements which have a name , like this:

let $thisBtn = $(this);
let formData = new FormData();
let $thisRow = $thisBtn.closest("tr");
$thisRow.find("input[name], select[name]").each(function() {
  formData.append(this.name, $(this).val());
});

It seems that this piece of code is finding inputs/select which name attribute is undefined, what would explain the fact you are getting undefined values in the formData.

 thisRow.find("input,select").each(function() {
    //alert(this.value)
    formData.append($(this).attr('name'), $(this).val());
});

I would recommend you to check whether the name is undefined before adding to the formData.

thisRow.find("input,select").each(function() {
    //alert(this.value)
    if($(this).attr('name'))
    {
        formData.append($(this).attr('name'), $(this).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