Hi
I have 3 selectors, where Products depends on type and number of products depends on Products.
Type --> Products --> Number Of Products
Im loading everything from a mySQL server and extract the data with $.getJSON. So when you load the types it automaticly fills the products with names and so on.
The problem I have now is that I want the number of products to change when the product change, but if you look at the example further down, you will see that's not the case.
Initially when you load the page the third selector wont even show any options, and when you change the "type" it wont update either.
It's only when you change the productname that this will happend.
I want this to automaticly change, how do I do this?
Thanks in advance!
This is the code I'm using,
<form>
Type:
<select name="name" id="lensType">
<option selected>Endagslins</option>
<option>Dygnet-runt-lins</option>
<option>2-veckorslins</option>
<option>Manadslins</option>
</select>
Product:
<select name="productName" id="products">
</select>
Number of products:
<select name="numberOfLenses" id="numberOfLenses">
</select>
</form>
<script type="text/javascript">
function getProducts() {
$.getJSON('getProducts.php', {lensType:$('#lensType').val()}, function(data) {
var select = $('#products');
var options = select.attr('options');
$('option', select).remove();
$.each(data, function(index, array) {
options[options.length] = new Option(array['productName']);
});
});
}
$(document).ready(function() {
getProducts();
$('#lensType').change(function() {
getProducts();
});
});
function getNumberOfLenses() {
$.getJSON('getNumberOfLenses.php', {productName:$('#products').val()}, function(data) {
var select = $('#numberOfLenses');
var options = select.attr('options');
$('option', select).remove();
$.each(data, function(index, array) {
options[options.length] = new Option(array['numberOfLenses']);
});
});
}
$(document).ready(function() {
getNumberOfLenses();
$('#products').change(function() {
getNumberOfLenses();
});
});
</script>
I figured it out myself :)
I used this code
function getProducts() {
$.getJSON('getProducts.php', {lensType:$('#lensType').val()}, function(data) {
var select = $('#products');
var options = select.attr('options');
$('option', select).remove();
$.each(data, function(index, array) {
options[options.length] = new Option(array['productName']);
});
getNumberOfLenses();
});
}
function getNumberOfLenses() {
$.getJSON('getNumberOfLenses.php', {productName:$('#products').val()}, function(data) {
var select = $('#numberOfLenses');
var options = select.attr('options');
$('option', select).remove();
$.each(data, function(index, array) {
options[options.length] = new Option(array['numberOfLenses']);
});
});
}
$(document).ready(function() {
getProducts();
$('#lensType').change(function() {
getProducts();
});
$('#products').change(function() {
getNumberOfLenses();
});
});
Related
I have been trying to add the chosen jquery for my selectbox which is fetching the values from database based on another. The normal selectbox works fine and all the options are getting displayed but the chosen jquery is not working.
I won't put the script tags over here because the chosen jquery is working fine for hard coded values of host names.I have applied jquery for 'host_name' scrolling list.
This is what i tried
$( function() {
$(".host_name").chosen(); });
or:
$( function() {
$("#host_name").chosen().change(host_name); })
or:
$( function() {
$('#host_name').trigger('chosen:updated');
})
perl cgi code containing ajax for fetching data from database scrolling list:
my $JAVASCRIPT = <<'ENDJS';
function call(host)
{
//alert("in call");
var selos=document.getElementById("ostype");
var x=selos.options[selos.selectedIndex].text;
if (x){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange=function() {
if (this.readyState == 4 && this.status == 200) {
var obj=JSON.parse(this.responseText);
var select = document.getElementById("host_name");
for (var key in obj){
var option = document.createElement('option');
option.text = option.value = obj[key];
select.add(option, 0);
//document.getElementById('host_name').appendChild(var);
}
}
};
xhttp.open("GET", "logic.cgi?ostype="+x, true);
xhttp.send();
}
}
cgi code for html
$q->start_td({-colspan=>2}),
$q->scrolling_list(-name=>'ostype',
-size=>1,
-id=>'ostype',
-values=>['RHEL','Windows','SLES'],
-onClick=>'together()',
-onChange=>'call()'
),
$q->end_td,
"Host name",$q->font({-color=>'red'},"*") ,
$q->end_td,
$q->start_td({-colspan=>2}),
$q->scrolling_list({-style=>'width:150px',
-name=>'host_name',
-class=>'host_name',
-id=>'host_name',
-size=>'3',
-values=>[],
-multiple=>'true'}
),
$( function() {
$(".host_name").chosen(); });
The $(".host_name") jQuery selector selects all elements with the class hostname (e.g. <div class="host_name"></div>).
$( function() {
$("#host_name").chosen().change(host_name); })
The $("#host_name") jQuery selector selects all elements with the id hostname (e.g. <div id="host_name"></div>)
$( function() {
$('#host_name').trigger('chosen:updated');
})
You might want to check the chosen() documentation for usage examples, too.
There's an error in your commented-out bit of JavaScript:
//document.getElementById('host_name').appendChild(var);
It should be
//document.getElementById('host_name').appendChild(option);
I am using jquery UI autocomple with json data source but it's not working but when I used same with fixed data it works. Below is my code.
$(document).ready(function () {
var codes = "";
Admin_BasicFeeSchedule.LoadCPTCodes().done(function (response) {
if (response.status != false) {
if (response.CPTCodeCount > 0) {
var CPTCodeLoadJSONData = JSON.parse(response.CPTCodeLoad_JSON);
$.each(CPTCodeLoadJSONData, function (i, item) {
codes = codes + "'" + item.ShortName + "'";
});
//codes = codes + "]";
alert(codes);
}
}
else {
utility.DisplayMessages(response.Message, 3);
}
});
$.widget("ui.autocomplete", $.ui.autocomplete, {
_renderMenu: function (ul, items) {
var that = this;
$.each(items, function (index, item) {
that._renderItemData(ul, item);
});
$(ul).wrap("<div></div>");
},
});
$("input#ddlCPTCode").autocomplete({
source: [codes],//['Tom', 'Alex', 'Patrick'],
});
});
Based on jQueryUI's API, the source option can either be an array or a String that points to an URL or a Function. Furthermore, your code needs to change few things so that the array is handled in appropriate fashion:
$(document).ready(function () {
var codes = []; // array is created
Admin_BasicFeeSchedule.LoadCPTCodes().done(function (response) {
//alert("LoadCPTCodes works") ;
if (response.status != false) {
//alert("response.status true") ;
if (response.CPTCodeCount > 0) {
//alert("CPTCodeCount > 0") ;
var CPTCodeLoadJSONData = JSON.parse(response.CPTCodeLoad_JSON);
$.each(CPTCodeLoadJSONData, function (i, item) {
codes.push(item.ShortName); //add item to an array
});
//codes = codes + "]";
alert(codes);
}
}
else {
utility.DisplayMessages(response.Message, 3);
}
});
$.widget("ui.autocomplete", $.ui.autocomplete, {
_renderMenu: function (ul, items) {
var that = this;
$.each(items, function (index, item) {
that._renderItemData(ul, item);
});
$(ul).wrap("<div></div>");
},
});
$("input#ddlCPTCode").autocomplete({
source: codes // pass an array (without a comma)
});
});
Finally, if those changes related to the array aren't enough to make it work, then I would check the JSON load part. I have added some alert calls that can be uncommented for JSON testing purposes. As I am not familiar with the details of the JSON load functionality that is used in the sample code, then I'm just going to mention that there are alternative ways of loading JSON data such as jQuery's getJSON method.
I have div with unique id and I'm trying to get that div id with jQuery
<div class="quantity" id="UNIQUE_ID">Quantity</div>
Everything works good, but after loading div with ajax - I just can't get id from loaded div.
$('.quantity').click(function() {
$.post('quantity.php', { id: $(this).attr('id') }, function(output) {
$(this).html(output);
});
});
Any ideas?
This should work
$('.quantity').click(function() {
var that = this;
$.post('quantity.php', { quantityId: $(that).attr('id') }, function(data) {
$(that).html(data);
});
});
But this is how i'd write it
<div class="quantity" data-id='<?=$unique_id?>'>
Quantity
</div>
$('.quantity').on('click', function() {
var that = this;
$.post('quantity.php', { quantityId: $(that).data('id') }, function(data) {
$(that).html(data);
});
});
And for dynamic divs
<div class="quantity" data-id='<?=$unique_id?>'>
Quantity
</div>
$(document).on('click', '.quantity', function() {
var that = this;
$.post('quantity.php', { quantityId: $(that).data('id') }, function(data) {
$(that).html(data);
});
});
The onclick binding to your div won't work once the div has been refreshed (it binded on document.ready() right?). The solution will be either to rebind the function to your element every time you change it (a bad one) or use the on() function of jquery. Example code:
$(document).on('click', '.quantity', function(){
var id = $(this).attr('id');
$.post('quantity.php', { quantityId: id }, function(data){
$('#'+ id).html(data);
});
});
UPDATE: As discussed in comments, the on method should bind to the document as a whole and not the the class to actually work as the deprecated live() method.
I am having difficulty with knockout refreshing.
Here's my viewModel;
$(document).ready(function () {
ko.applyBindings(new Task(), document.getElementById('taskSummary'));
setInterval(Task, 2000);
});
function task(name, description, project) {
var self = this;
self.name= ko.observable(name);
self.description = ko.observable(description);
self.project = ko.observable(project);
}
function Task() {
var self = this;
self.tasks = ko.observableArray([]);
self.tasks.removeAll;
$.getJSON("/api/tasks/5", function (data) {
$.each(data, function (key, val) {
self.tasks.push(new task(val.Name, val.Description, val.Project));
});
});
}
It returns data to the view but does not update when I change the data in the back end database.
any help appreciated. Im sure its something small that I'm missing.
For knockout, it might be better if you apply your model to a new Task instance, save that instance, then set up a setInterval loop that can modify the Task's "tasks" observableArray values.
$(document).ready(function () {
var oTask = new Task();
ko.applyBindings(oTask, document.getElementById('taskSummary'));
function onLoop() {
var self = oTask;
$.getJSON("/api/tasks/5", function (data) {
self.tasks.removeAll(); // not sure if you need this...
$.each(data, function (key, val) {
self.tasks.push(new task(val.Name, val.Description, val.Project));
});
});
}
setInterval(onLoop, 2000);
});
Hi all I have a site developed in cakephp and I would to integrate backbone on it.
For my scope I would to use external js for backbone to reuse the code.
I have write some lines but I can't append results on my element.
I have tried to print the "el" in this modes:
console.log($(this.el));
console.log(this.el);
console.log(this.$el);
But nothing I can't enter into el to make a simple append!
The container #search-results already exist
This is my main view:
<script type="text/javascript">
var search = {};
search.product = {};
search.product.template = "#results-product-template";
search.product.container = "#search-results";
search.product.defaults = {
id:0,
type:"product",
};
$(function(){
var ProductList = new Search.Collections.Products();
var ProductView = new Search.Views.Product({
// new Search.Collections.Products();
collection:ProductList
,el:$("#search-results")
});
function parseResults () {
var json = {
//my data
}
for (var i = json.products.length - 1; i >= 0; i--) {
ProductList.add([new Search.Models.Product(json.products[i])]);
};
updateResults();
}
function updateResults () {
console.log('updateResults: Ritorno il risultato quando hunter riceve una risposta dal server');
if ($('#search-results').length == 0) {
$('div.main > section:first-child').before('<section id="search-results"> <ul id="product-results"> <li>Contenuto</li> </ul> </section>');
}
ProductView.render();
}
// search
$('#search-results .close').on('click', function () {
$('#search-results').animate({height:0}, 500, function () {
$(this).remove();
})
});
});
</script>
And this is my external js with backbone
var Search = {
Models: {},
Collections: {},
Views: {},
Templates:{}
}
Search.Models.Product = Backbone.Model.extend({
defaults: search.product.defaults || {},
toUrl:function (url) {
return url.replace(" ", "-").toLowerCase();
},
initialize:function () {
console.log("initialize Search.Models.Product");
this.on("change", function (){
console.log("chiamato evento change del Model Search.Models.Product");
});
this.on("change:text", function () {
console.log("chiamato evento change:text del Model Search.Models.Product");
});
}
});
Search.Collections.Products = Backbone.Collection.extend({
model: Search.Models.Product,
initialize:function () {
console.log("initialize Search.Collections.Products");
console.log(this);
console.log(this.length);
console.log(this.models);
}
});
Search.Views.Product = Backbone.View.extend({
initialize:function () {
console.log("initialize Search.Views.Product");
console.log($(search.product.template).html());
},
template:function (data) {
if (data == null) {
data = this.collection.toJSON();
}
var template = Handlebars.compile($(search.product.template).html());
template(data);
},
render:function () {
console.log($(this.el));
$(this.el.append("TEST"));
//HERE IS THE PROBLEM
// I have tried this.$el.append("TEST");
return this;
}
});
Does this change anything?
var ProductView = new Search.Views.Product({
// new Search.Collections.Products();
collection:ProductList,
el:$("#search-results")[0]
});
I think backbone can accept both jQuery wrapped or not wrapped object and be fine, but I don't know what Backbone version you are using, see if this works
EDIT: From backbone 1.0 sources, it seems backbone can indeed take either a jQuery wrapped object or a regular dom element, it should still work
this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);
Do you have something online (JSFiddle?) I will be happy to take a look, but this.$el should work and be equal to $("#search-results") from your code in a quick glance.
Have you tried using ProductView.setElement($("#search-results")) instead? it should be the same, but worth a try as well.