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...
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:
.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.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*
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With