Anish Balay
Anish Balay

Reputation: 13

Jquery form element access

I'm new to jquery and trying to do the following:

I have a form:

<form method="POST" class="add-product" >
...
<label name="message"></label>
...
</form>

And script:

$(document).ready(function() {
$(".add-product").submit(function(e) {
    e.preventDefault();
    var form = this;
    $.ajax({
        type: "POST",
        url: "/product/add/",
        data: $(this).serialize(),
        success: function(data) {
            $(form.elements["message"]).html(data.message);
        }
    });
});

});

I'm trying to update label with message, but it doesn't work. Seems that I have some mistake in syntax:

$(form.elements["message"]).html(data.message);

Upvotes: 1

Views: 55

Answers (3)

ajtrichards
ajtrichards

Reputation: 30530

Try using the selector:

$("form.add-product label[name='message']").html(data.message)

You can read more about jQuery Attribute selector's here. https://api.jquery.com/attribute-equals-selector/

If you have more than one label on the page with the attribute name='message' then the above won't work.

Upvotes: 0

Anph
Anph

Reputation: 163

You used wrong jquery selector, try it:

$('label[name="message"]').html(data.message);

hope this help;

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337733

The issue is because the label does not appear in the form.elements collection. Instead you need to select it directly:

$(".add-product").submit(function(e) {
  e.preventDefault();
  var form = this;

  // inside the AJAX callback...
  var data = {
    message: 'Foo bar'
  }
  $(form).find('label[name="message"]').html(data.message);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="POST" class="add-product">
  <label name="message"></label>

  <button>Submit</button>
</form>

Upvotes: 2

Related Questions