JS / JQuery:动态添加“模式”和“标题”属性以形成输入 [英] JS/JQuery: Dynamically add "pattern" and "title" attribute to form input

查看:103
本文介绍了JS / JQuery:动态添加“模式”和“标题”属性以形成输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个表单输入元素。我想为每个属性添加模式属性和标题属性,但不是手动执行,而是想要使用JavaScript / jQuery为每个表单输入动态添加相同的模式 title

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...

作为示例,我尝试了以下for pattern属性,但它们都不起作用:

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:


  1. jQuery .attr()函数将动态添加您指定的任何属性,所以你不需要先在表单元素中加上 pattern =,以便添加或更改值。

  2. 重要的是,如果要使用jQuery动态添加正则表达式,则需要使用ESCAPE某些字符。

  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.

regex最初是 \d * \。?\d * 但在DOM中它显示为 d *。?d * 所以当通过jQuery发送正则表达式时,我像这样转义反斜杠: \\d * \\。?\\\\ *

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. 最后,我没有必要使正则表达式工作所需的字段。如果我在字段中包含不正确的文本,并且当它发出错误时,HMTL5验证只会给我一个错误,表单未提交。如果我将字段留空或在字段中放入正确的文本,则不会抛出任何错误。如果我错了,我可以解释一下。

这篇关于JS / JQuery:动态添加“模式”和“标题”属性以形成输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆