Search code examples
jqueryruby-on-railsrubycoffeescriptjcrop

Dynamic id name based on model in jquery


I'm following railscasts for jcrop but was wondering how do I have a dynamic model name in jquery if I have something like this:

update: (coords) =>
  $('#user_crop_x').val(coords.x)
  $('#user_crop_y').val(coords.y)
  $('#user_crop_w').val(coords.w)
  $('#user_crop_h').val(coords.h)
  @updatePreview(coords)

#user is based on user's model, but it was hard coded, but if I have other models with cropping, how do you make the id dynamic based on the model?

Thanks


Solution

  • andrewliu. I don't what about dynamic model mean. I talk about how to use another model name to use jcrop.

    update: (coords) =>
      $('#user_crop_x').val(coords.x)
      $('#user_crop_y').val(coords.y)
      $('#user_crop_w').val(coords.w)
      $('#user_crop_h').val(coords.h)
      @updatePreview(coords)
    

    The #user_crop_x is come from this form:

    = form_for MODEL, url: CROP_URL, method: :patch, html:{id: "jcrop_form"} do |f|
      - %w[x y w h].each do |attribute|
        = f.hidden_field "crop_#{attribute}"
      .form-actions
        = f.submit t(".crop"), class: 'btn btn-primary'
    

    It will default generate many id in the hidden_field in rails's form_for. Just like #user_crop_x and #user_crop_y and so on.

    The default id is a certain rule what is ##{model_name}_{attribute_name}, so if you have dynamic model and the best way is set the class name in the hidden_field. Example:

    = f.hidden_field "crop_#{attribute}", class: "crop_class_#{attribute}"
    

    And set the jQuery code like:

    update: (coords) =>
      $('.crop_class_x').val(coords.x)
      $('.crop_class_y').val(coords.y)
      $('.crop_class_w').val(coords.w)
      $('.crop_class_h').val(coords.h)
      @updatePreview(coords)