Miguel Moura
Miguel Moura

Reputation: 39394

Find inputs which name value present in an array of objects

I am submitting a form using JQuery 3 and AJAX as follows:

$("#send-question").on("submit", function (event) {

  event.preventDefault();

  $.post("api/questions", { content: "content" })
  .done(function (data, status, xhr) {
    console.log(data);
  })
  .fail(function (xhr, status, error) {

    var errors = $.parseJSON(xhr.responseText);

      $(this).find(":input[name]");

    });
});  

The object errors is an array of objects such as:

{ flag="content", info="the content is required" }

I need to find all inputs in the form that have the name attribute.

Then for those which name matches a flag on one error in the array just add the info in a span after the input:

input.parent().append("<span class='error'>" + error.info + "</span>");

I am just not sure how to find which inputs have an error in the array.

Upvotes: 0

Views: 57

Answers (1)

WebKenth
WebKenth

Reputation: 136

Go through each error and look for an input with the name of content. Might look something like this

errors.forEach(function(element, index, array){
    $('input[name="'+element.flag+'"]')
        .parent()
        .append("<span class='error'>" + element.info + "</span>");
})

Upvotes: 1

Related Questions