× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Avoid using IDs. Search within components instead.

James Jensen
Oct 08, 2014
<p>People will commonly use IDs to identify and retrieve elements on their page in JavaScript. </p><pre><code class="language-html">&lt;form onsubmit="onSearch(this)"&gt; &lt;input id="search_box"&gt; &lt;/form&gt;</code></pre><pre><code class="language-javascript">function onSearch(form) { var searchValue = $('#search_box').val(); ... }</code></pre><p>However, IDs are always universal, so this would break if you had two search forms like this on the same page (in different modal dialogs for example). Instead, try using classes, and only searching within the target form:</p><pre><code class="language-html">&lt;form onsubmit="onSearch(this)"&gt; &lt;input class="search-box"&gt; &lt;/form&gt;</code></pre><pre><code class="language-javascript">function onSearch(form) { var searchValue = $('.search-box', form).val(); ... }</code></pre><p> </p>
comments powered by Disqus