user3735111
user3735111

Reputation: 155

Ruby on Rails: passing conditional hidden values with form submit

In short: I have form that has 2 text fields for values :title and :title_de. I need to automatically pass value :lang on submit as either "eng" or "de" depending on if field for :title was left empty or not. How to do it?

EDIT: controller code for create:

def create
  @article = Article.new(article_params)

  if @article.save
    redirect_to @article
  else
    render 'new'
  end
end

Upvotes: 0

Views: 1221

Answers (3)

Gerry
Gerry

Reputation: 10507

UPDATE

Solution to assign lang in controller:

def create
  @article = Article.new(article_params)

  @article.lang = params[:title].blank? ? "de" : "eng"

  if @article.save
    redirect_to @article
  else
    render 'new'
  end
end

Or, if you prefer, you could use javascript/jquery to get the value of :title and then assign the correct value to :lang before submitting your form.

Snippet:

$('#my-button').on('click', function() {
  event.preventDefault();
  var title = $('#title').val();

  if(title == "") {
    $('#lang').val("de");
  } else {
    $('#lang').val("eng");
  }
  
  // change to $('#my-form').submit();
  alert($('#lang').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form id="my-form">
  title: <input type="text"name="title" id="title"/><br>
  title_de: <input type="text" name="title_de" id="title_de"/><br>
  <input type="hidden" id="lang" name="lang" />
  <input type="submit" id="my-button" />
</form>

Upvotes: 1

ashvin
ashvin

Reputation: 2040

Using javascript you can do like

In your view add hidden_file_tag
<%= hidden_filed_tag :langauge, id: "langauge" %>

and in javascript
$('#title').on("change",function(){
  if($(this).val() == ""){
    $("#langauge").val('eng')
  }else{
    $("#langauge").val('de')
  }
});

Upvotes: 0

Alexander Luna
Alexander Luna

Reputation: 5449

When a form field is left empty it returns nil. You can check for nil and set the language in your controller:

if params[:title] == "nil"
# set the language
else 
# title is not nil, do something else
end

You could do it in the view as well using javascript but if the user has javascript disabled you have a problem.

Upvotes: 0

Related Questions