Filtering a dropdown based on the value in another dropdown in Rails - ruby-on-rails

I have a Country model. In view I have a country dropdown. If country1 is selected, all states of that country must be listed in states dropdown box. If country2 is selected, only 'others' must be displayed in the drop down box. I have jquery to do this. but how do i access a constant defined in ruby in jquery? How do I do that?
$('#country_id').change(function() {
debugger
var country = $('#country_id').val();
if (country != 'India') {
// $('#country_state').val("others");
//$('#country_state').prop("disabled", true);
$('#country_state').empty().append('<option>Other</option>');
$('#phone').focus();
}
else{
$('#country_state').empty().append('<option>indiastates*</option>');
}
})
*indiastates is a constant in ruby. How do i display that as options for dropdown?

you can try grouped_collection_select
here is the railscast http://railscasts.com/episodes/88-dynamic-select-menus-revised

For the second dropdown list, I first created an array with the values i wanted to display in the dropdown.
var states_array = new Array("xxx","yyy");
to append this into dropdown
var states_option;
for(var i=0;i<states_array.length;i++)
states_option += "<option>" + states_array[i] + "</option>";
$school_state.empty().append( states_option );

Related

Is it possible to add an option to the top of a select2 when data comes from ajax?

I need to insert at the beginning of the list a new option in the select2 control.
I tried with
var data = {
id: -1,
text: 'SISTEMA'
};
var newOption = new Option(data.text, data.id, false, false);
$('#UsuarioId').append(newOption).trigger('change');
But that does not work when data comes from Ajax. In that case, the combobox appears with that option selected and when list is expanded, that option is not there.
Regards
Jaime
Create a variable and initially define that variable as the option you want to include - eg:
var trHTML;
trHTML = '<option value=""></option>'
Then loop through your result set adding each item back to that variable
$.each(x, function (i, item) {
trHTML += '<option value=' + value_name +'>'+ display_name +'</option>';
});
Then append the entire list to the select, and initiate Select2
$('#dropdown_name').append(trHTML);
$('#dropdown_name').select2({
placeholder: "foobar",
allowClear: true
});
This documentation from select2 already explains
https://select2.org/data-sources/ajax

Free Text Entry in Angular Material mdAutoComplete

I want my angular material autocomplete to be a list of suggestions but not requirements. However I'm not sure how to implement as their is no clear example from the Angular Material docs.
In the example below my model is $ctrl.item.category
Clearly the example below is wrong, as my model is linked to md-selected-item, but this only works if I select an item. I want the user to be able to free enter the text if the item is not in the list. Basically how autocomplete already works in most browsers.
I see plenty of questions on how to disable this, but they are not trying to disable so much as clean up the left over text when an item is not selected. In these cases when an item is not selected then the model value is null, but text is left in the input.
I want the text left int he input to be the model value if the person does not select (or a match is not made).
md-autocomplete(
md-floating-label="Category Name"
flex="50"
md-input-name="category"
md-selected-item="$ctrl.item.category"
md-search-text="catSearch"
md-items="category in $ctrl.categories"
md-item-text="category"
md-min-length="0"
md-select-on-match=""
md-match-case-insensitive=""
required=""
)
md-item-template
span(md-highlight-text="catSearch" md-highlight-flags="^i") {{category}}
My options ($ctrl.categories) is an array of strings ['Food','Liqour'] and I wan the user to be able to use one of those or free enter Tables as their choice.
In this case you should link md-search-text to your model.
If you want to implement fuzzy search you have to write the filter method yourself. Look at this example:
template:
<md-autocomplete
md-items="item in $ctrl.itemsFilter()"
md-item-text="item.label"
md-search-text="$ctrl.query"
md-selected-item="$ctrl.selected"
>
<md-item-template>
<span md-highlight-text="$ctrl.query">{{item.label}}</span>
</md-item-template>
<md-not-found>
No item matching "{{$ctrl.query}}" were found.
</md-not-found>
<div ng-messages="$ctrl.myValidator($ctrl.query)">
<div ng-message="short">Min 2 characters</div>
<div ng-message="required">Required value</div>
</div>
</md-autocomplete>
controller:
var items = [ ... ];
ctrl.itemsFilter = function itemsFilter() {
return ctrl.query ? filterMyItems(ctrl.query) : items;
};
ctrl.myValidator = function (value) {
return {
short: value && value.length < 2,
required : value && value.length < 1,
};
};
then you just need to add filterMyItems method to filter your items
To improve the answer of #masitko, I have implemented the filter in a way, that it adds the query to the filtered list. So it becomes selectable and a valid option. So it's possible to make the autocomplete a suggestion box.
I'm using ES6 in my projects. But it should be easily adaptable to ES5 code.
myFilter() {
if (!this.query) return this.items;
const
query = this.query.toLowerCase(),
// filter items where the query is a substing
filtered = this.items.filter(item => {
if (!item) return false;
return item.toLowerCase().includes(query);
});
// add search query to filtered list, to make it selectable
// (only if no exact match).
if (filtered.length !== 1 || filtered[0].toLowerCase() !== query) {
filtered.push(this.query);
}
return filtered;
}

Get selected option in Select2 event, when multiple options can be selected

How can I get hold on the <option> that was just selected when listening to the select2:select event? Note that this is simple when using a single-select, as when only one option is selected, that must be the one that was just selected. I would like to also be able to find the option that was just selected when using a multiple-select (<select multiple>).
In the select2:unselect event, the unselected <option> is available through e.params.data.element, but it is not so in the select2:select event. I do not see a reason why the <option> should not be available, since it is created at this time. For the select2:selecting event, however, the <option> is not yet created, and obviously cannot be available when the event is fired.
I've used the following to get the current selected in Select2 (it's for version 4 and up):
// single value
var test = $('#test');
test.on("select2:select", function(event) {
var value = $(event.currentTarget).find("option:selected").val();
console.log(value);
});
UPDATE: Multi Selected Values (with and without last selected)
// multi values, with last selected
var old_values = [];
var test = $("#test");
test.on("select2:select", function(event) {
var values = [];
// copy all option values from selected
$(event.currentTarget).find("option:selected").each(function(i, selected){
values[i] = $(selected).text();
});
// doing a diff of old_values gives the new values selected
var last = $(values).not(old_values).get();
// update old_values for future use
old_values = values;
// output values (all current values selected)
console.log("selected values: ", values);
// output last added value
console.log("last added: ", last);
});
$('#test').on('select2:select', function(e) {
var data = e.params.data;
console.log(data);
});

How to display previous value on Min Miles text field

I want to display a previous value on Min Miles and that should not be editable. I want like
Default value of Min Miles is 0.
When I click on Add More Range then In the new form - Min Value should be Max Value of Previous Form.
I am using semantic form for. Please Help Me. How can I do this...
Regarding your second question, and assuming that the new form appears through javascript, without page reloading, you can grab the
field value with javascript and use it as the default value for the
new field. The "add new range"
Something Like
function getvalue(){
var inputTypes_max = [],inputTypes_min = [],inputTypes_amount = [];
$('input[id$="max_miles"]').each(function(){
inputTypes_max.push($(this).prop('value'));
});
$('input[id$="amount"]').each(function(){
inputTypes_amount.push($(this).prop('value'));
});
var max_value_of_last_partition = inputTypes_max[inputTypes_max.length - 2]
var amount_of_last_partition = inputTypes_amount[inputTypes_amount.length - 2]
if (max_value_of_last_partition == "" || amount_of_last_partition == "" ){
alert("Please Fill Above Details First");
}else{
$("#add_more_range_link").click();
$('input[id$="min_miles"]').each(function(){
inputTypes_min.push($(this).prop('id'));
});
var min_id_of_last_partition=inputTypes_min[inputTypes_min.length - 2]
$("#"+min_id_of_last_partition).attr("disabled", true);
$("#"+min_id_of_last_partition).val(parseInt(max_value_of_last_partition) + 1)
}
}
I have Used Jquery's End Selector In a loop to get all value of max and amount field as per your form and get the ids of your min_miles field and then setting that value of your min_miles as per max_miles
It worked For me hope It works For You.
Default value of a field can just be passed in the form builder as a second parameter:
...
f.input :min_miles, "My default value"
Of course I do not know your model structure but you get the idea.
Regarding your second question, and assuming that the new form appears through javascript, without page reloading, you can grab the field value with javascript and use it as the default value for the new field. The "add new range" click will be the triggerer for the value capture.
Something like (with jQuery):
var temp_value = '';
$('#add_more_range').click(function(){
temp_value = $('#my_form1 #min_miles').value();
$('#my_form2 #max_miles').value(temp_value);
});
Again I am just guessing the name of the selectors, but the overall approach should work.
If you are also adding dinamically to the page the "Add new range" buttons/links, then you should delegate the function in order to be inherited also for the so new added buttons:
$('body').on('click', '#add_more_range', function(){...});

Processing multiple select controls within jquery mobile form

I am trying to process multiple input selects in a form each one has a unique name and id.
here is my first try, this is broken when y = value.val(); executes
var selects = $("#pmWorkOrderProcedureStepsForm").find('select');
$.each(selects,
function(index, value)
{
y = value.val();
});
I can see in chrome debug that value has a reference to something that looks like
HTMLSelectElement#select-choice-400139826
Where select-choice-400139826 is my first select input name.
How do I get just the name and the selected value of the input from here.
New to jquery mobile!
You can use the following code snippet:
var selects = $("#pmWorkOrderProcedureStepsForm").find("select");
$.each(selects,function(){
name = $(this).attr('name');
value = $(this).val();
});
A demo here - http://jsfiddle.net/5xg6F/
Let me know if that helps.

Resources