简体   繁体   English

清理jQuery或JavaScript中的动态表单字段名称

[英]Sanitizing Dynamic Form Field Names in jQuery or JavaScript

I'm dynamically generating a form when a button is clicked. 单击按钮时,我正在动态生成表单。 I'm using easily readable strings as labels for some fields which becomes an issue for things like Size (ft) since it contains invalid characters suited for form field names. 我在某些字段中使用易于读取的字符串作为标签,这对于诸如Size (ft)类的问题成为问题,因为它包含适用于表单字段名称的无效字符。 The solution for this particular problem is about 90% from complete and my lack of understanding of regular expressions now becomes an obstacle. 这个特殊问题的解决方案大约有90%来自完整的解决方案,而我对正则表达式的理解不足现在成为一个障碍。

I need a quick method for converting a string from something like Size (ft) to something like Size_ft . 我需要一个快速的方法来将字符串从Size (ft)Size_ft Preservation of case and converting spaces to underscores are all I really want to force. 我真正想强制保留大小写并将空格转换为下划线。 Invalid non-space characters can just be dropped, no need for substitution on those. 可以删除无效的非空格字符,而无需替换这些字符。

Edit 编辑

Form Variable Gathering: 表单变量收集:

var jFormVars = {};
jFormVars[fieldName] = fieldValue;

Form Assembly: 表格组装:

jButton.on('click', function() {
  jDiv.find('form').remove(); // Remove existing form...
  var jForm = $('<form action="path/to" method="post" />').appendTo(jDiv);
  $.each(jFormVars, function(key_i, val_i) {
    $('<input name="'+key_i+'" type="hidden" value="'+val_i+'" />').appendTo(jForm);
  });
  jForm.submit(); // Commented for debug .remove();
});

Edit 编辑

Solution as Integrated: 集成解决方案:

var jFormVars = {};
jFormVars[fieldName.replace(/\s+/g, '_').replace(/\W+/g, '')] = fieldValue;

Size (ft) to something like Size_ft Size (ft)Size_ft

You could use something like: 您可以使用类似:

var name = "Size (ft)";
name = name.replace(/\s+/g, '_').replace(/\W+/g, '');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM