I have set a password function for the portfolio posting function. It would be convenient if there was a function that automatically generated and even entered the password.
So let's make it!
Click the "Generate Password" button Let's be able to enter it automatically!
rails:5.2 ruby:2.6.3 bootstrap jquery
First, let's make random alphanumeric characters with the controller.
topics_controller.rb
def new
@topic = Topic.new
@password = SecureRandom.alphanumeric(6)
->Random alphanumeric characters(A-Z, a-z, 0-9)Generate a
(6)Is 6 digits, 16 digits if not specified
end
Next, change the password you created earlier to password_field (this time it is text_field) Allows you to enter.
ruby:new.html.erb
<div class="topic-new-wrapper" >
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_for @topic do |f| %>
<div class="form-group">
<%= f.label :password, 'password(Any)' %>
<%= f.text_field :password, class: 'form-control', id: 'password' %>
<%= button_tag 'Generate password', id: 'auto-fill-link' %>
</div>
<%= f.submit 'Password registration', class: 'btn btn-black btn-block' %>
<% end %>
</div>
</div>
</div>
</div>
<script>
$(function(){
autoFill();
function autoFill() {
$('#auto-fill-link').click(function(){
$('#password').val("<%= @password %>");
});
}
})
</script>
When a link containing the id "auto-fill-link" is clicked, it contains the id "password" @Password is entered in the field.
However, if this is the case, it will be submitted when the button_tag is clicked, so If you want to use it as just a button, add the following code.
type: "button"
ruby:new.html.erb
<div class="topic-new-wrapper" >
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_for @topic do |f| %>
<div class="form-group">
<%= f.label :password, 'password(Any)' %>
<%= f.text_field :password, class: 'form-control', id: 'password' %>
This line-> <%= button_tag 'Generate password', id: 'auto-fill-link', type: "button" %>
</div>
<%= f.submit 'Password registration', class: 'btn btn-black btn-block' %>
<% end %>
</div>
</div>
</div>
</div>
<script>
$(function(){
autoFill();
function autoFill() {
$('#auto-fill-link').click(function(){
$('#password').val("<%= @password %>");
});
}
})
</script>
We have created a function that will generate and enter a password.
It's easy, so please use the above code.