Add input field by radio option - ruby-on-rails

Im trying to show/add the field 'area_outros_descricao' when the radio button is selected with value 4. What im doing wrong ?
form do |f|
...
...
f.input :tipo_proposta, label: 'Proposta do Projeto', as: :radio, collection: {'Fechada' => 1, 'Pontual'=> 2, 'Emergencial' => 3, 'Outros' => 4}
if f.object.tipo_proposta == 4
f.input :area_outros_descricao, label: 'Descrição'
end
...
...
end
f.actions

You need to use JavaScript:
Here is an example to add Input fields on Radio button selected..
function yesnoCheck() {
if (document.getElementById('yesCheck').checked) {
document.getElementById('ifYes').style.display = 'block';
}
else document.getElementById('ifYes').style.display = 'none';
}
Demo1 :
Another Example
$(document).ready(function () {
$(".text").hide();
$("#r1").click(function () {
$(".text").show();
});
$("#r2").click(function () {
$(".text").hide();
});
});
Demo2:

You have to use jQuery on client side to show or hide the input.

Related

How to use Ajax for nested form on active admin rails

Please help me out with this problem. I am new on rails
I am trying to use the ajax method to get values on the active admin nested form. But only the top of the form gets dynamic values. After changing values on the top one form on the nested form then ajax makes a request then it changes the values(i.e. update the form values).
But after adding a new buy line item then ajax makes a request but doesn't update the values on the form i.e.same values for every new buy line item.
my js code
app/assets/javascripts/buys.js
// for nested buyline items of buys resources
$('.lineItem').change(function () {
$.ajax({
url: '/admin/get_buys_buy_line_item',
type: 'GET',
dataType: "json",
data: {
product_id: $('.lineBuyProduct').val(),
buy_quantity: $(".lineBuyQuantity").val(),
buy_quantity_unit: $(".lineBuyUnit").val(),
buy_price: $(".lineBuyAmount").val(),
},
success: (data) => {
alert(data);
// if (data == null) {
// document.getElementById('lineQuantity').value = ' ';
// document.getElementById('lineAmount').value = ' ';
// }
// else {
// document.getElementsByClassName("linebuyQuantity").value = data['1'];
// document.getElementsByClassName('linebuyAmount').value = data[0];
// console.log("Dynamic select OK!")
// }
}
});
});
});
My active admin forms
f.inputs 'Line Items', class: "lineItem" do
table do
thead do
tr do
th 'S.N', class: 'form-table__col'
th 'Product', class: 'form-table__col'
th 'Quantity', class: 'form-table__col'
th 'Unit', class: 'form-table__col'
th 'Amount', class: 'form-table__col'
th 'Expiry Date', class: 'form-table__col'
th 'Destroy', class: 'form-table__col'
end
end
end
f.has_many :buy_line_items, new_record: 'Add Buy Line Item', heading: false, allow_destroy: true do |x|
x.input :sn, label: false
x.input :product, label: false, as: :select2, collection: Product.drop_down_options,
input_html: { required: true, class: 'lineBuyProduct' }
x.input :buy_quantity, label: false, input_html: { required: true, class: 'lineBuyQuantity' }
x.input :buy_quantity_unit, label: false, collection: Unit.all.pluck(:name),
input_html: { class: 'lineBuyUnit' }
x.input :buy_price, label: false,
input_html: { required: true, class: 'lineBuyAmount' }
x.input :expiry_date, as: :date_picker, input_html: { style: 'width:auto' }, label: false
end
end
Some of my screenshots of how my program behaves and what my expectations are
In this image my first selection of product on buy line iteme then on request we can see json are renderd
But in this image after selecting another product again same json data are rendered that means doesn't update with different respective product values
And there are also some problems on active admin blaze theme, after adding class on form then it changes to legend color and add item button colors to light brown
This picture is about after removing custom class name lineItem.But, after removing this class then ajax doesn't hit for that form
Might be i faced such problem due to nested form's class on active admin.While i used default class of those form from inspect then it even doesn't hit to that form for ajax request.
So, please expert team help me to slove this problem.
If you want to send the data to create a new entity(record), you need to use the http POST method: https://api.jquery.com/jquery.post/
The GET request it just retrieves an already existing entity. Probably that's why you can read some data after an ajax call, but it's not updated.
More about the differences between GET and POST methods:
When should I use GET or POST method? What's the difference between them?
If this fix doesn't work, check the rails logs.
I have never used anything related to Ruby, and I'm not completely sure if I understood your question. I'm assuming you have problems with the AJAX behavior for new items in the list. Considering that, I think your problem could be related to attaching the "change" event to the new items. I think there might be many different other ways to get the behavior you want, but I will just elaborate on your solution using JS.
From the activeAdmin's code you can see they trigger an event called "has_many_add:after" when a new item was successfully added to its parent. Considering that, I would try changing your Javascript code to:
// for nested buyline items of buys resources
$("#buy_line_items").on("has_many_add:after", function(event, fieldset, parent){
fieldset.change(function () {
$.ajax({
url: '/admin/get_buys_buy_line_item',
type: 'GET',
dataType: "json",
data: {
product_id: $(this).find('.lineBuyProduct').val(),
buy_quantity: $(this).find(".lineBuyQuantity").val(),
buy_quantity_unit: $(this).find(".lineBuyUnit").val(),
buy_price: $(this).find(".lineBuyAmount").val()
},
success: (data) => {
alert(data);
// if (data == null) {
// document.getElementById('lineQuantity').value = ' ';
// document.getElementById('lineAmount').value = ' ';
// }
// else {
// document.getElementsByClassName("linebuyQuantity").value = data['1'];
// document.getElementsByClassName('linebuyAmount').value = data[0];
// console.log("Dynamic select OK!")
// }
}
});
});
});
I'm very confident that this will work, mainly because I don't have how to try it (if you give me the generated HTML maybe it'd help me). You can try it and reach back to see if it worked or if any adjustment is required.
You might want to change your commented lines accordingly. Also about the identifier "#buy_line_items" I'm not sure if it exists in the rendered HTML so you might need to adjust that as well.

If Else in HAML to check the value of a "select" box

= form_tag questions_path, :method=>:post do
= label :question, :type, 'Type: '
= select :question, :type, %w(Text Picture Audio Video), :id=> :question_type_combo
**- if :question_type_combo.selected != 'Text'**
= label :question,:url, 'URL: '
= text_field :question,:url, :id=> :question_url_text
= submit_tag 'Add Question',:id=>:add_question_button
Is something of this sort possible in HAML? I wish to render the textfield only for certain options if selected in the SELECT BOX above.
Yes and no. You can write a conditional based on the values of the record that you bind to the form:
= form_for #question do |f|
= f.label :type
= f.select, :type, %w(Text Picture Audio Video), id: 'question_type_combo'
- unless f.object.question_type_combo === 'Text'
= f.label :url
= text_field :url, id: 'question_url_text'
But this would only change the visibility after the user submits the form and not be very useful.
Instead you can just use jQuery to create an event handler for the ´change´ event.
$(document).on('change','#question_type_combo', function(){
var type = $(this).first(':selected').val();
var $other_input = $('#other_input');
if (type == 'Text') {
$other_input.hide();
} else {
$other_input.show();
}
});
// sets the initial state
// if you are using turbolinks
$(document).on('page:load', function(){
$('#question_type_combo').trigger('change');
});
// if you are not using turbolinks
$(function(){
$('#question_type_combo').trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="field">
<label>Type</label>
<select name="question[question_type_combo]" id="question_type_combo">
<option>Text</option>
<option>Something else</option>
</select>
</div>
<div class="field" id="other_input">
<label>URL</label>
<input type="text" name="question[url]">
</div>
</form>
- if :question_type_combo.selected != 'Text' This is not possible in the haml view, If you want to do something based on selected option you have to use js.
Or you may set the selected option using similar code if you have controller objects:
= select_tag("fee_discount", options_for_select(Fee.discounts.keys.map {|k| [k.titleize, k]}, selected: "#{"rewards" if #vendor.present? && #vendor.approved?}"), include_blank: true)
Or
You may keep the label and text_field inside a div with hide class.
And then using javascript you may hide unhide the div.

format_tag select field issue in rails 3 app

I have the following form in haml
= form_tag complete_move_into_partner_saas_admin_account_path, :id => "move_into_partner_form" do
%fieldset
%legend select partner
%label{:for => 'discount_code'} If the partner you are looking for isn't in this list you will need to back out and speak with development.
= select_tag "partner_id", options_from_collection_for_select(#partners, "id", "company_name")
%p
= submit_tag "Move account into partner", :id => 'move_into_partner'
The form works, but always passes back the first partner_id, rather than the one that is selected, so that the parameters from the form look like this...
{
"utf8" => "✓",
"authenticity_token" => "f3oVnjej3o5rfQrTa9/o/ZD8E9SH1l6CGy1imRd4Db8=",
"partner_id" => "19",
"action" => "complete_move_into_partner",
"controller" => "saas_admin/accounts",
"id" => "3997"
}
The partner ID is always 19, regardless of which option is selected. What am I missing???
#partners is assigned in the controller like this...
def move_into_partner
#account = Account.find(params[:id])
#partners = Partner.order(:company_name).all
end
19 is the ID of the first one in the list when sorted in this manner.
ahh, I don't think it's this, I think it's the modal confirmation box. which is this...
#move_into_partner_dialog.hidden
%p Are you sure you want to move #{#account.name} into the account of partner_placeholder? You can't undo this action !
:css
button { text-shadow: none; }
.ui-dialog .ui-widget-header { background: red; }
:javascript
$(function(){
$('#move_into_partner').click(function(e){
e.preventDefault();
var partner = document.getElementById("partner_id");
var partnertext = partner.options[partner.selectedIndex].text;
document.body.innerHTML = document.body.innerHTML.replace(/partner_placeholder/g, partnertext);
$('#move_into_partner_dialog').dialog({
modal: true,
title: 'Warning!',
draggable: false,
height: 200,
width: 500,
buttons: [
{ text: "Cancel", click: function(){ $(this).dialog('close'); } },
{ text: "Move account into partner", click: function(){ $('#move_into_partner_form').submit(); } }
]
});
});
});
when the confirmation box appears, the select tag behind the scenes goes back to the first option in the list. How do I prevent this?
EDIT
It's this bit, but I have no idea why
var partner = document.getElementById("partner_id");
var partnertext = partner.options[partner.selectedIndex].text;
document.body.innerHTML = document.body.innerHTML.replace(/partner_placeholder/g, partnertext);

Hide submit button before text is entered

Trying to simply hide the submit button before text is entered but nothing seems to be happening. (Something in the coffeescript is wrong but i don't know what - very new to js)
My form looks like this:
<%= f.input :body, as: :text, input_html: { :id => "inputBody" } %>
<%= f.submit "Answer", { :id => "button" }%>
Coffeescript looks like this:
$(document).ready ->
$("#button").hide()
$("#button").show() if $("#inputBody").length > 0
I do not know CoffeScript but in JavaScript You can try something like this:
$(function(){
$("#button").hide();
$("#inputBody").keyup(function() {
var val = $(this).val();
if (val.length > 0) {
$('#button').show();
}
else {
$('#button').hide();
}
});
});

Check if subject exist and append next to text box

I have a rails app that has a subject text field where the user input subject code id then beside the text field will the result of other details of the subjects when I blur the text field.
form:
SC_ID: <%= f.text_field "subject1", :id => "subject1"%>
jquery:
$('#subject1').blur(function() {
var field_value = $(this).val();
$.post("<%= validate_subject_path %>",{subject : field_value}, function(data) {
success: function() {
alert("Hahaha!");
},
error: function() {
alert("Subject not found!");
}
});
});
controller:
def validate_subject
sc_id = params[:subject].to_i
#subject = Subject.find_by_sc_id(sc_id)
string = "#{#subject.id}"
return string
render :layout => false
end
routes:
map.validate_subject '/subjects/validate_subject', :controller => "subjects", :action => 'validate_subject'
But when I try to blur no alert box is coming out.
Your $.post call is wrong, it should be something like this:
$.post("<%= validate_subject_path %>",{subject : field_value}, function(data) {
// not returning a hash
alert("Hahaha!");
});
If you really when to react on failures than you need to use $.ajax instead of $.post http://api.jquery.com/jQuery.ajax/

Resources