I'm developing a rails 5.1 app. I'm using chosen javascript plugin in my app for making the select-boxes more user friendly.
In one of my viewpage, I have 2 chosen select boxes. one for project and other for tasks. Requirement is to load only the associated tasks on change of project select box.
My View
<div class="form-group pad-right-one">
<%= f.collection_select :task_project_id_eq, #projects.order(:number), :id, :project_with_number, { include_blank: 'Project' }, {class: 'chosen-select', onchange: "populateTaskFieldWithOptions()"} %>
</div>
<div class="form-group pad-right-one">
<%= f.collection_select :task_id_eq, #tasks.order(:project_id, :number), :id, :task_with_number, { include_blank: 'Task' }, {class: 'chosen-select'} %>
</div>
Js Code
Ajax call that I'm making is a success and I'm getting all the values.
function populateTaskFieldWithOptions(){
let projectId = $("#q_task_project_id_eq").val();
$.ajax({
type: "POST",
url: "/mail/getTasks",
data: {project: projectId},
success:
function(result){
console.log("---Ajax Success----");
document.getElementById('q_task_id_eq').selectedIndex = -1;
var newOption = $('<option value="1">test</option>');
$('#q_task_id_eq').append(newOption);
$('#q_task_id_eq').trigger("chosen:updated");
// Other options I tried ...
//$('#q_task_id_eq').trigger("liszt:updated");
//$('#q_task_id_eq').val(' ').trigger('liszt:updated');
//$('#q_task_id_eq').val(' ').trigger('chosen:updated');
},
error:
function(jqXHR, textStatus, errorThrown){
console.log("---Ajax Error----")
console.error('AJAX Error: ' + textStatus + errorThrown);
}
})
};
I'm not able to reset or update the chosen dropdown.
Any help is really appreciated. Thanks in advance.
$(".chosen-select").chosen("destroy");
Related
Hey guys im currently working on a devise sign up form, the end goal is a user can select a state from the united states and a select tag below will populate with the correct cities in that state. im using the city-state gem. https://github.com/loureirorg/city-state
ive looked at other examples like this one https://forum.upcase.com/t/dependent-country-city-state/7038 my code is below
routes.rb
resources :states, only: :new
registrations.new.html.erb
<div class="field">
<%= f.select :state, options_for_select(CS.states(:us)), {:prompt => "State"}, {:class => "signup-input-container--input", :id => "state-picker"} %>
</div>
<div class="field">
<%= f.select :city, options_for_select([]),{}, {:class => "signup-input-container--input", :id => "city-picker"} %>
</div>
main.js
document.addEventListener("turbolinks:load", function(){
var state = document.getElementById("state-picker");
state.addEventListener("change", function() {
Rails.ajax({
url: "/states?country=" + "United States" + "&state=" +
state.value,
type: "GET"
})
})
});
registrations-controller.erb
def new
super
#cities = CS.get(:us, params[:state])
end
new.js.erb
var city = document.getElementById("city-picker");
while (city.firstChild) city.removeChild(city.firstChild);
var placeholder = document.createElement("option");
placeholder.text = "Choose a city";
placeholder.value = "";
city.appendChild(placeholder);
<% #cities.each do |c| %>
city.options[city.options.length] = new Option('<%= c %>');
<% end %>
im trying to get this to work the way the example link shows. the only difference is that users will only choose states from the US and citys
From our discussion in the comments the issue appears to be that you are requesting the wrong URL for your cities.
You have a route at /states/new but are making the request to /states. Try updating your main.js to:
document.addEventListener("turbolinks:load", function(){
var state = document.getElementById("state-picker");
state.addEventListener("change", function() {
Rails.ajax({
url: "/states/new?state=" + state.value,
type: "GET"
})
})
});
(I removed the country parameter in the URL because you don't seem to be using it, you say you only need this for the US anyway.)
Let me know how you get on with that.
I have a page on my website with a form that allows users to add tags to an item. I want to incorporate typeahead so that when a user starts typing a tag in the input box, a dropdown list appears with existing tags that match the string. I think I can accomplish this with the basic example but it doesn't seem to be working.
Here is my show page with the script:
<div id="add-tag-form">
<%= form_tag add_tag_path, id: "custom-tag",
class: "form-group",
autocomplete: "off",
remote:true
do %>
<%= text_field_tag :tag, nil, placeholder: 'Add tag', class: "form-control typeahead", id: 'add-tag' %>
<%= submit_tag 'Add' %>
<span id = "tag-block" class="help-block"></span>
<% end %>
</div>
<script>
$(document).ready(function(){
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
// an array that will be populated with substring matches
matches = [];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');
// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push(str);
}
});
cb(matches);
};
};
var tags = Tag.all.pluck(:name);
$('#add-tag-form .typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'tags',
source: substringMatcher(tags)
});
});
</script>
In the console I get Uncaught SyntaxError: unexpected token : which is pointing to the :name in the line var tags = Tag.all.pluck(:name);. My thoughts are the ruby isn't being recognized within the script tags but I could be wrong. What is the correct way to do this?
Also, do I need the $(document).ready line at the start of the script?
I have a remote form that is populated by jQuery with an AJAX request. Then, I am binding this form to an AJAX callback but the callback is not being triggered.
var msgSuccess=function(evt, data, status, xhr){
alert('ok!!!');
console.log(evt);
console.log(data);
console.log(status);
console.log(xhr);
}
var bindMsg = function() { // BIND IT TO THE CALLBACKS
$("#composeMsgPopup")
.live('ajax:beforeSend', loadingCallback)
.live('ajax:success', msgSuccess)
.live('ajax:error', failureCallback)
.live('ajax:complete',completeCallback);
}
$.ajax({ // GETTING THE FORM CODE
url: link,
type: "get",
success: function(response, textStatus, jqXHR) {
ans=response;
$("#popup_content").html(ans);
$("#popup").bPopup();
bindMsg();
},
error: function(jqXHR, textStatus, errorThrown) {
failureCallback(errorThrown, textStatus, jqXHR);
},
complete: function(jqXHR, textStatus) {
completeCallback("", jqXHR, textStatus);
},
beforeSend: loadingCallback
});
The code for the form:
<%= form_for(:conversation, :remote => true,
:url=> {:controller=>:conversations,:action=>:create},
:html=>{:id => 'composeMsgPopup' }) do |f| %>
<div id="founder-name" class="field"><b>Recipient: <%= #user.name %></b></div>
<div class="field">
<%= f.label :subject,"Subject" %>
<%= f.text_field :subject,:class=>"composeMsgField" %>
</div>
<div class="field">
<%= f.label :content,"Message Content" %>
<%= f.text_area :content,:class=>"composeMsgField" %>
</div>
<%= f.hidden_field :to_user, :value => #user.id %>
<%= f.submit "Send", :class=>"submitbt",:id=>'sendMessage' %>
<% end % >
I have tried to bind with bind() or on() but it does not work. The code is executed but when I submit the form the callback is not executed.
ok i found a solution.
the remote form not triggering the callback for unknown reason, so what i did is change the
submit button behaviour:
<%= f.button :submit, "Update",:class=>"submitbt",:id=>"submitnewpass",:onclick=>"return false;" %>
and bind the button to manually submit the form
var action=$('#composeMsgPopup')[0].action; // action url
$("#sendMessage").click(function() { // bind submit button
$.ajax({
type: "POST",
url: action,
data: $("#submitnewpass").serialize(), // serializes the form's elements.
success: function(data)
{
// do my stuff
},
error: failureCallback,
beforeSend: loadingCallback,
complete: completeCallback
});
return false;
});
In my _form.html.erb, I have two DatePicker:-
<div class="field">
<!--%= f.label :leaveFrom %-->
<div><%= f.text_field :leaveFrom, :id => 'datepicker4', :placeholder => "From Date"%></div>
</div>
<div class="field">
<!--%= f.label :leaveTo %-->
<div><%= f.text_field :leaveTo, :id => 'datepicker5', :placeholder => "To Date" %></div>
</div>
My requirement is to calculate the date difference between these two dates but not on the form submission. as soon as i select the "To Date", it displays the no of days. I am not able to implement ajax calls. can any one provide some solution to implement this.
I think best way is show difference using java script instead of calling ajax.var leaveFrom =
function dayDiff(){
var leavefrom = $('.datepicker4').datepicker('getDate');
var leaveto = $('.datepicker5').datepicker('getDate');
var dayDiff = Math.ceil((leavefrom - leaveto) / (1000 * 60 * 60 * 24));
}
Call this on select of date or before submitting form.
Try this using jQuery assuming CalculatorController having date_diff method
$(function() {
$('#datepicker5').live("change", function() {
$.ajax({
url: "/calculator/date_diff",
type: "POST",
data: {date1 : $("#datepicker4").val(), date2 : $("#datepicker5").val()}
success: function(result) {
alert(result);
}
});
});
});
I'm using rails 3.1 and ruby 1.9.2. Using checkbox_tag I want that when I click on checkbox, a variable (says #post) is set true then it's passed to controller. How can I do this?
Here is an example of jquery and view code of a live edit/save from a view using ajax:
In application.js:
jQuery('#tranx_field').live('change', function() {
var attr_value = $(this).val();
var attr_name = $(this).next("input[id=attr_name]").val();
var tranx_id = $(this).parent().parent().parent().children("input[id=tranx_id]").val();
$.ajax({
url: "/tranxes/" + tranx_id,
dataType: "json",
type: "PUT",
processData: false,
contentType: "application/json",
data: "{\"tranx\":{\"" + attr_name + "\":\"" + attr_value + "\"}}"
});
});
And the view code:
<%= hidden_field_tag 'tranx_id', #tranx.id %>
<div class="row">
<div class="span6 id="left_col">
<b>Salesrep:</b>
<%= text_field_tag 'tranx_field', #tranx.salesrep,:class => "itemfieldsm" %>
<%= hidden_field_tag 'attr_name', "salesrep" %>
<br>
In the view you could add the following
hidden_field_tag 'post', false
check_box_tag 'post', true
in the controller when the form is submitted, you could just assign it:
#post = params[:post]
The hidden value is just to set the default value, which will be overwritten if the checkbox is selected