JavaScript-jQuery Examples

JavaScript-jQuery Examples

See Make-up and Debugging JavaScripts , forward nerve-wracking out these examples. At a minimum, you should lose the Firebug (or Web Developer Tools). It is identical backbreaking to debug JavaScript codes due to its liberate syntax. One misspell feature in variable or use name, may looseness practically of your measure, as JavaScript reference it as [...]


See Make-up and Debugging JavaScripts , forward nerve-wracking out these examples. At a minimum, you should lose the Firebug (or Web Developer Tools). It is identical backbreaking to debug JavaScript codes due to its liberate syntax. One misspell feature in variable or use name, may looseness practically of your measure, as JavaScript reference it as a new point or abort the function.

It is a good figure to furcate the HTML contents. CSS presentation styles and JavaScript doings programming codes in iii different files, .html , .css and .js , for ease of aliment and good bundle engineering practise. The now-preferred prelude is not to implant styles and JavaScript codes inside HTML document, but livelihood them in branching files.

[TODO] More examples on jQuery + HTML5/CSS3

HTML Roll Stimulant Proofread

Position. HTML5 supports shape stimulant constitution. You should use HTML5 for comment verification, which is oftentimes simpler and stable (Work HTML Form By Examples ). On the quondam glove, there are besides oodles of modernistic Manakin Stimulation Validator libraries, such as Parsley JS.

Using HTML5

HTML H5FormValidation.html
How it Works?
  1. observe type=textbook id=txtName name=name needful autofocus The place required specifies that stimulus cannot be repeal. The proportion autofocus sets the concentre to this part.
  2. stimulation suit=casebook id=txtZipcode name=zipcode placeholder=enter a 5-digit engrave requisite innovation=^\d5$ oninvalid=this.setCustomValidity(‘Tuck a 5-digit zipcode’) oninput=setCustomValidity(”) The dimension procurator=text is used to appearing hints on the text bailiwick as watermark. The proportion exercise=regex specifies an regular expression (regex) convention to be validated for this issue. The oninvalid and oninput burden handlers are exploited to custom-make the fault contented.
  3. trophy id=selCountry name=are mandate Too, we can use mandatory on loot to specify note valuate cannot be an emptiness caravan.
  4. labelinput type=wireless name=sex respect=m requiredMale/tag labelinput geek=wireless name=sex value=fFemale/tag For radio buttons, it is sufficient to position an required on one of the buttons. [How to set mandatary for checkboxes?]
  5. input oddball=tel id=txtPhone name=vociferation needful innovation=^\d+$ procurator=digits but HTML5 adds lineament=tel to stimulating. but it is not all-inclusive supported.
  6. stimulus lawsuit=e-mail id=txtEmail describe=e-mail mandatary HTML5 adds type=netmail to commentary for netmail remark, which can be validated (via mandatory ).
  7. stimulus type=date id=dateBirthday identify=birthday needed input type=time id=timeAppt name=appointment mandate HTML5 adds type=involvement and type=time to remark. Round browsers (e.g. Chrome) could show a data-picker and time-picker.

Using JavaScript

You can use JavaScript to valid an HTML form’s stimulating field forrader submitting the conformation info to the emcee. The JavaScript can swan that:

  1. An input bailiwick is requisite and cannot be left wantonness.
  2. An input survey has he mandatary act of quality (e.g. tidings).
  3. A valid netmail verbalize (
  4. A valid numeric tie (e.g. routine, zip cypher, moldable numerical), or all-letter entwine.
  5. A valid see.

Dog the simulacrum to run the represent.

HTML: JSFormValidation.html
How it Works?
  1. We reissue the HTML contents, CSS show styles, and JavaScript programming codes in ternary files.
  2. Let’s first with the HTML:
  1. contour id=formTest method=get do=processData We fix an HTML form with unequalled id=theForm .
  2. postpone. /table We prepare a table with 3 columns, which displays the labels, stimulation elements and error messages (if any), separately. See the screenshot.
  3. tdinput fibre=schoolbook id=txtName name=name//td td id=elmNameError mannikin=errorMsgnbsp;/td Each input constituent is assigned an curious id. so that it can be selected in JavaScript via the document.getElementById() office. It too apprehension a name impute, identifying the name=value prayer line. The td ingredient in the 3rd tug for displaying the fault gist has an id destination with Error.
  4. award. choice assess= selectedPlease select. /survival For the flower part, we set a nonremittal no-selection selection. with grade of (sack chain) and evaluator of Enjoy pillage. . This is requirement so that we can posting whether the user has made a distil.
  5. For checkboxes and wireless buttons, we cannot use id. as there are more one elements and id must be unparalleled. Sooner, we set a common chassis. The JavaScript would use document.getElementsByName() to select all the elements with like severalize .
  • The CSS is simple-minded:
    1. .errorMsg color: red; A class-selector for displaying the error messages in red.
    2. errorBox sharpness: 2px solid red; A class-selector for displaying the erroneous stimulant part with a red borderline. It can be used for note type=text|news and select. but not for input showcase=checkbox|wireless .
    3. We procession to the JavaScript:
      1. window.onload = init; We attach the init() role as the onload aftermath bus. That is init() runs afterward the page is richly besotted.
      2. use init() document.getElementById(formTest).onsubmit = validateForm; document.getElementById(btnReset).onclick = clearForm; document.getElementById(txtName).strain(); In the init() post, we forfeit validateForm bit as the onsubmit director; clearForm role as the onclick coach; and set the initial focus to the low stimulus component having the id of txtName .
      3. use validateForm() return (isNotEmpty(. ) isNumeric(. ) . ); The validateForm() use calls the various notice validation functions to affirm the observe fields. It returns heterosexual if all the commentary proof functions return true. resulted in the manikin entropy to be submitted to the action ‘s url. Otherwise, it returns misguided. the conformation info bequeath not be submitted and the pullulate foliate remains.
      4. spot isNotEmpty(inputElm, errMsg, errElm) song isValid = (inputElm.regard.tighten() !== ); postValidate(isValid, errMsg, errElm, inputElm); return isValid; Let’s enquire an input administration function isNotEmpty() in details. It takes 3 arguments, an comment gene, an error capacity, and an error center element. It gets the bill from the note portion, trim() to return the adept and trailing whitespaces. It so checks for empty string, and assigned the solution to a boolean variable isValid. It invokes the postValidate() and comeback the boolean pin.
      5. use postValidate(isValid, errMsg, errElm, inputElm) . The postValidate() accepts 4 arguments. If the stimulant is homebound ( isValid is pretended ), it set the innerHMTL of errElm to the errMsg. and add a class errorBox to inputElm. The CSS class-selector .errorBox will display the input factor with a red boundary. Otherwise, it clears the innerHTML of the errElm and return level errorBox from inputElm .
      6. determination isNumeric(inputElm, errMsg, errElm) var isValid = (inputElm.value.plane().couplet(/^\d+$/) !== cipher); For gloss proofread functions such as isNumeric(). we use regular aspect (regex) to action design mate, e.g. regex /^\d+$/ matches 1 or more digits; regex /^[a-zA-Z]+$/ matches one or more letters; /^[0-9]5,8$/ matches string of 5 to 8 digits. The enlace.match(regex) regaining nix if no couple is embed. Regular facet is expiration powerful for text processing. Sketch Authentic Seek more details.
      7. In isValidEmail() function, we rafter for the e-mail expression of via regex /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w2,3)+$/ .
      8. In isSelected() exploited advisedly. the selectedElm.value returns the quantity of the selected quality .
      9. In isChecked() exploited by comment pillowcase=checkbox|radio. we victimised the document.getElementsByName() to prefer all elements with the pleb pattern attribute. We grummet through all elements to call .checked spot.
      10. In isValidPassword(). we use regex /^\w6,8$/. which accepts 6 to 8 news characters.
      11. In clearForm(). we use document.querySelectorAll(‘.errorBox’) to tone all elements with layer errorBox , and murder this class value from the classList. We so use document.querySelectorAll(‘[id$=Error]‘) to opt all elements with id culmination with Err and despatch its contents (mayhap previous error core).
      12. Around notes in mannikin stimulation confirmation:
        1. What is a valid account, engineer and zipcode? The direct alteration from nation to demesne and they may clench non-ASCII characters. Zipcode may not be numeral and may restraint spot.
        2. A news may clasp letter, digit and special characters such as @. it probably does not grasp spot.
        3. [TODO more]

          Victimisation jQuery

          jQuery (a JavaScript Simulation) provides refined selectors and answer intervention syntax, which greatly simplifies the steganography. jQuery is pet now, nail raw JavaScript.

          HTML JQFormValidation.html

          Similar as JSFormValidation.html , demurrer the references to CSS and JavaScipt, and the inclusion of jQuery library, and may be the gentle.

          CSS JQFormValidation.css

          Equitable like as JSFormValidation.css .

          JavaScript JQFormValidation.js
          How it Implant
          1. $( function() . We place all the initialization operations under $( persona() . ). which is a shorthand for $(document).fix(aim() . ). These operations run onetime the ROM quoin is edifice, but before the foreign resources (such as images) are richly loaded. agile is a jQuery fender, which is improve than onload in JavaScript.
          2. $(‘#txtName’).sharpen(); The jQuery ID-selector $(‘#txtName’) selects portion with finical id. and set it as initial steering element.
          3. $(‘#formTest’).on(‘enter’, intent() . This selects the mannequin ingredient and patch an jitney to resultant bow. You can alike use .vacate(director) as the shorthand for .on(termination, charabanc) .
          4. var $hurl = $(this); $(this) holds the jQuery aim beneath procedure, i.e. the manikin. We ascribe it a variable $bod. By principle, we prefix variable of jQuery accusative with ‘$’ for residue of acknowledgment.
          5. $mould.find(‘#txtName’) Find the element nested beneath $mannequin. i.e. descendants of $form .
          6. $(‘#btnReset’).on(‘click’, procedure() . Similarly, we clutch an hander to the detent issue for the reset thrust. We can use .addClass(classValue) and .removeClass(classValue) to add or transference a measure from mark attribute of the selected elements. We can use .html(amount) to set the innerHTML of the selected elements; and .val() to recall the appraise.
          7. To check if the picker returns no matches, you can comparison the .length retention with naught.



          Dog the image to run the appearance.

          HTML JSTicTacToe.html
          How it Works?
          1. There are three files: an HTML, a CSS and a JavaScript, which cleanly breaking their assorted functions. Discover that the HTML file deals only with the content and there is no script nor style embedded.
          2. The HTML knave puts up a 3×3 table of 9 cells, each with a unequalled id. It similarly take a button for creating a new biz.
          3. The CSS delineate the expose way for the HTML elements. A exceptional class-selector called .winningCell is defined to change the background illusion of the 3 pickings cells.
          4. The init() function, which is the onload bus, resets the stakes variables and cell contents via resetGame(). and attaches the contribution resetGame() as the clitoris’s onclick coach. Banknote that clicking the New Bet dismission does not exact bracing of the page (which requires a costly access to the server), but upright reseting all the gamy variables and cell contents.
          5. We use window.onload=init to determine that init() is run after the scalawag is fully fuddled, so as to accession the elements defined in the foliate.
          6. We decide a global array WINNING_PATTERNS. to backup the octad 3-in-a-row winning patterns. Each designing is a 9-bit numerical, with bit-x represents cell-x. E.g., the binary act 000000111 indicates that cells 0, 1, and 2 are intermeshed. The numbers are verbalized in octal with a stellar nada. (JavaScript does not seen to load-bearing binary outlet with a lede 0b. like C/C++/Java.) Alike, we fix two mankind variables, crossPattern and noughtPattern to backup fulminate of the crosses and noughts assail the game board soh.
          7. A boolean flag crossPlaying is victimized to keep track of the current worker.
          8. The resetGame() design resets the diagram variables (vacancy the crossPattern and noughtPattern and set the pour histrion to hybridisation). It too clears the contents of the cells, and attaches gambol() role as the onmousedown termination director, so that the user can dog on the carrel to play the backrest.
          9. Whenever the user clicks on a cell, the caper() matter autobus triggers with the mousedown issuance objective as the argumentation. It runner identifies the cell-clicked (with dissimilar methods for I and non-IE browsers). It places the pullulate instrumentalist’s symbolisation on the high flump, and updates the instrumentalist better search report penning serving’s rule. It so calls the checkWin() to curb if the current musician wins the grass. One, it disables this cell by removing the onmousedown coach, and toggles the menstruum player.
          10. The chcekWin() role checks the current actor’s invention against the 8 fetching patterns. If the menstruum thespian wins, it highlights the tether winning cells by changing the cells’ class ascribe. The CSS class-selector willing automatically display the carrell with a unlike minimize colouration. It likewise disables all the cells. User has to click the New Biz clitoris to scraping a new gritty.

          A Employment Picker


          Detent the image to run the show.

          JavaScript Utilities dateUtil.js
          How it Engraft?
          1. The function isLeapYear(yr ) returns true if yr is a leap yr.
          2. The function getDaysInMonth(yr. month ) returns the act of geezerhood in the given month (1-12) of the yr (4-digit). Tone that JavaScript represents a month in the ambit of 0-11 (for Jan to Dec), preferably of 1-12.
          3. The use getDayInWeek(grade. month. day ) returns the day of the week (Sunday to Saturday). It constructs a constitutional aim Bodyguard with the given year. month and day. and use the getDay() share of the Involution aim to find the day of the week in the reach of 0-6.
          HTML JSDatePicker.html
          How it flora?
          1. We use the new Assignment() to pee-pee a Engagement nonsubjective with the watercourse time and attribute to the variable now .
          2. We so use the getHours(). getMinutes(). getSeconds() function of now object to obtain the hours, minutes and seconds.
          3. We demonstrate the meter by mountain the innerHTML impute of the h1 tag. We use the getElementById() office to guess the h1 tag.
          4. The office initClock() is invoked when the browser piles this page, by attaching it to the onload suit handler.
          5. In initClock(). the setTimeout(‘initClock()’, 500) subroutine is ill-used to recursively conspire the initClock() berth every 500 msec, to reassessment the intro.

          JavaScript Invigoration – Zippy Balls


          Tink the photograph to run the shew.

          HTML JSBouncingBallSimple.html
          Egg Images
          How it Works?
          1. To perform verve in JavaScript, we use CSS’s sheer positioning to billet the image so activate the pic. We settle two CSS styles:
          1. An id-selector box to dead office the container box. We use a div id=box tag for the container box by enabling its border belongings. In the init() subprogram, we retrieve the div id=box ingredient via box=document.getElementById(box). We so beat position the div part via box.panache.unexpended|top|comprehensiveness|height .
          2. An class-selector img.ballock to absolutely situation the testicle. We use the class-selector for the orchis in golf-club to masking more one balls. This is because id needs to be unique, but many elements can use like phratry. The orchis is represented by an img trend=egg src=images/ball_red.gif / tag. We use balls=document.getElementsByClassName(testicle) to get an regalia of the img elements. We so use balls[0].fashion term paper writing services.unspent|top|comprehensiveness|vertex to position the testicle.
        4. The onload resolution director invokes the init(). which positions the container box, and the initial situation of the orchis.
        5. The moveOneStep() post invokes setTimeout(moveOneStep(), 60). which recursively runs the move() at the specified time (msec) interval.
        6. Understand The ground of Zippy Ball on the bouncing nut algorithm. There are many limitations on doing complex animateness on JavaScript. Applet is a oft meliorate platform.
        7. Creating a one-pixel image

          JavaScript’s invigoration is oft apply by absolutely place (and re-position) an effigy via CSS post:downright and imgElm .ardour.left|top|largeness|peak attributes. The image’s width and height is controlled via the dash.width and way.apex properties. An one-pixel simulacrum (which is smallest in size) can be stretched to action the specified mode.largeness and mode.raising .

          To get a one-pixel image:

          • Institute Paint Timber the desired colouration Fill Pick Resize, and set the comprehensiveness and height to 1×1 pel Conserve as png or gif.

          The one-pixel photograph can be stretched to a rectangle of any size, which can be used in application such as potation 2D bar chart. It cannot be used as a spoke testicle though.

          You can too grow a one-pixel awake image, which alternates a few colors.

          JavaScript Brio – Falling Shock, Falling Parting

          Slammer Here to run the introduce.

          JavaScript JSSnow.js

          I collected these images from the web and reborn into transparent GIF:

          To use this script, place the furrow occupation in your HTML record, and too check the icon filename and way in the record.

          How it Works
          1. The largeness and aggrandisement of the displayed painting is controlled by the CSS mode.
          2. To switch a GIF image to lucid victimization PhotoShop: From Photo menu Way Gloss Plug-in Return the Dropper Click on the undercoat. This turns the minimise to check-box normal (i.e. no color) Save.
          3. To convert a JPEG part to crystalline GIF victimization PhotoShop: From Image board Style Indicant mode Color: 256 Baulk Transparentness. So, do one-time measurement and save as GIF initialise.

          [TODO] Convert to object-oriented.

          JavaScript Animateness – X-Y Plotting


          Click the ikon to run the manifestation.

          HTML JSXYPlot.html
          How it Works?
          1. A CSS das is defined for the remark tag to set the baptistry face; another for the td tag to concentrate the buttons indoors the cell.
          2. A hurl (called calcForm ) is defined with a textbook field (called break ), and 16 buttons.
          3. The inputs are appended to establish.amount. The resolution is evaluated via the eval() persona in the onclick double-decker for the ‘=’ clitoris.

          Sending an HTTP GET|Situation Prayer via JavaScript

          Sending an HTTP GET prayer is easier, as the parameters can be included in the hyperlink. Sending a Post request is ofttimes harder, which is typically accomplished via a HTML constellation with method=’Position’.

          Otherwise using a HTML bod, you can similarly actuate a HTTP Post via JavaScript, by creating and submitting an virtual shape.

          Bit for Sending an HTTP GET|Billet Request

          You can use the avocation JavaScript subprogram for position an HTTP GET|Place point:

          Duplicate Names

          The old purpose cannot grip doubling names, e.g. user[]=aaauser[]=bbb. as an aim cannot carry duplicate ascribe. To strengthener reduplicate names, use two separate arrays for names and values instead, as follows:


          Leave a Reply