1

I need to select a form via native javascript (not jQuery) and prevent the form submission (preventDefault).

The trick is that the form does not have a name or id, and cannot be assigned one.

My HTML:

<div id="search">
    <form method="get">
        <input type="text" name="post"/>
        <input type="submit" value="Post">
    </form>
</div>

So far, I have tried to use document.forms[0] and document.getElementsByTagName("form")[0] to select the form, but the value returned is undefined.

Another possible solution is to overload the functionality of the submit button, but I did not have success with that either.

3 Answers 3

7

Using querySelector and an event listener, it's almost like jQuery

document.querySelector('#search form').addEventListener('submit', function(e) {
    e.preventDefault();
});

note that the script has to come after the elements, or use a DOM ready handler, so the elements are available.

FIDDLE

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

2 Comments

I tried something similar, but it tells me I cannot read property of null. I have no idea why it would be null...
It's because there is no element available, and it returns null, add the script after the elements in the DOM, and it will work.
1

on form submit just return false.

e.g. <form onsubmit="return false">

Comments

0

Simple way is use onsubmit event handler

<script>
var submitHandler = function() {
  // your code
  return false;
}
</script>

<form method="get" onsubmit="return submitHandler()">....</form>

or more easy

<form onsubmit="return false;">

1 Comment

Sorry I should have been a bit more clear, I cannot modify the markup in any way. @adeneo's solution worked, I was on the right track I just forgot the script had to be included after the markup on the HTML page.

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.