JQuery - Using Selector :contains - Weird Results - javascript

Story so far.....
I want to learn JQuery, and im also building an MVC ASP.NET Apps which requires a "search as you type" search function - perfect to learn JQuery as well! So far (with the help of stackoverflowers ) I have managed to get the AJAX/JSON bit. Now I want to evaluate each key press and validate it against the JSON Array which was created as an unordered list. What im trying to achieve is to only show the account numbers in the list that contain what is inputted. So, my reasoning was to check against keydown event and validate it. For the time being im just changing the color of the account numbers to red of hiding them, just to prove my logic works.
My JQuery Code so far....
http://jsfiddle.net/garfbradaz/JYdTU/28/
...and for convenience....
$(document).ready(function() {
var $input = $("#livesearchinput"),
filled = false;
$.ajaxSetup({
cache: false
});
$input.keydown(function(key) {
if (!filled) {
filled = true;
$.getJSON("/gh/get/response.json//garfbradaz/MvcLiveSearch/tree/master/JSFiddleAjaxReponses/", function(JSONData) {
var $ul =
$('<ul>').attr({
id: "live-list"
}).appendTo('div#livesearchesults');
$.each(JSONData, function(i, item) {
$.each(item, function(j, val) {
$('<li>').attr({
id: "live-" + val
}).append(val).appendTo($ul);
});
});
});
}
var n = $("li:contains('" + this.value + "')").length;
if (n === 0) {
$("li").removeClass("color-change");
console.log("1. value of n equals " + n + " : " + this.value);
}
else {
$("li:contains('" + this.value + "')").addClass("color-change");
console.log("2. value of n equals " + n + " : " + this.value);
}
});
});​
My Issue.....
My issue is that when i evaluate the key press using the following this.value is empty on the first keydown event and then out of step throughout
var n = $("li:contains('" + this.value + "')").length
Example:
If i input 100004, let me show you my console.log results from Chromefor inputting that result:
The results seem to always be one step behind. Is the keydown event the best one to use or am i missing something.
As always - thanks guys and happy coding.

because this.value on the keydown event does not contain the keystoke which triggered the event. Use keyup instead.
You can access the keystoke via the event object which is available in the function... but the value of the input will not contain it until the key is released.
http://jsfiddle.net/rlemon/TGBUe/1/ in this example you can open your console... and type a character in the input... you will notice the keydown this.value is blank for the first char whereas the keyup contains it.

Maybe the check fires before the AJAX part has completed.
Mind that AJAX is asynchronous and the code continues its flow regardless of the AJAX request, that is completed asynchronously.
Try to move the logic inside function(JSONData).

Related

trouble looping through div ids with newest jquery build

I upgraded my website to the latest jquery build (2.1.4), and I'm trying to debug the many errors that it is throwing.
However, I keep getting the error "unrecognized expression: [id=]" on the following script:
setTimeout(function() {
$(".cab_librovisitas, .cuerpo_librovisitas, .cuerpo_librovisitas_user").each(function () {
var ids = $('[id=' + this.id + ']');
if (ids.length > 1 && ids[0] == this) {
$(ids[1]).remove();
}
});
and I can't wrap my head around it.
Any help will be appreciated.
At first I was going to write a comment advising to put support requests directly on jQuery, but then I saw the code and thought it merits some discussion.
First of all, the id attribute is a special attribute in HTML. It is supposed to hold a unique value throughout the whole document (in other words, no two elements can have the same id), so I'm finding it strange that code would ever work.
Secondly, I don't see any reason why you would use jQuery to select an element by id when a simple document.getElementById() would have done the trick. Let's say you wanted to have a jQuery element. Fine, even in that case, your jQuery selector is far from perfect. A better alternative would be $('#' + this.id);. That said, the best alternative would be a simple $(this)... no need to worry about the id at all.
Perhaps I misunderstand the new jquery build, but normally you would declare your id within the jquery wrapper with
$('#myId')
Your code is assigning
var ids = $('[id=' + this.id + ']');
which translates to this
ids = $('[id=whateverThisIdIs]');
Can you try this instead?
var ids = $('#' + this.id); // assuming this.id does not contain '#'.
Final
setTimeout(function() {
$(".cab_librovisitas, .cuerpo_librovisitas, .cuerpo_librovisitas_user").each(function () {
var ids = $('#' + this.id);
// or this if you have the '#'
// var ids = $(this.id);
if (ids.length > 1 && ids[0] == this) {
$(ids[1]).remove();
}
});
One of the comments mentions
You script implies that there are multiple ids on the page: not good.
This is true if you are using the same id, which I do not think you are.
Somewhere in your HTML is an element with one of the classes .cab_librovisitas, .cuerpo_librovisitas, .cuerpo_librovisitas_user, that either has no id attribute or has an empty one.
Change the line
var ids = $('[id=' + this.id + ']');
to
var ids = $('#' + this.id);
and the error will go away.
Or do a check for an empty id:
setTimeout(function() {
$(".cab_librovisitas, .cuerpo_librovisitas, .cuerpo_librovisitas_user").each(function () {
if (!this.id) return;
var ids = $('[id=' + this.id + ']');
if (ids.length > 1 && ids[0] == this) {
$(ids[1]).remove();
}
});
}
...I can't help but wonder what the purpose of the code snippet is though... trying to remove duplicated elements...? Why are they there in the first place?

JavaScript "if" statement wont run

(Using Javascript)
If I enter text in the textbox or not, the alert will not come up.
I know this is a simple fix but I can not figure it out!
(This is for learning purposes.)
Workout Log Test
<script type="text/javascript">
function myResults() {
myExercise();
myWeight();
mySets();
myReps();
myFunction();
}
function myExercise() {
var txtExercise = document.getElementById("txtExercise");
var txtOutput = document.getElementById("txtOutput1");
var name = txtExercise.value;
txtOutput1.value = "You destroyed, " + name + "!"
if (txtExercise.length === 0) {
alert ('Do you even lift?');
return;
First off, you're checking the "length" property of the element rather than the value of the input.
Second of all, you're checking against an integer value. If you were to simply read the value of the element, you're going to get text.
I'm guessing, what you want is something like:
var exercise = parseInt(txtExercise.value, 10);
if(exercise === 0) {
alert('Do you even lift?');
return;
}
But that's assuming txtExercise is an input element. Without seeing your markup, it's hard to be sure that any given answer will work.
Here you go, all fixed. You need an event handler, and this is a better if/else use case.
http://codepen.io/davidwickman/pen/vOKjqV
// Check the .value.length instead of just the .length
if (txtExercise.value.length === 0) {
alert('Bro, do you even lift?');
} else {
txtOutput1.value = "You destroyed, " + name + "!";
}
Assuming you have closed the function and if statement properly, you are missing a semi colon just before the if statement.
txtOutput1.value = "You destroyed, " + name + "!"; <---- here

Passing javascript function in JSON

I am trying to implement jQCloud word cloud with click event handler. It requires me to pass a javascript function in JSON.
In C#, I have made the dynamic JSON text
foreach (var r in result)
{
sbChart.Append("{\"text\": \"" + r.Key + "\", \"weight\": " + r.Count().ToString() + ", ");
sbChart.Append("\"handlers\": { \"click\": \"function() { alert('You clicked " + r.Key + "');}\"}}, ");
}
if (sbChart.Length != 0)
{
returnString = "[" + sbChart.ToString().Substring(0, sbChart.Length - 2) + "]";
}
I return this through web method to javascript where my code is
var words = JSON.parse(strJSON);
$('#div').jQCloud(words);
The JSON generated is
[
{"text": "the", "weight": 111, "handlers": { "click": "function() { alert('You clicked the');}"}},
{"text": "in", "weight": 66, "handlers": { "click": "function() { alert('You clicked in');}"}}
]
However, since my function is a string, it does not gets execute as a object. And if I remove the double quotes before and after the function statement, it gives me Invalid Character error during parse.
Please can anyone help me as to how can I make this alert work?
If you absolutely have to pass a function to your page that way (see the "but" below), you could use eval for it, since you're the one providing the text you'll be evaling it doesn't have the security issue (and the speed issue is a non-issue and has been for years). I'm not sure what you want to do with the function, but for instance:
$(".foo").on("click", eval(words[0].handlers.click));
...would eval the function and assign the result as a click handler on the elements matching the .foo selector.
But, there's almost certainly a better way to structure things. Instead of passing back functions in the JSON, you might have those functions in your JavaScript already in some kind of map:
var clickHandlers = {
"the": function() { alert("You clicked the"); },
"in": function() { alert("You clicked the"); }
};
...and then just given the key ("the", "in") in your JSON.
Or, given that they're the same thing other than what was clicked, figure out what was clicked ("the" or "in") from the element that was clicked.
Or any of a dozen other things, but what they have in common is that the functions are defined in your JavaScript code, not sent back via JSON, and then you link up those functions via information in the JSON rather than actual functions in the JSON.
Functions are not meant to be passed as JSON, and it's a pretty big security issue to execute arbitrary logic passed by a data call. That being said, use eval to solve this.
Something like
var action = eval(response[0].handlers.click); // evaluates the string as javascript, and returns the value, in this case a function.
action();
Thanks a lot all for your suggestions above. But I ended up using the answer from how to provide a click handler in JQCloud
I modified it a bit as per my requirement and it worked
var tag_list = new Array();
var obj = GetCustomJsonObj(strJSON);
for (var i = 0; i < obj.length; i++) {
tag_list.push({
text: obj[i].text,
weight: obj[i].weight,
//link: obj[i].link,
handlers: {
click: function () {
var zz = obj[i];
return function () {
alert("you have clicked " + zz.text);
}
}()
}
});
}

even.data is not change

here is my own practice demo, it works well as i expect. but when i use line 8 ( comment on my demo code ) instead of line 7 ,the input text values all change to 0 which is different than the result of demo i giving out.
i look at the jquery website it only gives me this
Description: An optional object of data passed to an event method when the current executing handler is bound.
i think the result of using line 8 or line 7 should be the same because of i is assigned to count object, but it is not. Could someone explain me about this question. by the way, if someone could refactor my code will be even more nicer THANKS!!
here is my code
var i = 0;
$("#aa").on("click", {
count : i
},
function(event) {
var div = $('<div/>');
var input = $('<input />').attr("value", event.data.count);
event.data.count++;
//i++;
var bt = $('<input />').attr({
type : "button",
value : "remove",
});
div.append(input);
div.append(bt);
var index = $("div").length;
if (index == 0) {
$("#aa").after(div);
} else {
$("div").last().after(div);
}
bt.on('click', function(event) {
$(this).parent().remove();
});
});
when the current executing handler is bound.
this is important thing in the section. So, the object will be created only once, during the time of binding the function with the click event. So, changing i will not change the value of event.data.
When you do
event.data.count++;
you are actually mutating the object and the state of the object will be retained. That is why it works.

How can I make this code work better?

I recently asked a question about manipulating the html select box with jQuery and have gotten this really short and sweet code as an answer.
$("#myselect").change(function (event) {
var o = $("#myselect option:selected"),
v=o.text(),
old = $("#myselect option:contains('name')"),
oldv = old.html();
oldv && old.html( oldv.replace('name: ', '') );
o.text('name: ' + v);
});
I have one problem. This code doesn't work on multiple categories and I can't seem to wrap my mind around how it can be done. So, I made the obvious changes to it:
$("select").change(function (event) {
var foo = $("select option:selected"),
bar = foo.text(),
cat = foo.parent().attr("label"),
old = $("select option:contains('" + cat + "')"),
oldbar = old.html();
oldbar && old.html( oldbar.replace(cat + ': ', '') );
foo.text(cat + ': ' + bar);
});
This now works on multiple optgroups/categories but has led to another bug. A more problematic one, at that.
It happens when you click from one category to another. Check it out on jsFiddle.
The problem with the last snippet is it uses the name of the current category to locate the last selected label to flip back. Instead, how about searching for the ":", (this won't work if you have ":" in one of your options), and then replacing that part of the string.
change line 5 to:
, old = $("select option:contains(':')")
and line 8 to:
oldbar && old.html(oldbar.replace(oldbar.substr(0, oldbar.indexOf(':') + 2),''));
Let me know if that's not working for you!
Edit: as an afterthought, you might consider adding this line
$('select').change();
As well, somewhere in the $(document).ready() event, so that when the page first renders the default value gets the prefix like (I think) you want.
I've renamed the variables since it is really a good habit to get into naming your variables and functions with meaningful names so you can juggle in your memory what is going on.
$("select").change(function () {
// We immediately invoke this function we are in which itself returns a function;
// This lets us keep lastCat private (hidden) from the rest of our script,
// while still giving us access to it below (where we need it to remember the
// last category).
var lastCat;
return function (event) {
var selected = $("select option:selected"),
selectedText = selected.text(),
cat = selected.parent().attr("label");
if (lastCat) { // This won't exist the first time we run this
oldSelection = $("select option:contains('" + lastCat + ":')");
oldHTML = oldSelection.html();
oldHTML && oldSelection.html(oldHTML.replace(lastCat + ': ', ''));
}
selected.text(cat + ': ' + selectedText);
lastCat = cat; // Remember it for next time
};
}()); // Be sure to invoke our outer function (the "closure") immediately,
// so it will produce an event function to give to the change handler,
// which still has access to the variable lastCat inside
Here's a shot in the dark. At first blush, it appears you're not saving the previous selection and you're using the selection which triggered the event in your oldbar && old.html( oldbar.replace(cat + ': ', '') ); line. You need to save the category of the previous selection in a separate var.

Categories

Resources