In my project, I have a one-to-many relation (a Client has many contacts), Now, I am listing the clients in a Drop-down menu, What i want is, To have the Selected Client's Contacts rendered dynamically as check-boxes.
Here is (the part) of my _form.html.haml, and the jQuery part that sends the Ajax request:
%h4 This meeting is made for :
= f.input :client_id, collection:(Client.all)
%br
%hr
%h4 Assign Contacts:
//HERE WHERE I REALLY WANT THE CHECKBOXES TO BE REDNERED DYNAMICALLY.
= check_box_tag "contact_ids[]", c.id, #meeting.contacts.include?(c)
= c.first_name
%br
:javascript
$(document).ready(function (){
$('#meeting_client_id').change(function(){
var state = $('#meeting_client_id :selected').val();
if(state !== "")
{
$.getJSON('/clients/client_contacts/' + state, function(data){
console.log(data);
})
}
return false;
})
});
and here is my Clients_controller action, that handles the request:
def client_contacts
client = (params[:id])
cou = Contact.where(client_id: client)
#msg = { "success" => "true", "message" => "hello", "count" => cou}
respond_to do |format|
format.html
format.json { render json: #msg }
end
end
Now, in the console, I can see that the request is returning the count, and objects.
and hence I am really new to JS/jQuery , and fairly new to Rails, I really don't know how to take it from here.
Any tips/Articles/links/Helps or advice, is really appreciated.
If the only part you're missing is the creation of checkboxes, you can try something like this;
var output = $("some selector for an element containing the checkboxes");
$('#meeting_client_id').change(function(){
var state = this.value;
if(state !== "") {
$.getJSON("/clients/client_contacts/" + state).done(function(data) {
output.empty(); // clear the container
// assuming data is an array of strings, modify as needed
$.each(data, function () {
// for each array item in the result, create a checkbox
$('<input type="checkbox" value="'+this+'">'+this+'</option>')
.appendTo(output); // append it to the container
});
});
}
});
The important parts I used here is:
$.each() for looping through arrays: http://api.jquery.com/jQuery.each/
$("<html>") syntax for creating a new element: http://api.jquery.com/jQuery/#jQuery2
.appendTo() for attaching to the DOM: http://api.jquery.com/appendTo/
Here is a demo where i'm just using a custom function to fake the ajax call.
http://jsfiddle.net/kK622/1/
try this:
$.getJSON('/clients/client_contacts/' + state, function(data){
console.log(data);
data.each(function(){
var id = data.id;
var name = data.firstName;
//add to new div with id myDiv
$('#myDiv').append('<input name='+ id +' type="checkbox" /> ' + name + '<br />');)
});
});
Related
i am looking for a nice document explaining well about pagination in react native.I can't find a one i'm looking for.I'm fetching the data from server (set of 15 questions and answers).I want to display single question in a page with a next or previous button at the bottom.How to do this?Now i'm displaying all the 15 questions in a single page with ScrollView. But i want pagination.Please help me.
The library react-native-swiper would be the best to use in such a scenario.The example is mentioned in the following link here.
This library uses ScrollView , with a snap animation effect for each item and also contains the customized next and previous button as mentioned here.
var start=0; // above class
var end=100;
fetchData = () => {
var mydata = realm.objects('Product_Info');
this.setState({dbData: mydata})
console.log("fetch---------- paggingData.start--> " + start);
console.log("fetch---------- paggingData.end--> " + end);
var newData = mydata.filtered('prodId > $0 AND prodId <= $1' , start, end); // TODO Logic fetch Data
let paggingData =[];
paggingData = JSON.parse(JSON.stringify(this.state.paggingData));
Object.keys(newData).map(key => {
paggingData.push(newData[key])
})
this.setState({
paggingData
}, () => {
console.log('Search-------------------------------PAGGGING DATA \n', this.state.paggingData)
})
this.setState({dataProvider: dataProvider.cloneWithRows(paggingData)}) //TODO ... working in RecyclerView both
}
onScroll = () => {
console.log("Scrolling");
}
onEndReached = () => {
console.log("\n\n\n\n\--------------------------------------------Reached to End---------------------------------------------");
start = end;
end = end+100;
this.fetchData()
}
<RecyclerListView
layoutProvider={this.layoutProvider}
dataProvider={this.state.dataProvider}
rowRenderer={this.rowRenderer}
onEndReached={this.onEndReached}
onScroll={this.onScroll}
/>
I am working on a task to learn how to use JSON. I am trying to link to spotify's API via a search, get an artists albums and show them on the webpage. I am a beginner and do not know what I am missing in the data / callback function to create the correct html to show on my page. If anyone has time to point me in the right direction, it would be appreciated.
$(document).ready(function() {
// Creating the AJAX Request
//
$('#search').submit(function(event) {
// Stop the form from submitting
event.preventDefault();
// Get The value from the form
var SpotifyURL = "https://api.spotify.com/v1/searchjsoncallback=?";
var artist = $('#search').val();
var artistOptions = {
"type" : "album",
"q" : "artisit"
};
function displayAlbums(data) {
var albumHTML = '<ul>';
$.each(data.items,function(i, album) {
albumHTML += '<li class="albumInformation">';
albumHTML += '<></li>';
}); // end each
albumHTML += '</ul>';
$('#albums').html( albumHTML);
}
$.getJSON(SpotifyURL, artistOptions, displayAlbums );// end getJSON
}); // end submit function
}); // Closing Ready function
I am using auto-complete web service sing JSON, If i am selecting a list item that must not be appear again in auto-complete list;
JSON AJAX code:
select: function (event, ui) {
var terms = split(this.value);
if (terms.length <= 10) {
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
else {
var last = terms.pop();
$(this).val(this.value.substr(0, this.value.length - last.length - 0)); // removes text from input
$(this).effect("highlight", {}, 1000);
$(this).addClass("red");
$("#warnings").html("<span style='color:red;'>Max skill reached</span>");
return false;
}
}
I am attaching screenshot also, please see here :
Like #Bindred mentioned in the comments to your question, an easier solution would be to use the Select2 jQuery library. It is not exactly what you are looking for, but as far as UX goes I think it would achieve a similar goal, and it is a breeze to get working.
I have added an example for you to use: https://jsfiddle.net/9cqc5876/9/
HTML
<select id="txtExpertise" multiple="multiple"></select>
JavaSript
$(document).ready(function() {
$("#txtExpertise").prop("disabled", "disabled");
// do your ajax request for data
//$.getJSON("../WebServices/WebServiceSkills.asmx/GetAutoCompleteData", function(data) {
// fake json data
var data = {"languages": ["Java", "C", "C++", "PHP", "Visual Basic",
"Python", "C#", "JavaScript", "Perl", "Ruby"]};
// populate the select
$.each(data.languages, function(key, val) {
$('#txtExpertise')
.append($("<option></option>")
.attr("value", key)
.text(val));
});
// activate the select2
$("#txtExpertise").select2();
$("#txtExpertise").prop("disabled", false);
//});
});
I'm using Firefox and working on a page when I notice that & turns into &.
Usually I can fix this by using html_entitiy_decode() - but in this case it's not working.
Then I discovered this. The alert is fired once the page is loaded.
Before
After
The data is loaded using PHP / Yii - not through JS / Ajax. I am however adding / removing brands using JS Knockout.
<ul data-bind="template: { name: 'brand-item-template', data: $root.brands}">
<li>
<span id="<?= $brand->id?>" data-bind="text: brand_name, attr: {'id': brand_id}"><?= $brand->name; ?></span>
</li>
</ul>
Update
I've discovered that this JS Knockout code is what makes the change. But this code should not be triggered until I add a brand. So why is this affecting my &s?
It's the self.addBrand = function() that makes the change. If I remove this function and leave the rest as it is, everything is fine. Can it be a Knockout bug?
$('#store.manage-special-offers').exists(function(){
Store.mangeSpecialOffers();
});
function manageBrandListModel() {
var self = this;
var store_id = $('.data-item-id').val();
var exiting_list = $('.brand-list ul').clone();
// Data
self.brands = ko.observableArray(create_list(exiting_list));
self.brand_name = ko.observable();
self.brand_id = ko.observable();
self.store_id = ko.observable(store_id);
// This is the function that makes the chage
self.addBrand = function() {
if (self.brand_name() != "") {
// Update DB
$('#store.manage-brands').exists(function(){
$.ajax({
url: site_url + '/associatebrand',
type: "POST",
dataType: 'json',
data: {
Brand: {
brandId : self.brand_id(),
storeId : self.store_id(),
add : true
}
},
success: function (data) {
// Add brand to GUI list
self.brands.push(new brand(self.brand_id(), self.brand_name()));
self.brand_name("");
}
});
});
}
}.bind(self);
(...)
function create_list(exiting_list){
var arr_list = [];
$(exiting_list).find('li').each(function(e,li){
var id = $(li).find('span').prop('id');
var name = $(li).find('span').html(); // <--- This is the problem. Must be .text()
arr_list.push(new brand(id,name));
});
return arr_list;
}
Can anyone explain why this is happening?
The credit should really go to both JeremyCook and Quentin for pointing me in the right direction.
$(exiting_list).find('li').each(function(e,li){
var id = $(li).find('span').prop('id');
var name = $(li).find('span').html(); // <--- This is the problem. Must be .text()
arr_list.push(new brand(id,name));
});
What I did wrong was that I used .html() and the text was returned in HTML format. Changing this to .text() solved my problem.
There are interesting task: my active record 'Event' entity can contain one 'Attachment' PDF file. On the Create Event page, user can Upload this attachment BEFORE Submits that Event. Attachment uploads to Amazon via Ajax, progress-bar displays etc blablabla.
It should be displayed in_a_way:
= form_for #event do |e|
= e.text_field :name
= form_for #attach, :remote=>true, html=>{:multipart=>true} do |at|
= at.file_field :pdf, :accept=>"pdf", :size=>"1"
= at.submit
= e.submit
Yes, this is just pseudo-code, and I don't mind how it can work, but the main idea is presents: [Submit Attachment] button should be placed inside the Event form.
How I can implement it? Maybe, just make some offset to nested Attachment form so it will be displayed inside Event form, or there are any others solutions?
..........................................................................................................
Solution: override form headers
This is a form for creating new event.
Inside this form, we need ajax file uploading.
There is a solution: mixing single form between two different types of submits: ajax(js) and html:
= form_for #event, html=>{:multipart=>true} do |e|
= e.text_field :name
= file_field_tag "attach[pdf]", :id=>"attach_pdf", :accept => "pdf", :maxlength => "200"
= submit_tag "", :id => "ajax_submit", :style=>"display:none"
= e.submit <!-- id = "new_event_submit" -->
////////////////////////////
// before 'submits' call override functions:
$("#ajax_submit").click(function(){
prepeareFormForAjax();
return true;
});
$("#new_event_submit").click(function(){
prepeareFormForHtml();
return true;
});
//////////////////////////////
// to store original (previous, html) form data
var html_form_action = "";
var html_form_method = "";
///////////////////////////////
/*
* To ajax file upload:
**/
function prepeareFormForAjax() {
$("form").attr("data-remote", "true");
$("form").attr("enctype", "multipart/form-data");
html_form_action = $("form").attr("action"); // save old action
$("form").attr("action", "/attach"); // I need /nors action
//_method field is a hidden form field, maybe you have it too on the page:
if ($('input[name="_method"]').length != 0) {
html_form_method = $('input[name="_method"]').val();
$('input[name="_method"]').val("post");
}
}
function prepeareFormForHtml() {
$("form").removeAttr("data-remote");
$("form").removeAttr("enctype");
if (html_form_action != "") {
$("form").attr("action", html_form_action);
html_form_action = "";
}
if (html_form_method != "") {
$('input[name="_method"]').val(html_form_method);
html_form_method = "";
}
}
///////////////////////
Now, to upload file via AJAX use:
$("#ajax_submit").click();
any questions?