2013-08-29 53 views
9

你能告訴我如何在同一時間替換下劃線的空間(當我在輸入字段中輸入文本時)? 如果我有我喜歡的字符串。如何將空格替換爲下劃線(當我在輸入字段中輸入文本時)?

replace(/ /g,"_"); 

但是我正在尋找,當用戶輸入的輸入欄文本,然後它會自動替換空間下劃線。我使用keyup事件只觸發第一次。

$("#test").keyup(function() { 
    var textValue = $(this).val(); 
    if(textValue==' '){ 
     alert("hh"); 
    } 
}); 
+0

首先更好地利用KEYDOWN的。 –

+0

我在類似的情況下把它放在HTML爲「onKeyDown ='foo();'」 –

回答

12

DEMO

$("#test").keyup(function() { 
    var textValue = $(this).val(); 
    textValue =textValue.replace(/ /g,"_"); 
    $(this).val(textValue); 
}); 

更新

DEMO

$("#test").keyup(function() { 
    this.value = this.value.replace(/ /g, "_"); 
}); 
+1

這是比測試哪個按鍵更好的方法。開銷是最小的 –

+0

可以任何身體解決我的這個問題也.http://stackoverflow.com/questions/18502449/why-data-position-fixed-data-tap-toggle-false-not-work/18502566?noredirect = 1#comment27204600_18502566 – Rohit

+0

@tushar請檢查這個問題也解決此問題http://stackoverflow.com/questions/18502449/why-data-position-fixed-data-tap-toggle-false-not-work/18502566?noredirect=1 #comment27204600_18502566 – Rohit

0

您可以檢測通過添加參數回調哪個鍵被按下(比方說e),然後測試它的which屬性(從documentation

$("#test").keyup(function(e) { 
    if(e.which === 32 /*space*/){ 
     alert("hh"); 
    } 
}); 
+0

請幫忙解決這個問題http://stackoverflow.com/questions/18502449/why-data-position-fixed-data- tap-toggle-false-not-work/18502566?noredirect = 1#comment27204600_18502566 – Rohit

0

您可以用.split( ' ')。加入替換事件的整個價值(' _'); 它比替換更快。

所以,

$("#test").keyup(function() { 
    $(this).val($(this).val().split(' ').join('_')); 
}); 
1

試試這個demo

代碼

$("#test").keyup(function(e) { 
    (/ /i).test(this.value)?this.value = this.value.replace(/ /ig,'_'):null; 
}); 
0
$("#test").keypress(function(e) { 
    var textValue = $(this).val(); 
    if(e.keyCode === 32){ 
     $("#test").val(textValue + "_"); 
     return false; 
    } 
}); 
+0

請幫助在這個問題http://stackoverflow.com/questions/18502449/why-data-position-fixed-data-tap-toggle-false-not-work/18502566?noredirect=1#comment27204600_18502566 – Rohit

3

只要試試這個Demo

$("#test").keyup(function() { 
    if ($(this).val().match(/[ ]/g, "") != null) { 
     $(this).val($(this).val().replace(/[ ]/g, "_")); 
    } 
}); 
+1

恕我直言,這是更好比接受的答案。 –

0

小提琴:http://jsfiddle.net/FTmg9/

$(function(){ 
    $('#test').keydown(function(){ 
     $(this).val($(this).val().replace(/\s/g, "_")); 
    }); 
}); 
相關問題