jquery - 在输入文本后添加新的 div 元素并添加 css

标签 jquery css

我有一个带有输入类型文本的 html 表单和带有 class = required 的单选按钮。我正在尝试验证表格。在提交表单时我需要验证表单,如果它返回 false,我需要添加一个新的 div(文本“请填写必填字段”)并将其显示在字段下方红色。如果用户填写该字段,它应该变成绿色或红色应该消失。 jQuery 在单独的 js 文件中。因此,在单击提交按钮时,我正在执行以下操作

$('#test_form .required').filter(':visible').each(function() {
var input = $(this);
if($(this).is(':empty')){
    $(this).css("border","2px solid #FF0004");
    $(this).after('<div>Please fill in the required field</div>');
    return = false;
}else{
    return true;
}
});

现在出现了几个问题。 1. 必填文本出现在字段下方。我需要红色和字体大小 - 10px。那么如何给新添加的div添加css呢? 2. 考虑有一个由 5 个单选按钮组成的单选组。因此,仅当未选择至少一个并在该单选组下方显示文本时,我才需要 Required 文本。现在所有单选按钮的必需文本都出现了。 3. 此外,如果用户点击提交 4 次,则文本会为每个字段添加 4 次。我认为我们可以使用标志来处理

有人可以指导我吗?

最佳答案

  1. required text is coming below the fields.I need that in red color and font size - 10px. So how can I add css to the newly added div?

添加 css 怎么样?只需向新创建的 div 添加一个类。这可以帮助您更好地定位您的 div 并添加其他 CSS。

修改

$(this).after('<div>Please fill in the required field</div>');

$(this).after('<div class="info">Please fill in the required field</div>');

CSS

<style>
.info{
background:#FFB0B0;
color:#FF0000;
}
</style>

2. Consider there is a radio group of 5 radio button. So I need the Required text only if atleast one is not selected and display the text below that radio group. Now the Required text is coming for all the radio buttons.

3. Also if the user clicks submit 4 times, the text gets added 4 times for each field.

添加一个标志可以解决这些问题

关于jquery - 在输入文本后添加新的 div 元素并添加 css,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19311309/

相关文章:

html - div 的高度不是自动的

javascript - Laravel - Bootstrap 数据表 (yajra) 中的单选按钮

jquery - 动态改变一组 li 标签内的 html

css - Angular 2.0 和 D3.js 不在 svg 上应用 Css

html - 简单的 HTML & css 表格愚蠢问题,简单的解决方案

html - IE 的样式问题

javascript - Wheel Color Picker jquery修改

javascript - 购物车内容总值(value)的 WooCommerce 进度条

jquery - 让jquery程序运行得更好

javascript - 来自 span 的 Jquery 搜索字符串无法正常工作