- Screen name: mailfonrs
mailfonrs's Profile
8 Posts
12 Responses
0
Followers
Show:
- Expanded view
- List view
Private Message
- 02-Apr-2015 10:47 AM
- Forum: Using jQuery Plugins
Hi,
I have a simple validation for my input elements:-
$("#forma").validate({ errorClass: "red" }); $("#input").each(function(index, elem) { var rules = { required:true }; $(elem).rules("add", rules); });
-
<label id="lastname-error" class="red" for="lastname">This field is required.</label>
span
element inside of those labels, at the beginning (prependTo) with the background-image and other CSS properties, so it will look like this:
-
<label id="lastname-error" class="red" for="lastname"><span class="myspan"></span><This field is required.</label>
-
$("#forma").validate({ errorClass: "red", errorPlacement: function(error, element) { var html = '<span class="myspan"></span>' + $(error).text(); $(error).html(html).insertAfter(element); } });
And this works - span element is added within the error label container, but, if you focus that input and don't type (change) - span element will disapear, and we will again have just label, without span .
This probably means that errorPlacement doesn't 'fire' everytime when errors occur...
So, I tried with highlight:
-
highlight: function(element, errorClass) { $("label."+errorClass).prepend('<span class="
myspan
"></span>') }
And it works, but it adds more then 1 span within the error label.
Do you know how can I solve this problem?
The reason why I want to instert span element with some class within error label is because I want to put background-image to those spans (right arrow picture that will point to input)...
-
.myspan {
background-image: url("images/arrow-left.png");
padding-right: 26px;
background-repeat: no-repeat;
}
- 01-Apr-2015 08:31 AM
- Forum: Using jQuery Plugins
Hi,
I have a simple form that has several input elements that are required:
- $("input").each(function(index, elem) {
- var rules = {
- required:true
- }
- $(elem).rules("add", rules);
- });
And I want to place all error messages within div:
- <div id="errorContainer" class="inputGreska">
- There are some errors. Please correct the following:
- <ul id="errorLabelContainer"></ul>
- </div>
So, I did the following:
- $("#forma").validate({
- errorClass: "red",
- errorContainer: "#errorContainer",
- errorLabelContainer: "#errorLabelContainer",
- wrapper: "li",
- errorElement: "div"
- });
The problem is the following:
If the user forgets to fill more than one input - within error container there will be the same warnings repeated. So, if the user forgets to fill 3 fields, there will be:
- This field is required.
- This field is required.
- This field is required.
Is it possible to show just one error message, like this:
- Fields marked by asterisks (*) are required
no matter how many elements the user has forgotten to fill.
Thank you.- 30-Mar-2015 03:23 AM
- Forum: Using jQuery UI
Hi,
I have read some books and tutorials about using jQuery UI, including Autocomplete widgets... So , I decided to make some simple application where I have JSON file named auto.json in which is data for the Autocomplete widget.
This is my code:
- var
arr = [];
$("#automobil").focus(function() {
$.getJSON("auto.json", function(data) {
$.each(data, function(key, value) {
if ($.inArray(value.name, arr) === -1) {
arr.push(value.name)
}
})
});
}).autocomplete({
source: arr
}).focusout(function() {
arr = [];
});
On StackExchange I asked is it good to empty an array on focusout because my thoughts were that in "real world examples", there can be large amounts of data, so the array needs to be empty on focusout (after the job is done), because of resources...
This is the response that I received:
I believe this is a case of being too paranoid in optimization. Here's some problems:
-
Your
arr
is global. You should probably place this somewhere only the widget knows about. -
You're clearning the array... by creating another array. You're spawning more objects (in this case, an array) instead of cleaning up. The proper way to clear an array is to set
length
to 0. If nothing references the items in the array, they'll get GC'ed eventually. -
autocomplete
,focus
, andfocusout
can go out of sync. When you focus on the input, you dogetJSON
. However, yourautocomplete
will run regardless if the request has returned. So that means the array might be empty when autocomplete runs. When you focus out, you cleared your array, so if you focus in again, this happens. -
You're making unnecessary AJAX calls. On focus, you're calling AJAX. In the real world, waiting for AJAX is a more painful experience than memory consumption. With proper practice, the GC can and will reclaim memory but you can't reclaim the time you waited for AJAX.
I suggest you do the following instead:
-
You can limit the returned results to a reasonable length. That way, even if you hit the server with AJAX for each keypress, the return won't take that long.
-
Cache your results. Have some internal logic which caches returned data into an array (add when non-existent, update if existing). The problem here isn't the size of your cached data. It's the way you're discarding data and retrieving them back again.
Yourarr
is global. You should probably place this somewhere only the widget knows about.You're making unnecessary AJAX calls &autocomplete
,focus
, andfocusout
can go out of sync.
Cache your results.
3. I know nothing about how to Cache results, maybe it has something to do with server-side (for example PHP)?Thank you in advance!
- Hi,
I know that there are many topics about Autocomplete & JSON, but I didn't find what I'm looking for... It is very basic:
I have some simple JSON file named auto.json:
-
[
{"name": "Audi", "model": "A6", "datum": "12.04.2012", "boja": "crna"},
{"name": "BMW", "model": "X5", "datum": "15.03.2011", "boja": "siva"},
{"name": "Ferari", "model": "Spider", "datum": "01.11.2010", "boja": "crvena"},
{"name": "Jugo", "model": "Koral 55", "datum": "04.04.1991", "boja": "bordo"},
{"name": "Zastava", "model": "101", "datum": "18.05.1986", "boja": "plava"},
{"name": "Golf", "model": "2", "datum": "16.02.1990", "boja": "zelena"},
{"name": "Toyota", "model": "Yaris", "datum": "08.10.1998", "boja": "žuta"},
{"name": "Honda", "model": "Civic", "datum": "23.07.2009", "boja": "siva"},
{"name": "Opel", "model": "Corsa", "datum": "31.03.1999", "boja": "plava"},
{"name": "Mustang", "model": "H22", "datum": "19.08.2006", "boja": "zelena"},
{"name": "BMW", "model": "X7", "datum": "13.12.2007", "boja": "siva"},
{"name": "Audi", "model": "A4", "datum": "04.06.1999", "boja": "plava"},
{"name": "Lamborghini", "model": "Diablo", "datum": "29.03.1990", "boja": "bela"},
{"name": "Fiat", "model": "Punto", "datum": "15.09.2003", "boja": "bordo"},
{"name": "Opel", "model": "Astra", "datum": "21.11.2004", "boja": "crvena"},
{"name": "Reno", "model": "Clio", "datum": "07.01.2005", "boja": "bela"},
{"name": "Peugeot", "model": "407", "datum": "08.02.2008", "boja": "plava"},
{"name": "Porsche", "model": "Carrera", "datum": "18.07.2006", "boja": "crna"},
{"name": "Lada", "model": "Niva", "datum": "10.12.1989", "boja": "zelena"},
{"name": "Reno", "model": "Megan", "datum": "04.08.2003", "boja": "bela"}
]
and, I have this input element:
-
<p><label for="automobil">Automobil: </label><input type="text" id="automobil" name="automobil"></p>
How can I implement Autocomplete, for example, just for "name" from auto.json?
Sorry for my bad English. Thank you in advance!
- Hi,
I was reading http://api.jqueryui.com/datepicker/ and I downloaded .datepicker-fr.js from here: https://github.com/jquery/jquery-ui/tree/master/ui/i18n
Here is my code:
-
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Example</title>
<link href="styles/css.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="scripts/jquery-2.1.1.js"></script>
<link href="scripts/ui/jquery-ui.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="scripts/ui/jquery-ui.js"></script>
<script type="text/javascript" src="scripts/ui/datepicker-fr.js"></script>
<script type="text/javascript">
$(function() {
$("#datum").datepicker($.datepicker.regional["fr"]);
})
</script>
</head>
<body>
<div class="ui-widget">
<span id="datum"></span>
</div>
</body>
</html>
But, for some reason - it doesn't work? Do you know what could be the problem?
- Hi,
I'm not sure if I understood well what converters actually do. Here's an explanation from http://api.jquery.com/jquery.ajax/ :
- converters (default:
{"* text": window.String, "text html": true, "text json": jQuery.parseJSON, "text xml": jQuery.parseXML}
)Type: PlainObjectAn object containing dataType-to-dataType converters. Each converter's value is a function that returns the transformed value of the response. (version added: 1.5)
Concretely:
-
converters: {
"text json": function(data) {
return data;
}
}
without this, one application from one tutorial does not work... here's the rest of the code:
-
$("#buttonDiv").click(function(e) {
var unetiPodaci = $("#orderForm").serialize();
e.preventDefault();
$.ajax({
url: "http://localhost",
type: "post",
data: unetiPodaci,
dataType: "json",
dataFilter: function(siroviOdgovor, dataType) {
var jsonOdgovor = $.parseJSON(siroviOdgovor);
var cleanData = {
totalItems: jsonOdgovor.totalItems,
totalPrice: jsonOdgovor.totalPrice
};
delete jsonOdgovor.totalItems;
delete jsonOdgovor.totalPrice;
cleanData.products = [];
for (prop in jsonOdgovor) {
cleanData.products.push({
name: prop,
quantity: jsonOdgovor[prop]
})
}
return cleanData;
},
converters: {
"text json": function(data) {
return data;
}
},
success: function(data) {
obradiPrimljeniOdgovor(data);
}
})
})
Correct me if I'm wrong , maybe it means that the response (which is a text) will be converted to json? If so, then why is something like that needed when we have:
- dataType:
"json",
dataFilter: function(siroviOdgovor, dataType) {
var jsonOdgovor = $.parseJSON(siroviOdgovor);
where it is already stated that we expect "json" and in dataFilter we parsed response to JSON?
- Hi,
I get the following response from the server:
-
{"aster":"3","daffodil":"4","rose":"3","totalItems":10,"totalPrice":"31.90"}
and, I want to put it in the table that will look like this:
The problem is that I do not know how to get values (for the "Quantity" column). This is my code:
-
function processServerResponse(data) {
if (data.products.length > 0) {
$("#orderForm").hide();
$("#summaryForm").show();
var html = '';
$.each(data.products, function(key, value) {
html += "<tr><td>"+value.name+"</td><td>"+?????+"</td></tr>"
});
$(html).appendTo("tbody");
$("#totalItems").text(data.totalItems);
$("#totalPrice").text(data.totalPrice);
}
}
Before that, this is how my $.ajax looks like (it's bigger code, y ou don' have to read it out):
-
$("#orderForm button").click(function (e) {
e.preventDefault();
var formData = $("#orderForm").serialize();
$("#popup").show();
$("body *").not("#popup").css("opacity", 0.5);
$("input").prop("disabled", true);
$.ajax({
url: "http://localhost/",
type: "post",
data: formData,
dataType: "json",
dataFilter: function(data, dataType) {
primljeniOdgovor = $.parseJSON(data);
var cleanData = {
totalItems: primljeniOdgovor.totalItems,
totalPrice: primljeniOdgovor.totalPrice
};
delete primljeniOdgovor.totalItems;
delete primljeniOdgovor.totalPrice;
cleanData.products = [];
for (prop in primljeniOdgovor) {
cleanData.products.push({
name: prop,
quantity: data[prop]
})
}
return cleanData;
},
converters: {
"text json": function(data) {
return data;
}
},
success: function(data) {
processServerResponse(data);
},
complete: function() {
setTimeout(function() {
$("#popup").hide();
$("body *").not("#popup").css("opacity", 1);
$("input").prop("disabled", false);
}, 1500);
}
});
})
I get the name from that response by value.name , but I have no idea how to get that value (quantity)?
- Hi,
First of all , I apologize - my English is bad .
Is it a bad approach to put all the main code inside success setting ($.ajax({ success: ) - for example, I have this JSON in file mydata.json:
-
[
{"name":"Aster","product":"aster","stock":"10","price":"2.99"},
{"name":"Daffodil","product":"daffodil","stock":"10","price":"1.99"},
{"name":"Rose","product":"rose","stock":"2","price":"4.99"},
{"name":"Peony","product":"peony","stock":"3","price":"1.50"},
{"name":"Primula","product":"primula","stock":"20","price":"3.12"},
{"name":"Snowdrop","product":"snowdrop","stock":"5","price":"0.99"},
{"name":"Carnation","product":"carnation","stock":"1","price":"0.50"},
{"name":"Lily","product":"lily","stock":"2","price":"1.20"},
{"name":"Orchid","product":"orchid","stock":"5","price":"10.99"}
]
And, my code looks like this:
-
$.ajax({
url: "mydata.json",
success: function(data) {
var html = '';
$.each(data, function(key, value) {
html += '<div class="dcell">';
html += '<img src="images/'+value.product+'.png">';
html += '<label for="'+value.product+'">'+value.name+':</label>';
html += '<input id="'+value.product+'" type="text" required="" value="0" name="'+value.product+'" stock="'+value.stock+'">'
html += '</div>';
});
$(html).filter("div").slice(0,3).appendTo("#drow1");
$(html).filter("div").slice(3,6).appendTo("#drow2");
$(html).filter("div").slice(6).appendTo("#drow3");
/* OVO JE ZA VALIDACIJU - POCETAK */
$("<div id='errorContainer'>Odgovor...:</div>")
.addClass("inputGreska").append("<ul id='errorLabelContainer'></ul>").hide().insertAfter("h1");
$("form").validate({
highlight: function(element, errorClass) {
$(element).addClass("invalidElem");
},
unhighlight: function(element, errorClass) {
$(element).removeClass("invalidElem");
},
errorContainer: "#errorContainer",
errorLabelContainer: "#errorLabelContainer",
wrapper: "li",
errorElement: "div"
});
var plurals = {
aster: "Asters",
daffodil: "Daffodils",
rose: "Roses",
peony: "Peonies",
primula: "Primulas",
snowdrop: "Snowdrops",
carnation: "Carnations",
lily: "Lillies",
orchid: "Orchids"
}
$("input").each(function(index, elem) {
$(elem).rules("add", {
required: true,
min: 0,
digits: true,
messages: {
required: "Please enter a number of "+plurals[elem.name],
digits: "Please enter a number of "+plurals[elem.name],
min: "Please enter a positive number of "+plurals[elem.name]
}
})
}).change(function(e) {
$("form").validate().element($(e.target));
});
/* OVO JE ZA VALIDACIJU - KRAJ */
$("#drow2, #drow3").hide();
$("<a id='left'></a>").prependTo("#oblock").css({
"background-image": "url(images/leftarrows.png)",
"display": "block",
"float": "left",
"width": "50px",
"height": "50px",
"margin-top": "15px"
}).hover(handleMouseEnter).click(handleMouseClick);
$("<a id='right'></a>").appendTo("#oblock").css({
"background-image": "url(images/rightarrows.png)",
"display": "block",
"float": "right",
"width": "50px",
"height": "50px",
"margin-top": "15px"
}).hover(handleMouseEnter).click(handleMouseClick);
function handleMouseEnter(e) {
if (e.type == 'mouseenter') {
$(this).css({
"background-position": "-50px 0px",
"cursor": "pointer"
});
} else {
$(this).css({
"background-position": "0px 0px"
});
}
}
function handleMouseClick(e) {
var redovi = ["drow1", "drow2", "drow3"];
var trenutniRed = $("div.drow:visible");
var indexTrenutnogReda = jQuery.inArray(trenutniRed.attr("id"), redovi);
var indexNovogReda;
if ($(this).attr("id") == "left") {
indexNovogReda = indexTrenutnogReda - 1;
if (indexNovogReda < 0) {
indexNovogReda = redovi.length -1;
}
} else {
indexNovogReda = (indexTrenutnogReda + 1) % redovi.length;
}
trenutniRed.fadeOut("fast", function() {
$("#"+redovi[indexNovogReda]).fadeIn("fast");
});
}
$("#buttonDiv").prepend("<div>Total Items: <span id='total'>0</span></div>");
$("input").change(function(e) {
$("form").validate().element($(e.target));
var total = 0;
$("input").each(function(index, value) {
total += Number($(value).val());
});
$("#total").text(total);
})
}
})
As you can see - everything is in the success setting of jQuery.ajax().
For this particular example , I know it can be done in a different way so that there is NOT almost everything inside success setting of jQuery.ajax() - but, does it make any difference ? Or , it does not matter?
Thanks in advance!
- «Prev
- Next »
-
-
-
-
-
Moderate user : mailfonrs
© 2013 jQuery Foundation
Sponsored by and others.

