I have the following select tag in rails:
我在rails中有如下选择标记:
<%= form_tag({:controller => :reports, :action => :monthly_assignments_by_organization_report}, :method => :post, :class=> 'form-horizontal', validate: true) do %>
<div class="col-md-12">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="" class="col-sm-4 control-label">Product Type</label>
<div class="col-sm-5">
<%= select_tag 'product_id',
options_from_collection_for_select(Product.all, :id, :name), :include_blank => "Please select...",
class: 'form-control single-select', validate: { presence: true, uniqueness: false }
%>
</div>
<label for="" class="col-sm-4 control-label">Reporting Month</label>
<div class="col-sm-5">
<%= text_field_tag "reporting_month", nil,
class: "form-control reporting-month",
id: "reporting-month",
placeholder: "Select Month"
%>
</div>
<div class="row">
<div class="col-md-4 pull-right align-right">
<%= submit_tag "Generate", class: 'btn btn-primary' %>
</div>
</div>
</div>
</div>
</div>
</div>
<% end %>
I want to perform a fornt-end form validation whereby an error message shows if no option was selected in the input field, meaning a product must be selected.
我想要执行一个fornt-end表单验证,如果在输入字段中没有选择任何选项,就会显示一个错误消息,这意味着必须选择一个产品。
My code has no model so I can't do a model validation. It has to be javascript or in the view itself.
我的代码没有模型,所以不能进行模型验证。它必须是javascript或视图本身。
Any help offered is greatly appreciated.
如有任何帮助,不胜感激。
0
So, assuming your markup would look like:
假设你的标记是:
<select id="product_id" name="product_id">
<option value="Please select...">Please select...</option>
<option value="prod1">Product 1</option>
<option value="prod2">Product 1</option>
<option value="prod3">Product 1</option>
<option value="prod4">Product 1</option>
</select>
<input id="commit" name="commit" type="submit" value="Generate" />
You could do one of the following.
你可以这样做。
Javascript:
Javascript:
var selectElem = document.querySelector("#product_id");
function validateSelect () {
if (selectElem.selectedIndex === 0) {
alert ("Please select a product.");
}
}
selectElem.addEventListener("change", validateSelect);
document.querySelector("#commit").addEventListener("click", validateSelect);
jQuery
jQuery
var $selectElem = $("#product_id");
function validateSelect() {
if ($selectElem.prop("selectedIndex") === 0) {
alert ("Please select a product.");
}
}
$selectElem.on("change", validateSelect);
$("#commit").on("click", validateSelect);
Demo@Fiddle
Demo@Fiddle
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2015/04/20/fd413bca0a3daa370305eb8641b4d64f.html。