lilixiaocc lilixiaocc - 4 months ago 13
jQuery Question

Use HTML element attribute as rails form input

I am writing a html.erb page.

Have some dynamic attributes of my span

HTML:

<span>something<span>


jQuery:

$('span').attr('data-x', function(){})


Ruby:

<%= form_for @blah do |f| %>
<%= f.hidden_field :x_value, value: ?? %>
<% end %>


So basically the span attribute 'data-x' will change from time to time based on the function, and I have a button set up, if I click the button, I want the value of the 'data-x' attribute be submitted by form helper to my database column "x_value".

How can I do that? Thank y'all!

After getting the idea from Inf, I got this part done.
Get the value of the attribute in my js file:

var valueX = $('span').attr('data-x')


Add an ID for the hidden field in my erb file:

<%= f.hidden_field :x_value, :id=>"columnX" %>


Then assign the id with valueX in my js file:

$("#columnX").val(valueX)

Inf Inf
Answer

Option 1. You can update hidden field on form submit, for example:

$('form').submit(function() {
  $('input[type="hidden"]').val($('span').attr('data-x'));
  return true;
});

Option 2. Update hidden field together with span:

var value = function(){};
$('span').attr('data-x', value);
$('input[type="hidden"]').val(value);