Chrome html forma validación incorrecta en el elemento seleccionado

It seems that Chrome does not validate <select> in the way I expect. Firefox returns correctly false if I select the first option while chrome does it selecting the second option. This happens both on Windows and Linux.

Mi HTML

<form>
<select name="select-choice" id="select-choice" required>
  <option value="">This is just a placeholder, it should invalidate the form</option>
  <option value="choice2">Choice 2</option>
  <option value="choice3">Choice 3</option>
</select>
</form>

Mi JS

$('form').change(function(){
   $('.result').html('form is ' + this.checkValidity());
});

CodePen

Here is a code pen

preguntado el 12 de junio de 14 a las 10:06

1 Respuestas

That would seem like a jQuery bug. If so, here is a functional vanilla/native Javascript:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Demo</title>
</head>
<body>
    <form id="theForm">
        <select name="selectChoice" id="selectChoice" required>
            <option value="">Invalidating placeholder</option>
            <option value="choice2">Choice 2</option>
            <option value="choice3">Choice 3</option>
        </select>
    </form>
    <script>
        var selectChoice = theForm.selectChoice;
        selectChoice.onchange = function() {
            if (selectChoice.value == '') alert('Invalid selection.');
            else alert('Valid selection.');
        }
    </script>
</body>
</html>

.

The live example is a codepen as well: http://codepen.io/anon/pen/hqutj?editors=100.

Alternatively in jQuery, you might wanna try to not use the function checkValidity(), which would seem to return the options.selectedIndex, but to check for an empty value of the select.

EDITAR: on a side note: required seems to be an attribute that is not supported by any browser, at least not in native Javascript. See http://www.w3schools.com/tags/att_select_required.asp.

Respondido el 12 de junio de 14 a las 11:06

This works. What still bugs me is that checkValidity() is not jQuery, is native JavaScript as well and required should work. I ll accept this answer if nothing better comes out. - naturaleza muerta

@MirkoGuarnier - cute, that checkValidity(). Never heard of it before, but it will make coding a lot easier. However, at this point in time, it seems to be structurally buggy due to wrong or no browser support. See sanalksankar.blogspot.nl/2010/12/…, the forelast paragraph. Regarding required: with such poor browser support (no IE8/9 and no iOS Safari), I'm gonna forget it about for now. Too busy. - Frank Conijn - Apoyo a Ucrania

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.