简体   繁体   中英

Saving a value in a hidden_field_tag with Javascript

I have a form in rails app with a field for choosing a city and saving it's id.

= select_tag 'building[city_id]', 
options_for_select(cities.map{|c| [c.name, c.id]}),
onchange: "myFunction();", include_blank: "Choose city"

I want to save a city name in a hidden_field_tag as soon as the user chooses something from a select tag. How do I implement this with Javascript?

I'm very new to Javascript, please don't judge hard.

I suggest doing as little JS as possible. So:

Start by adding the hidden field (with a null value) in your Rails view.

Now you'll need to add Javascript to your pages (you may already have a file at app/assets/javascripts/application.js which is included with all your pages; including JS with your Rails templates is its own question). You'll need two functions, and jQuery will make life a lot easier:

  1. A function which checks the value of the select tag, and updates the value of the hidden tag with the value from the select tag.
  2. A function which runs at page load time which attaches an event listener to the select tag; this will listen for the "change" event on the "select" tag and call our first function when it sees it.

These will look something like this (NB this code will almost certainly not work for you without changes):

function setHiddenValue() {
  // Get the value from the select tag
  var selectValue = $('select#building_city_id').val();
  // Set the hidden tag's value to the select tag value we got in the last line
  $('input[type=hidden]#city_name').val(selectValue);
}

I'm guessing at the selectors for getting the elements, but Rails is putting IDs on them which you can use.

$(document).ready(function () {
  $('select#building_city_id').on('change', setHiddenValue());
}

Obviously this is rough and will not work immediately on being pasted in. You'll want to be sure the selectors match what Rails is putting in your HTML, you'll want to be sure the scripts are getting included in your page and the event listener is being set, you'll need to check that jQuery is present, and you'll want to be sure the setHiddenValue function gets the correct value to put in the hidden form tag. But this is how I'd start out on what you're trying to do; the rest is details which are particular to your page.

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