2010-10-29 53 views

回答

0

Got it! 我把這段代碼中的application.js:

// Place your application-specific JavaScript functions and classes here 
// This file is automatically included by javascript_include_tag :defaults 
$(function() { 
    $("#search_submit").click(function() { 
     if ($("#search_value").val().length < 3) { 
      alert("You must supply 3 or more characters in your search."); 
      return false; 
     } 
    }) 
}) 

我的形式是:

<%= form_for(@search, { :remote => true, :html => { :id => 'left', :class => "custom-border" } }) do |f| %> 
    <h2><%= f.label :value, "Search By Part or Interchange #" %></h2> 
    <p><%= f.text_field :value %></p> 
    <p class="button"><%= f.submit "Search" %></p> 
    <% end %> 

瞧!

2

是的,onclick確實會被認爲是突兀的。 您可能想要在JavaScript中使用第三方驗證庫。 它可以工作是這樣的:

<form ... class="validated"> 
    <input type="text" name="name" data-validation="presence=true,format=/[a-zA-Z0-9\s]+/" /> 
    <input type="submit" value="Send" /> 
</form> 

<script language="javascript"> 
    $('form.validated').live('submit', function() { 
    var data = $(this).serializeArray(); 
    var errors = []; 
    $(this).find('input').each(function() { 
     var input = $(this); 
     $.each($(this).attr('data-validation').split(','), function(validation) { 
     var type, param = validation.split("="); 
     if(type == "presence") { 
      if(input.val() == "") errors += input.attr('name') + " is empty"; 
     } else if(type == "format") { 
      ... 
     } 
    }); 
    return (errors.length == 0); 
    }); 
</script> 

(只是一些粗略的代碼了我的頭警告的大量存在。)

但不是寫了這麼多,也許你只是想用:http://github.com/jzaefferer/jquery-validation

+0

請您將我的答案標記爲已接受? :) – balu 2010-10-31 14:31:16

相關問題