I ran into a problem with an object which I'm trying to modify. The object has a certain amount of keys in the format key_yyyy-mm-dd. When certain inputfields lose focus, I trigger a function to modify the object. This function is as follows:
function updateHotelBooking()
{
$(".no_hotel").each(function(i) {
var day = $(this).attr('name').match(/\[(.*?)\]/)[1];
hotelBooking["key_" + day] = parseInt($(this).val());
});
}
.no_hotel are the textboxes that trigger the function, and they also provide a value which I want to put in my object.
Now, say I put 3 in my first text box, a console.log will return the following object:
Object
key_2011-08-21: 3
key_2011-08-22: 0
key_2011-08-23: 0
key_2011-08-24: 0
key_2011-08-25: 0
However, the next time I put something in the textbox (or another textbox that should trigger the function), it DOES trigger, however the object returned remains the same. So instead of changing the first number to, say, 5, it will just return 3 again.
I have no idea why. My code seems pretty straightforward, and a console.log of day and $(this).val() returns the right values. It's just my object that doesnt get updated.
Does anyone have any idea? Thanks a lot!
EDIT:
hotelBooking is initialized right after $(document).ready():
var hotelBooking = {};
The method that calls updateHotelBooking is the following:
$(".roomrequest").blur(function()
{
updateHotelBooking();
});
EDIT2: JSFiddle: http://jsfiddle.net/pBYeD/2/
it has to do with something with the console rather than your code, if you change the logging code to this, you will see that you have the correct values:
function updateHotelBooking()
{
$(".no_hotel").each(function(i) {
var day = $(this).attr('name').match(/\[(.*?)\]/)[1];
hotelBooking["key_" + day] = parseInt($(this).val());
**logObject(hotelBooking);**
});
}
function logObject(hotelBooking){
for(var i in hotelBooking){
console.log(i+": "+hotelBooking[i]);
}
console.log("------");
}
Are you sure the problem does not come from the debugger output?
As far as i can see in my chrome output, if i let the fiddle as is, the object doesn't appear to change in the console (just the number on the left takes a +3). However if I add something like console.log(hotelBooking["key_" + day]); just before or after, it's shown as changing.
Related
Here is my Javascript code.
$("#changetemp").click(function () {
var temp = $("#temperature").html;
var final_letter = temp[temp.length-1];
$("#temperature").html(function ()
{if (final_letter == "F") {return celsius;}
else {return fahrenheit;}});});
});}});});
It is supposed to toggle the temperature between celsius and fahrenheit but does a big fat nothing. I've googled and changed a few things (e.g. gone between val, html and text, and tried charAt but I can't get it to do anything, let alone the right thing. Any suggestions would be very welcome.
Edit: "#changetemp" is the button you click to toggle between temperature (ideally).
"#temperature" is where the temperature displays (and it does, but then won't change).
Also tried:
console.log(final_letter); (which gave the correct letter in the console)
console.log(celsius); (which reports as 'undefined') as does console.log(fahrenheit);
These two are defined earlier via a JSON
$.getJSON( url, function(location){ var celsius =
$("#temperature").html(Math.round(location.main.temp - 273) + "°C");});
and I tried to make them be global variables by putting
var celsius;
var fahrenheit;
after the beginning of the first function (which surrounds everything else) but I'm guessing that didn't work.
More:
Googling suggests that variables cannot begin with a number. Is this what is stopping me here?
1. I've managed to show the temperature though, just not change it.
2. How do you get round that? I tried changing the code so that 'celsius' would give 'Temperature: 10C' rather than '10C' but that didn't solve it.
i assume the error is in the line var temp = $("#temperature").html;
Does it help if you change it to var temp = $("#temperature").html();?
html is a jQuery function, so you need to call it with the parantheses. Otherwise temp will not contain the content of the #temp element, but rather a reference to the html method. Therefore you don't get the last letter of the content.
This has me stumped, and should be pretty simple.
I have an input in my html:
<input type="text" id="fafsaNbrFam" name="fafsaNbrFam" value="<%=nbrFam%>" class="hidden" />
System.out.println(nbrFam); // Works, gives me "6"
Then my js code:
$("#submit").click(function(e) {
var numEntries = 0;
var fafsaNbr = 0;
$("input[name^='name_']").each(function() {
if (this.value) {
numEntries++;
}
});
// EVERYTHING ABOVE HERE WORKS
fafsaNbr = $("input[name=fafsaNbrFam]").val();
alert(fafsaNbr + "X");
// WHERE THE 6 is I want to put the variable fafsaNbr, just hardcoded for now.
if (6 > numEntries && !confirm("The number of members you listed in your household is less than the number you indicated on your FAFSA. Please confirm or correct your household size. ")) {
e.preventDefault();
}
});
On my alert to test this, I get "undefinedX", so basically my jquery to get the value is coming up undefined.
EDIT: So it turns out my code wasn't the problem, but the placement of my input. Even though the original input placement was being processed, once I changed it, it all worked properly. Needless to say, I am still stumped.
You are missing the quotes around the name value. Try:
fafsaNbr = $("input[name='fafsaNbrFam']").val();
Your code is working fine,
I just added your code to jsFiddle and it works
Live EXAMPLE
Could you please make sure, the java scriplet is loading inside the value tag properly or not by checking the view source in browser?
Try to parse the value of the input like this:
fafsaNbr = parseInt($("input[name=fafsaNbrFam]").val());
Or Check whether the $("input[name=fafsaNbrFam]") is undefined or not.
I've got two events: an onFocus (saveOld) and an OnChange (showPoints). When a user focuses in the drop down I use the jquery.data function to save the old value of the drop down. When the user changes the value of the drop down I check to see if the old value was larger then then the current value. If so, I adjust the total accordingly. But this only works when I alert the old value after getting it from the .data function in my onChange. Without the alert nothing happens.
function showPoints(pointCategory, ddlAmount, name){
old = jQuery.data(document.body,name);
alert(old);
var Points = parseInt($('p#points').html());
if(old > ddlAmount){
diff = old - ddlAmount;
currentPoints = Points + (diff * pointCategory);
}else{
currentPoints = Points - (ddlAmount * pointCategory);
}
$('p#points').html(currentPoints);
}//showPoints
function saveOld(oldAmount, name){
$(document.body).data(name,oldAmount);
}
Without the alert in showPoints() this does not work correctly. What is going wrong?
EDIT: Note that I have already tried a this.delay(1000) where the alert should be. Still did not work.
Try changing onfocus to onclick and also save your current value to .data in the end of showPoints like so:
$('p#points').html(currentPoints);
$(document.body).data(name,currentPoints);
I would use local variables inside showPoints function.
When you Alert you lose focus from element. So its a changed scenario for the alert() case.
So I would say you Save the value onBlur (called when u leave the control.)
delay(1000) will not help as it only adds processing time and not give more time for the function to process. I would go with x3ro's solution and check how the function is called.
i plan to show some images on the page and when the user press up button some related new images will be shown. I have been achieving that by changing the "src" attribute already existing image html tag.
i have json data like [["a","b"],["c","d"]] which gives the name of images like a.jpg, b.jpeg etc.
Here is the problem i can not pass the array value to jquery click object. my javascript functions as below:
var a; // a global variable holding the json array [["a","b"],["c","d"]]
function rileri(){ //img next
var ix=parseInt($("#up").attr('rel'));
ix=(ix+1)%a.length;
for(var i=0;i<2;i+=1){
$("#k"+i).attr("src","img/m/t/"+a[ix][i]+".jpg");
$("#k"+i).click(function() { rgetir(a[ix][i]);}); //problem is here!!
}
$("#up").attr('rel',ix); // i keep index data of appearing img on "rel"
}
function rgetir(n){ //img down ajax
$("#brc").load("data/rgetir.php", {'name':n});
}
I wonder how can i bind click event and if there is any better solutions ?
html is like that (no "src" at start, is it ok ?):
<img id="k0"/><img id="k1"/>
<input id="up" rel="0" type="button" onclick="rileri()" value="Next">
Yeap the main problem is passing the multidimensional array value to a function :(
The problem has nothing to do with "multidimensional arrays." It is that you are using i inside the assigned click value, and i changes with every iteration of the loop. Each assigned click value holds a reference to i, so when rileri is finished each points to the same value. You need to break the reference, usually done by passing i to a function and binding the click in there.
There are many flavors of using a function to break a reference, but since you're using jQuery and iterating an array, we'll use $.each:
(what follows is untested but should serve as an example)
function rileri(){
var ix=parseInt($("#up").attr('rel'),10);
ix=(ix+1)%a.length;
$.each(a[ix], function (i) {
var img_name = this;
$("#k"+i)
.attr("src","img/m/t/"+img_name+".jpg")
.click(function () {
rgetir(img_name);
});
if (i >= 2)
{
return false;
}
});
$("#up").attr('rel',ix);
}
Here is a simple fiddle that shows your problem
http://jsfiddle.net/MHJx6/
The problem is your ix and i variables are closures, so at the time the event runs they have the wrong values as you can see in this example.
I tried to write some code that will do what I think you are trying to do below. It would be easier if I knew what you were trying to do (use case). Maybe this is what you want?
var a; // a global variable holding the json array [["a","b"],["c","d"]]
function rileri(){ //img next
$("#k0").click(function() { handleClick(0); });
$("#k1").click(function() { handleClick(1); });
}
function handleClick(index) {
var ix=parseInt($("#up").attr('rel'));
ix=(ix+1)%a.length;
$("#k"+index).attr("src","img/m/t/"+a[ix][index]+".jpg");
$("#up").attr('rel',ix);
}
i am developing an autocomplete feature.but i am facing one problem there...
when i click on the suggestion box one of the results will not enter into the suggest html box...
function handleOnMouseOver(oTr)
{
deselectAll();
oTr.className ="highlightrow";
position = oTr.id.substring(2, oTr.id.length);
updateKeywordValue(position);
}
can you plz tell the solution
thanks
function updateKeywordValue(oTr)
{
var oKeyword = document.getElementById("keyword");
var strKeyword="";
var crtLink = document.getElementById("a" +oTr.id.substring(2,oTr.id.length)).toString();
crtLink = crtLink.replace("-", "_");
crtLink = crtLink.substring(0, crtLink.length);
oKeyword.value=unescape(crtLink.substring(googleurl.length, crtLink.length));
strKeyword=oKeyword.value.toString();
if (oTr.id.substring(2,oTr.id.length)==0)
{
oKeyword.value=strKeyword.substring(3,strKeyword.length);
}
selectedKeyword=oKeyword.value;
}
you should get rid of the second parameter in the substring() method. Since you just want the remainder of the string, I'm guessing, that is the default if you don't set a second value.
position = oTr.id.substring(2);
My guess is that you are getting the value of the keyword from the id, and pushing that into the input box, right? If that's the case, we'll need to see more of your code. Specifically, I'd like to see the updateKeywordValue function and I'd also like to know if the text that they are hovering over is the text you are trying to send the input box. If so, you could probably simplify the whole thing and go with something like:
function handleOnMouseOver(oTr)
{
deselectAll();
oTr.className ="highlightrow";
keywordbox.value = oTr.innerHTML;
}
But this is based on the assumption that the only data inside the hovered row is the text, and no other html. And I had to make up a name for your input box.
But if this way off, this is because we need more information to see the real problem.