2014-08-27 96 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