Jaromando
Jaromando

Reputation: 329

Utilize on.("submit") With HTML Form Not Working

Could anyone give me a clue as to why this would not work.

I have a form:

<form id="add">
    .
    .
    .
    <button id="button1" type="submit">Submit</button>
</form>

And want to make inputs within the form readonly on submit (I know there is better ways to accomplish this but I am looking at this specific situation).

Why would this jquery not work:

$(document).ready(function(){

    $("#add").on("submit", "input", function(event) {
        console.log("hello");
        event.preventDefault();
        $(this).prop("readonly", true);
    });

});

Thanks!

Upvotes: 2

Views: 66

Answers (2)

Always Helping
Always Helping

Reputation: 14570

You are actually not adding a readonly attribute on your inputs on submit event but $(this) actually refers to the whole HTML form - which you can not apply readonly attribute to.

Why your example does not work: You are event binding the form submit on an input which is a part of the form. That means your eventDelegation is on the inputs which are in the form and the submit handler is a button type="submit"- so doing this way will always refresh the page and will not submit the form nor set the prop to readonly. In a nutshell it will not do anything at all because the eventDelegation is incorrect.

To enable all the inputs readyOnly on form submit you can use .find() method jQuery and looks for all :input including any textarea if you have one as well.

$(this).find(':input').prop("readonly", true); //prop all readonly

Also, you do not need to add input in your submit event function as well.

Working Demo:

$(document).ready(function() {
  $("#add").on("submit", function(event) {
    event.preventDefault();
    $(this).find(':input').prop("readonly", true); //prop all readonly
    console.log("form submitted - all inputs are readonly now");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

<form id="add">
  <input class="form-control" type="text" value="Some value" />
  <br>
  <input class="form-control" type="text" value="Some other value" />
  <br>
  <textarea class="form-control">I am a textarea</textarea>
  <br>
  <button class="btn btn-success" id="button1" type="submit">Click me to submit</button>
</form>

Upvotes: 1

Capsule
Capsule

Reputation: 6159

You're passing input as the second argument of on so essentially listening for a submit event on #add input. There's no submit event on inputs. Remove that second argument and you'll be fine.

Upvotes: 2

Related Questions