在一个输入字段上为只读和必填

时间:2018-07-11 09:59:08

标签: html html5 web mobile

对于我当前正在开发的Web应用程序,在关注文本框时,我需要隐藏标准的IOS键盘。

只需添加“ readonly”标签,然后使用onClick函数打开我的自定义输入即可。

    <form method="post" action="" enctype="multipart/form-data">
      <input type="text" id="test123" onClick="doSomething();" readonly required />
      <button type="submit" value="submit">
        Save
      </button>
    </form>

(JSFiddle)

这有效。部分地。通过启用只读,我可以使键盘保持隐藏状态。但是,另一个问题出现了。使用只读时,不会调用“ required”。您可以使用空白字段提交表单,因为它假定只读字段包含必须包含的内容。

我们怎么可能保持只读和必需?我们不能。我们需要一种解决方法。

编辑:

关于可能的重复项。 THIS帖子中的答案是将JQuery只读添加为preventDefault。问题是,在ios设备上,键盘会一直打开,这最终是我们的目标。键盘不得打开,但仍应为必填字段。从理论上讲,我认为可以使用Javascript验证来实现。但这意味着,我的Submit按钮将调用js函数,而必须调用php函数来提交数据。

2 个答案:

答案 0 :(得分:1)

这是我解决此问题的方法。我试图使JS验证器尽可能简单。

$('#dataInput').submit(function (e) { //Form is submitted, it calls this function automatically
    var empty = 0;
    $('input[type=text]').each(function(){ //Check each input (had to be done like this, because i dont know the amount of input beforehand)
       if (this.value == "") { //The textbox is empty
           empty++;
       } 
    })
    if(empty === 0){ //No empty textboxes

    }else{
       alert(empty + ' empty input(s)'); //There are empty textboxes
   e.preventDefault(); //Prevent the submit from happening
    }

});

You can check out the fiddle here

答案 1 :(得分:0)

第一种方法:您可以分配一个虚拟值,然后在后端检查该值是否已更改,如果未更改,则会显示错误消息。否则,将其保存到数据库中。

            <form method="post" action="" enctype="multipart/form-data">
            <input type="text" value="dummy" id="test123" onClick="doSomething();" 
                    readonly required />
            <button type="submit" value="submit">
                Save
                </button>
              </form>

第二种方法:当触发输入字段的onclick事件时,可以使用以下代码删除readonly属性。

               function doSomething()
                {
               $("#test123"). removeAttr("readonly");
                 }