最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - html5 input type required without a form. Does it work? - Stack Overflow

programmeradmin6浏览0评论

I want to use: HTML 5 Required.

such as

<input type='text' required>

it only seems to work if the input type is in a form. Can I not use it on its own and then by javascript call some sort of validate first method ?

More ments following feedback:

I have

    <input id='name' type='text' required>
    <input id='surname' type='text' required>
    <input id='send' type='button' onclick ='send()'>

    function send() {
       if (document.getElementById('name').value == '') { alert('missing name'); return }
       if (document.getElementById('surname').value == '') { alert('missing surname'); return }

       // logic now...

    }

The bit where it checks the input params and sends alert that's the bit I would like to change by using HTML 5

I want to use: HTML 5 Required.

such as

<input type='text' required>

it only seems to work if the input type is in a form. Can I not use it on its own and then by javascript call some sort of validate first method ?

More ments following feedback:

I have

    <input id='name' type='text' required>
    <input id='surname' type='text' required>
    <input id='send' type='button' onclick ='send()'>

    function send() {
       if (document.getElementById('name').value == '') { alert('missing name'); return }
       if (document.getElementById('surname').value == '') { alert('missing surname'); return }

       // logic now...

    }

The bit where it checks the input params and sends alert that's the bit I would like to change by using HTML 5

Share Improve this question edited Oct 12, 2011 at 14:25 Zo72 asked Oct 12, 2011 at 13:49 Zo72Zo72 15.3k18 gold badges74 silver badges105 bronze badges 3
  • Can you post a little more code to explain better what you are trying to acheive? – beefyhalo Commented Oct 12, 2011 at 13:51
  • 1 When is the validation supposed to happen if there is no form to send? – JJJ Commented Oct 12, 2011 at 13:53
  • are you using AJAX to send the input's value off? – Moin Zaman Commented Oct 12, 2011 at 13:56
Add a ment  | 

3 Answers 3

Reset to default 19

Sure, use

document.getElementById('your_input_id').validity.valid

to check validity of field dynamically.

First, the "required" attribute will fire on "submit" event, so, I guess, no form — nothing will be submitted. Second, why there is the problem with form?

With 'required', this should work only if form is submitted.

发布评论

评论列表(0)

  1. 暂无评论