1

I have problems accessing my form from the JS file, and I don't know how to access it. Here's my code:

$("#my-form").submit(function(e) {
  e.preventDefault();
  var textInput = $("#my-input").val();
  $("#container").html(textInput);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container" class="container-fluid"></div>
<script id="view-contact" type="text/html">
  <form id="my-form" class="form">
    <input id="my-input" type="text">
    <input type="submit">
  </form>
</script>

3
  • The form is html it shouldn't be inside the script Commented Feb 14, 2021 at 12:09
  • Why is there a <script> tag around your form? Remove it, then your code will work. Commented Feb 14, 2021 at 12:10
  • If you're using a <script> as some for of hack replacement for a <template> element (or even if you're using an actual template element) then there isn't going to be a submit button to trigger the submit event without some code to create an actual form in the document. Provide a minimal reproducible example Commented Feb 14, 2021 at 20:53

1 Answer 1

1

Don't put your html inside the <script> tag. Put your JavaScript / JQuery inside the script tag.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container" class="container-fluid"></div>
<form id="my-form" class="form">
  <input id="my-input" type="text">
  <input type="submit">
</form>
<script>
  $("#my-form").submit(function(e) {
    e.preventDefault();
    var textInput = $("#my-input").val();
    $("#container").html(textInput);
  });
</script>

Sign up to request clarification or add additional context in comments.

2 Comments

But can i access the form in any way when it is located in a script? I am trying to make a one-page website..
then don't put the form inside the script put your jquery / js code inside the script

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.