我是rails和html的新手....
我想在视图中的字段fullname中连接名字和姓氏。我希望在您修改姓氏或名字时,全名会自动刷新'名字' +" " +'姓氏'
我尝试了这个,但是我错了。因为,似乎全名字段保持为空,我试图在函数中发出警报以查看串联是否正常工作。但似乎不这样做....
<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<script type="text/javascript">
function test ()
{
$('fullname').value <= $('firstname').value + " " + $('lastname').value;
}
</script>
<div class="form-group">
<%= f.label :prenom %><br />
<%= f.text_field :firstname, autofocus: true, placeholder: "Prenom", class: "form-control",:onchange => "test()" %>
</div>
<div class="form-group">
<%= f.label :lastname %><br />
<%= f.text_field :nom, autofocus: true, placeholder: "Nom", class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :fullname %><br />
<%= f.text_field :fullname, autofocus: true, placeholder: "Full Name", class: "form-control", :readonly => true %> <!-- ajout de readonly -->
</div>
感谢您的帮助
答案 0 :(得分:2)
您应该检查(或发布问题)您生成的HTML,以便我们为您提供更多帮助。
这是不正确的:
$('fullname').value <= $('firstname').value + " " + $('lastname').value;
这是工作示例。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<script type="text/javascript">
$( document ).ready(function() {
$('input.firstname, input.lastname').on('input', function(e) {
var changedFullName = $('input.firstname').val() + " " + $('input.lastname').val()
$('input.fullname').val(changedFullName);
});
});
</script>
<label for="firstname">FirstName</label><br>
<input type="text" name="firstname" class="firstname" /><br>
<label for="lastname">LastName</label><br>
<input type="text" name="lastname" class="lastname" /><br>
<hr>
<span>FullName</span><br>
<input type="text" name="fullname" class="fullname" readonly />
</form>