querySelector输入中的所有检测值 [英] querySelectorAll detecting value in input

查看:196
本文介绍了querySelector输入中的所有检测值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据用户是否输入值来区分多个输入.

<input type="text" class="foo"> <br/>
<input type="text" class="foo" value = "D"> <br/>
//and so on.. 

<button onclick="calculate()">Hightlight</button>

我编写的代码仅适用于属性值,而不是在启动函数之前检测手动"类型的值:

function calculate() {

  var allinputs = document.querySelectorAll('input[value][type="text"]:not([value=""])');
  var myLength = allinputs.length;

  for (var i = 0; i < myLength; ++i) {
    allinputs[i].style.backgroundColor = "lime";

  }
}

我只想检测用户通过突出显示按钮提交内容时输入的内容. 有没有办法用纯JavaScript做到这一点?

这是我的小提琴: https://jsfiddle.net/Lau1989/Lytwyn8s/

感谢您的帮助

解决方案

无法使用CSS选择器选择空输入(请参见

I have multiple inputs I want to discriminate according to whether the user enters a value in it or not.

<input type="text" class="foo"> <br/>
<input type="text" class="foo" value = "D"> <br/>
//and so on.. 

<button onclick="calculate()">Hightlight</button>

The code I wrote only works with attribute values, instead of detecting "manually" typed values before launching the function :

function calculate() {

  var allinputs = document.querySelectorAll('input[value][type="text"]:not([value=""])');
  var myLength = allinputs.length;

  for (var i = 0; i < myLength; ++i) {
    allinputs[i].style.backgroundColor = "lime";

  }
}

I only want to detect the inputs in which the user typed something when he submits it through the highlight button. Is there a way to do it in pure javascript ?

Here is my fiddle : https://jsfiddle.net/Lau1989/Lytwyn8s/

Thanks for your help

解决方案

It's not possible to select empty inputs using CSS selectors (see Matching an empty input box using CSS), but you can achieve what you want by testing the length of the value before applying the style:

function calculate() {
  var allinputs = document.querySelectorAll('input[type="text"]');
  var myLength = allinputs.length;
  var input;

  for (var i = 0; i < myLength; ++i) {
    input = allinputs[i];
    if (input.value) {
        input.style.backgroundColor = "lime";
    }
  }
}

这篇关于querySelector输入中的所有检测值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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