{"id":203,"date":"2012-05-13T11:38:33","date_gmt":"2012-05-13T03:38:33","guid":{"rendered":"https:\/\/www.techcoil.com\/blog\/?p=203"},"modified":"2018-09-03T22:08:41","modified_gmt":"2018-09-03T14:08:41","slug":"handy-javascript-code-segments","status":"publish","type":"post","link":"https:\/\/www.techcoil.com\/blog\/handy-javascript-code-segments\/","title":{"rendered":"Handy Javascript code segments"},"content":{"rendered":"<p>The augmentation of Javascript to CSS and HTML is beautiful. While trying out <a href=\"http:\/\/jquery.com\/\" title=\"Link to jQuery.com\" target=\"_blank\">jQuery<\/a> to create my own <a href=\"http:\/\/www.techcoil.com\/blog\/life-bits\/jquery-tic-tac-toe\/\" title=\"jQuery tic tac toe\" target=\"_blank\">tic tac toe game<\/a>, I realised that there are Javascript\/jQuery code segments that could be helpful to me when building web applications.<\/p>\n<p>In this post, I collate Javascript and jQuery code segments that I had utilized in my web projects for ease of future references.<\/p>\n<h3>DOM manipulation<\/h3>\n<h4>Get a jQuery reference for manipulating a DOM element<\/h4>\n<p>Suppose we have a html input text field<\/p>\n<pre class=\"brush: xml; title: ; notranslate\" title=\"\">\r\n&lt;input id=&quot;nameTextField&quot; name=&quot;name&quot; type=&quot;text&quot;\/&gt;\r\n<\/pre>\n<p>The following will get a jQuery reference that allow us to act on the input text field. <\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n$nameTextField = $('#nameTextField');\r\n<\/pre>\n<h4>Check whether a DOM element exists<\/h4>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n\/\/ Get a jQuery reference with id\r\n\/\/ as nameTextField\r\n$nameTextField = $('#nameTextField');\r\n\/\/ If jQuery contains no results\r\nif ($nameTextField.length == 0) {\r\n    alert('nameTextField does not exists.');\r\n} \r\nelse {\r\n    alert('nameTextField exists.');\r\n} \/\/ end if\r\n<\/pre>\n<h4>Hide a DOM element<\/h4>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n\/\/ Get a jQuery reference to a DOM element with id\r\n\/\/ as nameTextField\r\n$nameTextField = $('#nameTextField');\r\n\/\/ Hide the DOM element\r\n$nameTextField.hide();\r\n<\/pre>\n<h4>Show a DOM element<\/h4>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n\/\/ Get a jQuery reference to a DOM element with id\r\n\/\/ as nameTextField\r\n$nameTextField = $('#nameTextField');\r\n\/\/ Show the DOM element\r\n$nameTextField.show();\r\n<\/pre>\n<h4>Set the HTML contents of a DOM element<\/h4>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n\/\/ Get a jQuery reference to a DOM element with id\r\n\/\/ as firstParagraph\r\n$firstParagraph= $('#firstParagraph');\r\n$firstParagraph.html('New contents');\r\n<\/pre>\n<h4>Add a DOM element as a sibling to another DOM element<\/h4>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n\/\/ Get a jQuery reference to a DOM element with id\r\n\/\/ as nameTextField\r\n$nameTextField = $('#nameTextField');\r\n\/\/ Add a paragraph as a sibling right \r\n\/\/ after nameTextField\r\n$nameTextField.after('&lt;p&gt;A paragraph after nameTextField.&lt;\/p&gt;');\r\n\r\n\/\/ Add a paragraph as a sibling \r\n\/\/ before nameTextField\r\n$nameTextField.before('&lt;p&gt;A paragraph before nameTextField.&lt;\/p&gt;');\r\n<\/pre>\n<h4>Remove a DOM element<\/h4>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n\/\/ Get a jQuery reference with id\r\n\/\/ as nameTextField\r\n$nameTextField = $('#nameTextField');\r\n\/\/ Remove the DOM element with id as nameTextField\r\n$nameTextField.remove();\r\n<\/pre>\n<h4>Check whether there is a sibling element after a DOM element<\/h4>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n\/\/ Get a jQuery reference with id\r\n\/\/ as nameTextField\r\n$nameTextField = $('#nameTextField');\r\nif ($nameTextField.next().length == 0) {\r\n    alert('There is no sibling element after nameTextField');\r\n}\r\nelse {\r\n    alert('There is a sibling element after nameTextField');\r\n} \/\/ end if\r\n\r\n<\/pre>\n<h4>Check whether there is a sibling element before a DOM element<\/h4>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n\/\/ Get a jQuery reference with id\r\n\/\/ as nameTextField\r\n$nameTextField = $('#nameTextField');\r\nif ($nameTextField.prev().length == 0) {\r\n    alert('There is no sibling element before nameTextField');\r\n}\r\nelse {\r\n    alert('There is a sibling element before nameTextField');\r\n} \/\/ end if\r\n<\/pre>\n<h4>Add a CSS style class to a DOM element<\/h4>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n\/\/ Get a jQuery reference with id\r\n\/\/ as nameTextField\r\n$nameTextField = $('#nameTextField');\r\n\/\/ Add the style class errorField to \r\n\/\/ nameTextField\r\n$nameTextField.addClass('errorField');\r\n<\/pre>\n<h4>Remove a CSS style class from a DOM element<\/h4>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n\/\/ Get a jQuery reference with id\r\n\/\/ as nameTextField\r\n$nameTextField = $('#nameTextField');\r\n\/\/ Remove the style class errorField to \r\n\/\/ nameTextField\r\n$nameTextField.removeClass('errorField');\r\n<\/pre>\n<h4>Detect clicks on a DOM element<\/h4>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n\/\/ Get a jQuery reference with id\r\n\/\/ as nameTextField\r\n$nameTextField = $('#nameTextField');\r\n\/\/ Add a function callback to the click\r\n\/\/ event for nameTextField\r\n$nameTextField.click(\r\n    function(event) {\r\n        alert('You had clicked on nameTextField.');\r\n    } \/\/ end function(event)\r\n);\r\n<\/pre>\n<h4>Detect form submission<\/h4>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n$contactMeForm = $('#contactMeForm');\r\n$contactMeForm.submit(\r\n    function(event) {\r\n        alert('Form had been submitted');\r\n    } \/\/ end function\r\n);\r\n<\/pre>\n<p>Returning a false value inside the callback function can prevent the form from submitting the input contents to the server end. This is useful for form validation.<\/p>\n<h3>Field inputs and string value checking<\/h3>\n<h4>Get value of input text fields<\/h4>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n\/\/ Get a jQuery reference with id\r\n\/\/ as nameTextField\r\n$nameTextField = $('#nameTextField');\r\nname = $nameTextField.val();\r\n<\/pre>\n<h4>Check whether a checkbox is checked<\/h4>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n\/\/ Get a jQuery reference with id as \r\n\/\/ milkOptionCheckbox\r\n$milkOptionCheckBox = $('#milkOptionCheckbox');\r\nif ($milkOptionCheckBox.is(':checked')) {\r\n    alert('You have indicated that you like to drink milk.');\r\n}\r\nelse {\r\n    alert('You have indicated that you do not like to drink milk.');\r\n} \/\/ end if\r\n\r\n<\/pre>\n<h4>Get the length of a string<\/h4>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nstr = 'Hello there!';\r\nalert('Length of str: ' + str.length);\r\n<\/pre>\n<h4>Remove leading and trailing whitespaces<\/h4>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nvalue = '   some value.  ';\r\ntrimmedValue = $.trim(value);\r\n<\/pre>\n<h4>Check whether a string value contains only numbers<\/h4>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nnumberRegEx = \/^&#x5B;0-9]+$\/;\r\nvalue = '$1234567';\r\n\r\n\/\/ If value contains only numbers\r\nif (numberRegEx.test(value)) {\r\n\talert('Value contains only numbers');\r\n}\r\nelse  {\r\n\talert('Value contains other non-numeric characters');\r\n} \/\/ end if (numberRegEx.test(value))\r\n<\/pre>\n<p>Because of the dollar sign ($) in the <code>value<\/code> variable, the example code will display a dialog box with the message \"Value contains other non-numeric characters\".<\/p>\n<p>Note the importance of the ^ and $ characters in numberRegEx. They specify that the regular expression matching spans from the <strong>start<\/strong> to the <strong>end<\/strong> of the test value. The + character indicates that there should be at least 1 number.<\/p>\n<p>Without these two characters, the example code will display a dialog box with the message \"Value contains only numbers\". <\/p>\n<h4>Check whether a string value contains specific number of numbers<\/h4>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nsevenNumbersAfterSixRegEx = \/^&#x5B;6]&#x5B;0-9]{7}$\/;\r\nvalue = '12345678';\r\n\r\nif (sevenNumbersAfterSixRegEx.test(value)) {\r\n    alert('Value contains a 6 followed by exactly 7 other digits.');\r\n}\r\nelse {\r\n    alert('Value is not of the format that we desire.');\r\n} \/\/ end if\r\n<\/pre>\n<p>Because the number contained in <code>value<\/code> does not start with a 6, the example code will display a dialog box with the message \"Value is not of the format that we desire.\".<\/p>\n<p>As with the previous example, the ^ and $ characters specify that the regular expression matching spans from the <strong>start<\/strong> to the <strong>end<\/strong> of the test value.<\/p>\n<p>Within the ^ and $ characters, the matching consists of two main parts. <\/p>\n<ol>\n<li><code>[6]<\/code> matches the number 6.<\/li>\n<li><code>[0-9]{7}<\/code> matches any digit from 0 to 9, appearing for exactly 7 times.<\/li>\n<\/ol>\n<h4>Check whether a string value contains a decimal value to 2 decimal places and less than 100<\/h4>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\ndecimalsLessThan100RegEx = \/^(&#x5B;0-9]{1,2}\\.)?&#x5B;0-9]{1,2}$\/;\r\nvalue = '56.78';\r\n\r\nif (decimalsLessThan100RegEx.test(value)) {\r\n    alert('Value contains a decimal value to 2 decimal places and less than 100.');\r\n}\r\nelse {\r\n    alert('Value is not of the format that we desire.');\r\n} \/\/ end if\r\n<\/pre>\n<h4>Check whether a string value contains only words and spaces<\/h4>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nonlyWordsAndSpacesRegEx = \/^&#x5B;a-zA-Z\\s]+$\/;\r\nvalue = &quot;I contain some signs&quot;;\r\nif (onlyWordsAndSpacesRegEx.test(value)) {\r\n\talert('Value contains only words and spaces.');\r\n}\r\nelse {\r\n\talert('Value contains other unwanted characters.');\r\n} \/\/ end if\r\n<\/pre>\n<h4>Check whether email is valid<\/h4>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n\r\nemailRegEx = \/^&#x5B;_A-Za-z0-9-]+(\\.&#x5B;_A-Za-z0-9-]+)*@&#x5B;A-Za-z0-9]+(\\.&#x5B;A-Za-z0-9]+)*(\\.&#x5B;A-Za-z]{2,})$\/;\r\nvalue = 'techcoil@example.com';\r\n\r\nif (emailRegEx.test(value)) {\r\n    alert('Email is in a valid form.');\r\n} \r\nelse {\r\n    alert('Email is not in a valid form.');\r\n} \/\/ end \r\n<\/pre>\n<p>Regular expression pattern taken from <a href=\"http:\/\/www.mkyong.com\/regular-expressions\/how-to-validate-email-address-with-regular-expression\/\" title=\"mkyong.com's regular expression pattern for email validating email\" target=\"_blank\">mkyong.com<\/a>.<\/p>\n<h3>Related posts<\/h3>\n<ul>\n<li><a href=\"http:\/\/www.techcoil.com\/blog\/quick-references\/code-segments-for-rendering-html-4-0-pages\/\" title=\"Code segments for rendering html 4.0 pages\" target=\"_blank\">Code segments for rendering html 4.0 pages<\/a><\/li>\n<li><a href=\"http:\/\/www.techcoil.com\/blog\/quick-references\/how-to-validate-input-fields-as-the-user-is-filling-up-a-form-with-jquery\/\" title=\"How to validate input fields as the user is filling up a form with jQuery\" target=\"_blank\">How to validate input fields as the user is filling up a form with jQuery<\/a><\/li>\n<li><a href=\"http:\/\/www.techcoil.com\/blog\/quick-references\/how-to-send-http-post-requests-and-http-get-requests-using-jquery\/\" title=\"How to send HTTP post requests and HTTP get requests using jQuery\" target=\"_blank\">How to send HTTP post requests and HTTP get requests using jQuery<\/a><\/li>\n<li><a href=\"http:\/\/www.techcoil.com\/blog\/how-to-ensure-that-your-javascript-is-able-to-write-unicode-characters-from-external-javascript-files-to-your-html-contents\/\" title=\"How to ensure that your Javascript is able to write unicode characters from external Javascript files to your HTML contents\" target=\"_blank\">How to ensure that your Javascript is able to write unicode characters from external Javascript files to your HTML contents<\/a><\/li>\n<li><a href=\"http:\/\/www.techcoil.com\/blog\/deciding-which-http-status-code-to-use-in-a-http-response\/\" title=\"Deciding which HTTP status code to use in a HTTP response\" target=\"_blank\">Deciding which HTTP status code to use in a HTTP response<\/a><\/li>\n<\/ul>\n\n      <ul id=\"social-sharing-buttons-list\">\n        <li class=\"facebook\">\n          <a href=\"https:\/\/www.facebook.com\/sharer\/sharer.php?u=https%3A%2F%2Fwp.me%2Fp245TQ-3h\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n            <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Facebook.png\" alt=\"Facebook icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"twitter\">\n          <a href=\"https:\/\/twitter.com\/intent\/tweet?text=&url=https%3A%2F%2Fwp.me%2Fp245TQ-3h&via=Techcoil_com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Twitter.png\" alt=\"Twitter icon\"> Tweet\n          <\/a>\n        <\/li>\n        <li class=\"linkedin\">\n          <a href=\"https:\/\/www.linkedin.com\/shareArticle?mini=1&title=&url=https%3A%2F%2Fwp.me%2Fp245TQ-3h&source=https:\/\/www.techcoil.com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/linkedin.png\" alt=\"Linkedin icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"pinterest\">\n          <a href=\"https:\/\/pinterest.com\/pin\/create\/button\/?url=https%3A%2F%2Fwww.techcoil.com%2Fblog%2Fwp-json%2Fwp%2Fv2%2Fposts%2F203&description=\" class=\"pin-it-button\" target=\"_blank\" role=\"button\" rel=\"nofollow\" count-layout=\"horizontal\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Pinterest.png\" alt=\"Pinterest icon\"> Save\n          <\/a>\n        <\/li>\n      <\/ul>\n    ","protected":false},"excerpt":{"rendered":"<p>The augmentation of Javascript to CSS and HTML is beautiful. While trying out <a href=\"http:\/\/jquery.com\/\" title=\"Link to jQuery.com\" target=\"_blank\">jQuery<\/a> to create my own <a href=\"http:\/\/www.techcoil.com\/blog\/life-bits\/jquery-tic-tac-toe\/\" title=\"jQuery tic tac toe\" target=\"_blank\">tic tac toe game<\/a>, I realised that there are Javascript\/jQuery code segments that could be helpful to me when building web applications.<\/p>\n<p>In this post, I collate Javascript and jQuery code segments that I had utilized in my web projects for ease of future references.<\/p>\n","protected":false},"author":1,"featured_media":1213,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"advanced_seo_description":"","jetpack_seo_html_title":"","jetpack_seo_noindex":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":true,"_jetpack_newsletter_tier_id":0,"footnotes":""},"categories":[375],"tags":[133,130,131,132,134,129,128,89],"jetpack_featured_media_url":"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/JavaScript-Logo.gif","jetpack_shortlink":"https:\/\/wp.me\/p245TQ-3h","jetpack-related-posts":[],"jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/203"}],"collection":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/comments?post=203"}],"version-history":[{"count":0,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/203\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media\/1213"}],"wp:attachment":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media?parent=203"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/categories?post=203"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/tags?post=203"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}