2017-06-29 71 views
-1

我有一個rails應用程序來渲染一個表單並接受三個輸入。我不希望用戶能夠輸入字符之間的空格。我是鐵桿新手,不確定從哪裏出發。這裏是我的形式:如何防止用戶輸入空格到欄文本字段

<%= form_for :article, url: articles_path do |f| %> 
    <p> 
     <%= f.label :IP , "IP Address" , class: "input-lg"%><br> 
     <%= f.text_field :IP , class: "form-control"%> 
    </p> 

    <p> 
     <%= f.label :Email , class: "input-lg"%><br> 
     <%= f.text_field :Email , class: "form-control"%> 
    </p> 
    <p> 
     <%= f.label :Device , class: "input-lg"%><br> 
     <p> 
      <%= f.select :Device , [['Server'],['Network']] %> 
     </p> 
    </p> 
    <p> 
     <%= f.submit "Submit", class: "btn btn-default"%> 
    </p> 
<% end %> 

我敢肯定有一種方法使用JavaScript或jQuery來做到這一點,但我不是很熟悉如何在Rails中使用JQuery或我怎麼會做這個用JavaScript 。

回答

1

既然你想在輸入時做到這一點,你將需要使用JavaScript或JQuery。我不會了解如何啓用和調試該部分,只需檢查一些現有的指南就可以了。

對於檢查的實際方法,您需要: - 知道用戶何時在您想要限制的某個輸入字段中輸入內容; - 防止或替換受限輸入。

完成它的最簡單方法是通過傳遞輸入選擇器將「keyup」事件綁定到要定位的輸入字段。在這種情況下,IP和電子郵件。

 $("input[name='IP'], input[name='Email'").keyup(function(e) { 
      var value = $(this).val(); 
    //read the value - jquery will pass the element that is triggering the event as -this- so you can get it by using $(this) 
      value = value.replace(/\s+/g, ''); 
//replace all whitespaces by nothing, effectively removing them 
      $(this).val(value); 
//assign the stripped of whitespace value to the val attribute of to the input field 
     }); 

這可以變得更復雜,只接受特定的模式,只接受數字等,但可能性幾乎是無止境的。

相關問題