使用jQuery在联系人表单7复选框中添加类

时间:2018-08-31 10:23:27

标签: jquery contact-form-7

我正在使用联系表7来构建带有复选框的表单。我希望能够为每个复选框分配图片。我看到的唯一方法是在包装输入和标签的范围内使用:before,但这意味着我需要能够使用CSS到达每个复选框。

为此,我结合了一个脚本,该脚本会在复选框输入中自动创建一个具有输入名称的ID,并使用:has jquery选择器将我的类分配给父级而不是输入。

jQuery(document).ready(function($){

    $('form.wpcf7-form input').each(function(){
      var span = $(this).parent('span');
      if(span){
        var idAttr = span.attr('id');
        $(this).attr('id',idAttr);
        span.attr('id','');
      }
      var name = $(this).attr('name');
      var type = $(this).attr('type');
      switch(type){
        case 'radio':
        case 'checkbox':
          name += '-'+$(this).attr('value');
          name = name.replace(/\s+/g, '-').replace(/[&<>"'\/]/g, '').toLowerCase(); //replace spaces with dash, remove question mark, and convert to lowercase
      }
      $(this).attr('id',name);
    });

    $( "span:has(label>input#problèmes-de-fuites)" ).addClass( "fuites" );
    $( "span:has(label>input#chaudières-radiateurs)" ).addClass( "radiateurs" );

});

我的问题是:有没有一种方法可以自动执行此操作,因此我不必手动输入所有类?这样,脚本会在跨度中输入ID而不是输入,知道跨度是父级:

<span class="name that i get manually and want to automate">
    <label>
        <span>Checkbox title</span>
        <input name="name used by script" id="name replicated automatically">
    </label>
</span>

我是jquery的新手,所以我自己也搞不清楚。

还是有一种更好的方法可以完全做到这一点?

0 个答案:

没有答案