2014-08-27 59 views
0

我正在使用PHP + MySQL。在一页中我有一个aprox的表格。 30个输入。使用jQuery填充空输入

在显示表单之后,最后我执行了一些样式化表单的jQuery语句。

那么,我的SQL中的一些行有数据空输入,所以我显示空输入。我想用“------”来填写表格,而不用将斜杠写入数据库,因为使SQL变得更大。

我想“replaceWith”,但我不知道这个实现与“空”是否正确。 这不起作用,即使没有。是(:空)

<script> 
    $('#form').find('input[type=text]').is(':empty').replaceWith(function() 
     { 
     return this.val('------'); 
     }); 
</script> 
+3

一件事你不能'回报return'。 – 2014-08-27 14:29:13

+1

我会建议做这个服务器端代替。您可以简单地在输出之前使用简单IF格式化输出,而不触及数据库,如if(is_null(field)){field =“----”;} – briansol 2014-08-27 14:30:16

+0

':empty'附近缺少引号 – SeinopSys 2014-08-27 14:38:58

回答

1

使用这样的事情:

<script> 
    $('#form').find('input[type=text]').each(function(e){ 
     if($(this).val()=="") $(this).val("---"); 
    })  
</script> 
+0

这工作!作为@adeneo写道,我需要使用.trim来修剪掉空格。谢谢 !!!! – 2014-08-27 15:30:27

3

jQuery的:empty发现的元素,没有孩子,没有元素没有值,并作为输入不能生孩子就觉得没有什么。

而jQuery的is()返回一个布尔值,而不是集合。

jQuery的replaceWith替换整个元素,而不仅仅是值。

请检查值。

$('#form input[type=text]').val(function(_, val) { 
    return val.length === 0 ? '------' : val; 
}); 

$('#form input[type=text]').filter(function() { 
    return this.value.length === 0; 
}).val('------'); 

扔在一个$.trim如果需要

剪掉空白
+0

哇,谢谢。我很明显误解了空的功能。不幸的是,两个选项不起作用。我会尝试用$('#form')。find('input [type = text]') – 2014-08-27 15:23:29

+0

这不仅仅是jQuery的':empty',它是CSS选择器应该工作的方式。 – SeinopSys 2014-08-27 15:27:18

1

你有使用HTML placeholder属性考虑?

您可以使用placeholder使破折号显示为浅灰色文本,而不实际更改输入值。他们会自动添加到你的页面上的任何空白字段:

<input type="text" placeholder="----" value="asdf" name="notempty" 
    title="This has a placeholder, but doesn't show it because the input is filled with something" /> 
<input type="text" placeholder="----" value="" name="empty" 
    title="This is empty, so it shows the dashes" /> 

占位符的文本将不会被包括在您的$_POST数据。在这个例子中,$_POST['empty']将是空白的。

placeholder属性被许多现代的浏览器,但不支持IE9:

http://caniuse.com/#feat=input-placeholder

有模仿这种效果以及各种jQuery插件。你可以阅读他们几个在这里:

How do I get placeholder text in firefox and other browsers that don't support the html5 tag option?

+0

这是一个非常好的选择,但我无法使用它,因为在添加斜线后,我使用其他Jquery语句将此输入转换为纯文本,因此如果输入中没有写入文本,则转换会使其消失 – 2014-08-27 15:28:04