如何根据其值更改所需表单输入的CSS样式 [英] How to change the CSS style on required form inputs based on their values

查看:53
本文介绍了如何根据其值更改所需表单输入的CSS样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何编写JavaScript来更改所需的表单元素的样式;并更改其中是否包含值.

I would like to know how to write the javascript to alter the style of form elements which are required; and change them if they have values in them.

我想要做的是在必填文本字段为空时在其周围有彩色边框,并在它们具有值时删除边框样式.

What I want to do is have a colored border around the required text fields when they are blank, and remove the border style when they have values.

我想做的是编写一个JavaScript函数来检查该值是否为空并设置适当的样式:

what I've thought of doing is to write a single javascript function which checks if the value is empty and set the appropriate style:

function requiredElement(id) {
  var Input = document.getElementById(id);
  if(Input.value==null) {
    Input.style.border = '2px solid #FF0000';
  }
}

但是我一直坚持的是,随着用户在这些必填字段中输入/删除字符,并为这些字段调用函数,更改样式.

But what I'm stuck with is changing the style as user enters/removes characters in these required fields, and calling the function for the fields.

我有一个简单的html表单,每个输入都有一个唯一的ID.

I have a simple html form, each input has a unique ID.

推荐答案

使用jQuery

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>

然后添加此代码:

$('.important').change(function() {
  if(($(this).val()) != '') $(this).css( 'border-width', '0' );
  else  $(this).css( 'border-width', '2' );
});

假设您在CSS中添加了边框

Assuming you added a border in the css

.important
{
    border-style:solid;
    border-width:2px;
    border-color:red;
}

这篇关于如何根据其值更改所需表单输入的CSS样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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