Use both jQuery.checkbox & jQuery.field - javascript

I am trying to use two jQuery solutions on the one form, but I am unable to get the desired result after working on it for several hours.
The first jQuery solution enables a better look and feel
http://www.envirotalk.com.au/jquery/jquery-checkbox.htm
The second jQuery solution enables a limit to be set on the number of checkboxes selected.
http://www.envirotalk.com.au/jquery/jquery-field.htm
This is my attempt at combining the two.
http://www.envirotalk.com.au/jquery/combined.htm
I believe the problem relates to this line of code, but I cannot be certain.
setLimitSelection();
The outcome I am trying to achieve.
Look and feel; jquery-checkbox
Limit to the number of checkboxes one
can select; jquery-field
The error message; jquery-field
Clearing the extra field value once
exceeded limit; jquery-field.
If someone has the time to take a look and help me, that would be greatly appreciated.

The two plug-ins are probably conflicting with each other, since the code that you're using is the same as the ones given in the individual examples. For limiting checkboxes that can be selected, you can try this:
function setLimitSelection(){
$("input[type=checkbox]").click(function(){
var checkboxes_to_allow = 3;
if($('input[type=checkbox]:checked').length == (checkboxes_to_allow+1)){
//show error message
return false;
} else {
//clear message
}
});
}
I think the code is clear enough to not need comments?

Hello I think you can solve the problem with a small status variable like checkfield:
var checkfield = false;
$("input[name ='name']").limitSelection({
limit: 3,
onfailure: function (n){
checkfield = true;
return false;
}
}).click(function (){
if (field6error)
{
$(this).checkBox('changeCheckStatus', false);
checkfield = false;
alert("Not more than 3 values!")
return false;
}});

Related

jQuery code should change something simple in web page by using JSON data from two external device buttons

This is my school project. I have tried to do it as simple as possible, just to change background color in web page etc..
I work with an external device with two buttons (microbit a and b) -connected in serial port, writing data string "aa" or "bb". Then python code reads it inside for ever loop and writes it in json file, where this code should be able to enter in. With these changing json time stamps, this code should read which button was pressed latest and then do what is written in conditions.
json files reference time is changing all the time, by the button press.
I am very thankful for any help, we have been doing this project already quite long, this is final stage but as you see ,but i am not yet there.
As this does not execute anything after get json line... it did once, and till final >>if, but then it stopped..why? I dont know.. I am not good enough in this.
Final part of the code curly braces etc, i cant anymore count which one is too much or >>what is missing?! ...
my json example: {"REF": 1624391142, "aa": 1624391140, "bb": 1624391142}
$(document).ready(function () {
console.log("jQuery starts");
var d = new Date();
var time = d.getTime();
setInterval(function () {
// loop that reads every 2 sec json file,
$.getJSON("data.json"),
function (json) {
console.log("test", time);
//what is REF-time <= time
if (time <= json.REF) {
// any changes?
time = json.REF;
console.log(" REF", time);
pressedBtn = "";
jQuery.each(json, function (key, value) {
//searhing
if (value == time && key != "REF") {
pressed = key;
console.log("Working");
}
if (pressedBtn == "aa") {
$("body").show("active"); //background color change
console.log("pressed", pressedBtn);
$("#toshow").show("toshow"); // comment div
}
if (pressedBtn == "bb") {
$("#toshow").hide("toshow"); //comment div
console.log("pressed", pressedBtn);
}
});
}
};
}, 2000);
});
I think I understood you and maybe this is your solution check this
$(document).ready(function(){
setTimeout(doSomething,2000);
});
function doSomething(){
console.log("do something");
setTimeout(doSomething,2000);
}
this function is execute every 2 seconds like you want in your code
i hope i have help you
Ok, here is a pick what was wrong. I somehow had added parenthes there right side of the json, where is shouldnt be, thats how the whole block got stuck, i am appologising for taking anyones time. All these marks and syntaxes make one crazy..
Thank you anyway, this community is amazing

Best way to change messages from alert to labels

I used to display my validation as well as success/failure messages through alert pop-ups but now my requirement is to display the same using HTML label texts and make them disappear after a particular amount of time. I am currently using a timeout function:
if ($("#lblErrorMessage").text() != "") {
clrMsg = setTimeout(function(e) {
$("#lblErrorMessage").text("");
clearTimeout(clrMsg);
}, 5000);
}
This approach is very messy and there is no way to check whether the message is success (needs to be displayed for longer) or error/failure message (needs to be displayed for shorter period). Can anyone suggest a function which can be used throughout the page and also meet the requirements I want?
Thanks in advance
With an added class?
You don't show how you add the message in #lblErrorMessage...
But I suppose you can also add a class to it like "success" or "fail".
$("#lblErrorMessage").text("Some success messsage to user.").addClass("success");
removeMessage();
or
$("#lblErrorMessage").text("Some error messsage to user.").addClass("fail");
removeMessage();
Then, here is the new setTimeout function:
function removeMessage(){
if ($("#lblErrorMessage").text() != "") {
if $("#lblErrorMessage").hasClass("success"){
clrDelay = 5000;
}
else if $("#lblErrorMessage").hasClass("fail"){
clrDelay = 2500;
}
clrMsg = setTimeout(function(e) {
$("#lblErrorMessage").text("");
//clearTimeout(clrMsg); // No use for that.
$("#lblErrorMessage").removeClass("success fail"); // Remove classes for future messages.
}, clrDelay);
}
}

I need a new way to detect if there has been a change to an elements HTML

Right now im trying to find a way to detect when an elements HTML has changed.
I'm currently trying:
var a, b;
setInterval(function() {
a = $('#chat').text();
}, 150);
setInterval(function() {
b = $('#chat').text();
if (a !== b) {
alert("There has been a new message.");
}
}, 200);​
What I do is every 150 milliseconds I check for the HTML of #chat and then every 200 seconds I check the HTML again and then check if variable a does not equal to variable b them in the future I will so something with that but for right now I just alert something.
You can see it live here: http://jsfiddle.net/MT47W/
Obviously this way is not working and is not very accurate at all.
Is there a better/different to do/achieve this?
Thanks for any help, I've been trying to figure out how to do this a better for about a week now but I just can't find a fix for this and i'm hoping I posted this problem at the right place, and at the right time.
Use a var to store the element's current text then check against it in a setInverval and update the var to store the current text after checking:
var a = $('#chat').text();
setInterval(function() {
if (a !== $('#chat').text()) { //checks the stored text against the current
alert("There has been a new message."); //do your stuff
}
a = $('#chat').text(); //updates the global var to store the current text
}, 150); //define your interval time, every 0.15 seconds in this case
Fiddle
You may as well store the value in the .data() of the element to avoid using globals.
Example using .data():
$('#chat').data('curr_text', $('#chat').text());
setInterval(function() {
if ($('#chat').data('curr_text') !== $('#chat').text()) {
alert("There has been a new message.");
}
$('#chat').data('curr_text', $('#chat').text());
}, 150);
Fiddle
Another approach, to save client's memory, you can just store the number of child divs your #chat element has:
$('#chat').data('n_msgs', $('#chat').children().length);
setInterval(function() {
if ($('#chat').data('n_msgs') !== $('#chat').children().length) {
alert("There has been a new message.");
}
$('#chat').data('n_msgs', $('#chat').children().length);
}, 150);
Fiddle
EDIT: Here's my very final addition, with a DOM mutation event listener:
$('#chat').on('DOMNodeInserted', function() {
alert("There has been a new message.");
});
Fiddle (not tested in IE < 8)
Note: As noted in the comments, even though mutation events are still supported they're classed as deprecated by W3C due to the performance loss and some incompatibilities across different browsers, therefore it's suggested to use one of the solutions above and only use DOM Mutation events when there's no other way around.
Just checking the last chat would improve efficiency and also do what you want. The only way that it would not work is if the same person sends the same message twice - which most likely will not happen.
I hope this would work:
var lastMessage = $('#chat .body').last().text();
function checkMessages(){
var newLastMessage = $('#chat .body').last().text();
if(lastMessage !== newLastMessage && $('#chat .body').last().length > 0){
//message has changed
alert("There has been a new message.");
lastMessage = $('#chat .body').last().text();
}
setTimeout(function(){checkMessages();},1000);
}
checkMessages();
Js Fiddle
Use crc32 or md5 hashing to check whether data has changed. Just get the html content of the div that you want to check, hash it as a string with either crc32 or md5 and you'll get a string that will represent that content. Use a hidden timestamp etc to be sure that multiple messages by one user get a different hash. If you do this in a setInterval callback, you should be good.
Although it is not highly recommended, it is also possible to use Paul Irish's Duck punching method to tie into jQuery's append function - if you know for sure that the append function is how content is being added (demo):
(function($) {
// store original reference to the method
var _old = $.fn.append;
$.fn.append = function(arg) {
// append as usual
_old.apply(this, arguments);
// do your own checking here
// "this" is a jQuery object
if (this[0].id === "chat") {
alert('there is a new message!');
}
return this;
};
})(jQuery);
With this method, no timing loops are needed.

Trouble using array.some and general code hash up. Navigation function to correct div/section

I've made a general hash up of the following function. Basically linking this function to the onclick method of a button. The idea being that if the next page/div is visible to navigate there else navigate to the next one, and so on. If there are no further pages visible (from the current page) then alert the user. Just in case they carry on clicking.
Here is my code:
function showNext(id){
var currPage = id.match(/\d+/)-1;
var pages = [document.getElementById("page2"),document.getElementById("page3"),document.getElementById("page4")];
var next = ["page2marker","page3marker","page4marker"];
var valid = false;
for (var i=currPage; i<=pages.length; i++){
var Icansee = pages.some(function() { pages[i].style.display == "block"});
if(Icansee){
valid = true
}
if(valid){
return window.location.hash = next[i];
}
if(!valid){
alert("No other pages to navigate to");
}
}
}
I know that my use of the array some function is incorrect, along with plenty of other things. Just need a general shove in the right direction.
Edit: Just realised that array some is an ECMAScript 5 addition which isn't supported by the piece of software that I'm using. So I will need to find another way of solving this one. Any ideas?
There's a sample implementation of Array.prototype.some for browsers that don't support it natively at https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some

error with javascript globals and jquery call back functions

i'm trying to make an array of value's to be checked to see if that value has been added before.
if it has show an alert.
if it hasn't added it to the array and conduct a post ajax query to the server to retrieve a corresponding table row.
i'm mostly a novice when it comes to javascript and i'm finding it hard to debug because a fault in syntax breaks the entire script.
here is my code if someone see's an error could u tell me how to fix it.
also if you know a program to help with debugging java-script that would be really helpful.
I know that the jquery calls work fine because i added in the array check afterwards.
var selectedProductsArray = new array();
var selectedProductsCount = 0;
$(function() {
$('.selectProductID').live('click', function(event) {
var count = 0;
var found = false;
while(count < selectedProductsCount)
{
if(selectedProductsArray[count] == $(this).val())
{
found = true;
break;
}
count++;
}
if(found)
{
alert("you can only add one line for each product.");
}else{
selectedProductsArray[selectedProductsCount] = $(this).val();
selectedProductsCount++;
$.post("order/getitem", "ProductID="+$(this).val(), function(data){
$("#orderItems tbody").append(data);
selectedProductsCount++;
});
}
return false;
});
});
Firstly, there is no "array" class so I'm surprised that you even getting passed that; you want:
var selectedProductsArray = new Array();
or
var selectedProductsArray = [ ];
Also, you don't need to keep computing $(this).val() over and over again, you should just say:
var count = 0;
var found = false;
var value = $(this).val();
above the while loop and reference value instead of $(this).val() in the rest. You're also incrementing selectedProductsCount twice when I think you only want to do it once, this will leave empty/null entries in your selectedProductsArray and that might confuse things later on.
I can't eye-ball any other glaring errors but that new array() one should be a show stopper. Hard to say without a fully functioning example.
Does order/getitem get called? Does it send anything back?
For debugging and trying things out:
Firebug
jsfiddle

Categories

Resources