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 pattern and title to each form input using JavaScript/jQuery.

This is what the form input fields look like now:

<input type="text" class="form-control" id="paycheck" />
<input type="text" class="form-control" id="investments" />
<input type="text" class="form-control" id="otherIncome" />

As an end result I would like each form input to look like the following:

<input pattern="\d*\.?\d*" title="blah blah blah" type="text" class="form-control" id="paycheck" />
etc...

As examples, I've tried the following for the pattern attribute, but none of them work:

$( "input" ).attr("pattern", '\d*\.?\d*');
$( "input" ).attr("pattern",  \d*\.?\d* );
$( ".formClass input" ).attr("pattern", '\d*\.?\d*');

$( "input" ).prop("pattern", '\d*\.?\d*');
$( "input" ).prop("pattern",  \d*\.?\d* );
$( ".formClass input" ).prop("pattern", '\d*\.?\d*');

...imagine something similar for the title attribute...

Answers:

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.