Javascript输入类型="颜色"表格验证

时间:2015-09-25 10:16:28

标签: javascript html css validation input

使用Javascript初级,并对输入类型颜色有疑问。

我试图让用户在继续下一页表格之前选择黑色。默认颜色为黄色。

有人可以帮我解决这个问题并解释我哪里出错了或遗失了什么吗?

并且已经做过研究,试着弄清楚自己但是卡住了,可能是正常情况下最简单的事情。感谢

这是一个片段:



function validate() {

    var elements = document.getElementById("form1").elements;
        
    for (var i = 0, element; element = elements[i++];) {
            
        if (element.style.backgroundColor =='rgb(255, 153, 153)') {
        
            alert("Please enter data for any fields highlighted in red");
        
            return false;
        
        }

    }
}


function spamCheck() {
        
    //alert("Spam Check Working.......");
        
    var color = document.getElementById("color").value;
        
    if (!color == "#000000") {
            
        alert("Please enter the color black to proceed.");
        color.focus;
        return false;
                
    }
}

<form id="form1">
  <span class="center">Spam Check. What colour is black? (choose a colour) 
    <input name="color" id="color" type="color" value="#FFFF00" />
  </span>
            
  <span class="button">
    <button type="submit" onClick="validate(), spamCheck()">Continue &rarr;  </button>
  </span>
</form>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

现在我们可以检查if (color !== "#000000")功能中的spamCheck更改if语句,现在我们可以检查颜色是否正确。

这是example尝试将颜色更改为黑色,警报将会更改。

答案 1 :(得分:0)

这里有一些需要改进的地方,因为逻辑并没有真正加起来。继承你的代码,修改并注释注释:

&#13;
&#13;
function validate() {
    var elements = document.getElementById("form1").elements;
    for (var i = 0, element; element = elements[i++];) {

        // When using the `not equal` operator, use it _in the operator_.
        // Putting a `!` in front of a variable will change the variable first
        // before comparing. This can cause unexpected issues!
        // Also added a type check as the button does not have a value of
        // '#000000', so the alert would _always_ show. This prevents that.

        if (element.type === 'color' && element.value !== '#000000') {
            alert("Please enter data for any fields highlighted in red");
            return false;
        }
    }
    // to allow your HTML prevention of submission, make sure to always return a boolean value.
    return true;
}


function spamCheck() {
    // As you want to focus on this element later, store the element
    // NOT the value.
    var color = document.getElementById("color");

    // This is the point where the placement of the `!` is changed
    // Because if you invert the value of a string, you might get
    // unexpected results!
    if (color.value !== "#000000") {
            
        alert("Please enter the color black to proceed.");

        // Focus is a _method_ of an <input> node,
        // not a property, so call it with ().
        // Also, because you originally set color to the _value_, 
        // it is only a string and not the <node>
        color.focus();

        return false; 
    }
    // to allow your HTML prevention of submission, make sure to always return a boolean value.
    return true;
}
&#13;
<form id="form1">
  <span class="center">Spam Check. What colour is black? (choose a colour) 
    <input name="color" id="color" type="color" value="#FFFF00" />
  </span>
            
  <span class="button">
    <!-- To prevent submission, your onclick is changed -->
    <button type="submit" onClick="return (validate() && spamCheck())">Continue &rarr;  </button>
  </span>
</form>
&#13;
&#13;
&#13;

请注意,validate()将始终发出提醒,因为button的值#000000不属于color,这也被视为元素。因此,并非所有元素都通过了测试。但是,我通过检查元素类型是否是event listeners的类型来修改它,然后才检查该值并发出警报。

但这是主要问题:你如何正确地做到这一点?好吧,javascript使用onSomething,它可以大大改善您的代码。我已将我的建议添加到下面的代码段中。请记住,使用元素上的var form = document.getElementById('myForm'); // Only run this function when a submit button is clicked and the form is // considered to be submitted. Pass the function an event as well. form.addEventListener('submit', function(event){ // Lets assume the form is valid var isValid = true; // Lets use a standard for loop, it's easier to read for(var i = 0, element; element = form.elements[i]; i++){ // I;ve added two data-properties in your HTML, one that tells us what // value your are looking for and another that provides the hint // you want to show people var match = element.getAttribute('data-match'); var hint = element.getAttribute('data-hint'); // If there is something to match and it does not match the value provided // then set isValid to false and alert the hint (if there is one); if(match && match !== element.value){ isValid = false; if(hint) alert(hint); } } // If one element has set the isValid to false, then we want to prevent // the form from actually submitting. Heres were the event comes into play: // event.preventDefault() will stop the form from actually submitting. if(!isValid) event.preventDefault(); });属性将事件附加到HTML元素会被视为不良做法。这主要是因为它使你的代码紧密耦合在一起,这意味着如果你以后必须修改它,它将混合使用JS,HTML和其他元素,它会变得混乱。

事件监听器为您解决了这个问题,您可以使用 javascript将它们附加到元素,但这确实意味着您的表单可以是subm,而不需要javascript。从技术上讲,这就是你想要的 - 但请记住,垃圾邮件机器人通常会禁用javascript,所以除非你使用 javascript编写表单,否则你所做的一切都没有任何影响。

现在,提供的代码的改进版本没有紧密耦合。我为你的HTML添加了一些属性(并删除了其他只是为了使它更简单,但你可以保持跨度,例如)。这些属性与JS紧密耦合。他们在那里供JS阅读,但不会有任何区别。这也意味着只知道HTML的人可以编辑消息。

现在,checkColor也会进入您的验证功能,对任何事情都进行验证。现在更好的方法是检查使用正则表达式模式,但这超出了这个问题的范围。

&#13;
&#13;
<form id="myForm">
  <input name="color" id="color" data-hint="Enter the color black in HEX to proceed." data-match="#000000" type="color" placeholder="#000000" />
  <input type="submit" value="Continue &rarr;" />
</form>
&#13;
hst = ['host1', 'host2', 'host1', 'host2']
err = ['Tomcat', 'Disk Space', 'MySQL', 'Apache']


def make_dict(hst, err):
    d = {}
    for h, e in zip(hst, err):
        try:
            d[h].append(e)
        except KeyError:
            d[h] = [e]
    return d


expected = {'host1': ['Tomcat', 'MySQL'], 'host2' : ['Disk Space', 'Apache']}
result = make_dict(hst, err)
assert expected == result
&#13;
&#13;
&#13;