2

I am pretty new in JQuery and I am finding some difficulties in the validation of an HTML5 input tag.

So, in my page I have the following input tag:

<input id="variazioneAnticipo" class="rightAlligned form-control" style="width:50%" type="number" step="0.01" />

and this button:

<button id="variaAnticipoButton" type="button" class="btn btn-primary" onclick="validaProgetti()">Varia anticipo</button>

When this button is clicked is performed the following JQuery script that have to perform the validation of the previousinput field vi JavaScript (the inserted value have to be a decimal number and not for example a String).

$("#variaAnticipoButton").click(function() {
    alert("Variazione Anticipo");

    alert($('#variazioneAnticipo').checkValidity());

});

And here I have my problem because the previous JQuery script can't work, in the FireBug console I obtain this error message:

TypeError: $(...).checkValidity is not a function
alert($('#variazioneAnticipo').checkValidity());

but doing by JavaScript seems work, in this way:

document.getElementById('variazioneAnticipo').checkValidity(); 

I think that it could depend by the fact that checkValidity() is not a function of the object returned by the $('#variazioneAnticipo') JQuery selector but only of the pure JavaScript document.getElementById('variazioneAnticipo') selector.

Is it or am I missing something? I thought that both return the HTML element having a specific ID and that the checkValidity() function is applicable to this HTML object regardless of whether it is retrieved using JQuery or pure JavaScript. But seems which it is not so. What am I missing?

How can perform the HTML5 validation using JQuery instead the pure JavaScript in my code?

AndreaNobili
  • 40,955
  • 107
  • 324
  • 596
  • 1
    Yes you are right... `$('#variazioneAnticipo')` returns a jQuery object which does not have the method `checkValidity`.... which is a member of `HTMLFormElement` object – Arun P Johny Dec 14 '15 at 12:07
  • 3
    Hi Andrea, both returns very different objects. try this http://stackoverflow.com/questions/7386817/html5-form-checkvalidity-method-not-found – divakar Dec 14 '15 at 12:08
  • Try `alert(this.checkValidity());` – Rayon Dec 14 '15 at 12:09
  • 1
    You can do `$('#variazioneAnticipo')[0].checkValidity()` - where `$('#variazioneAnticipo')[0]` will return the dom element reference – Arun P Johny Dec 14 '15 at 12:09

2 Answers2

4

At the moment, jQuery does not have html5 validation api directly in their wrapper. But you can access the native object with this :

$('#variazioneAnticipo')[0]

So you can write :

$('#variazioneAnticipo')[0].checkValidity();
Magus
  • 14,796
  • 3
  • 36
  • 51
2
$('#variazioneAnticipo')[0].checkValidity()

When you select $('#variazioneAnticipo') you get a collection of nodes, to access actual DOM properties you must select the first one.

divakar
  • 1,379
  • 6
  • 15
  • 31