简体   繁体   中英

Set value of text a random number a combination of character and integer?

Here is the code for the random number combining integer and character

<%=(0...4).map { ('a'..'z').to_a[rand(26)] }.join %> <%=rand(1..2000)%>

Gives output like:

tqzu 1664

But when i put this into textbox like;

<input type = "text" value=<%=(0...4).map { ('a'..'z').to_a[rand(26)] }.join %><%=rand(1..2000)%>  />

OUTPUT

ztgg

Question:-

how to get the value of random number into textbox with the combination of char and integer ?

It only processes the first part. If you place your code in a helper you can call the helper method within your view and you shouldn't have any problems.

You have to put your code into " :

<input type = "text" value="<%=(0...4).map { ('a'..'z').to_a[rand(26)] }.join %> <%=rand(1..2000)%>" />

or better:

# in helper
def code
  [(0...4).map { ('a'..'z').to_a[rand(26)] }.join,
   rand(1..2000)].join(' ')
end

# in view
<%= tag :input, :value => code %>

In your form place code like this

<%=@rand_value = (0...4).map { ('a'..'z').to_a[rand(26)] }.join.to_s + rand(1..2000).to_s %>
<%= f.text_field :text, :value => @rand_value %>

or you can use text_field_tag as below:

<%= text_field_tag "text", @rand_value %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM