Skip to content Skip to sidebar Skip to footer

Js/jquery: Dynamically Add "pattern" And "title" Attribute To Form Input

I have multiple form input elements. I would like to add a pattern attribute and a title attribute to each one, but rather than do so manually, I want to dynamically add the same

Solution 1:

In the end, I found that the syntax was correct. There was an error somewhere else in the code preventing that statement from being run. Just goes to show that you should always make sure everything is good elsewhere in your code first.

However, I did learn a few things from this which I will note for others:

  1. The jQuery .attr() function will dynamically add any attribute you specify, so you don't need to put pattern="" in your form elements first in order for the value to be added or changed.
  2. Of important note, if you are going to dynamically add a regex using jQuery, YOU NEED TO ESCAPE certain characters.

The regex was originally \d*\.?\d* but in the DOM it was showing up as d*.?d* so when sending the regex through jQuery I escaped the backslashes like so: \\d*\\.?\\d*.

  1. Finally, I did not have to make my fields required for the regex to work. The HMTL5 validation only threw an error for me if I included incorrect text in the field, and when it threw an error, the form was not submitted. If I left the fields empty or put correct text in the fields, then no error was thrown. I'm up for an explanation if I'm wrong.

Post a Comment for "Js/jquery: Dynamically Add "pattern" And "title" Attribute To Form Input"