setting jquery auto-complete plugin to auto-submit - javascript

Two things I'm trying to adjust in my usage of JQuery autocomplete in PHP.
1. I would like that when I chose an option it will auto-submit the form (currently it requires two enters)
2. When I continue to write and no new options exist is still shows me the old options. I would rather it not suggest un-relevant options even if none exist.
Thanks
UPDATE:
I've resolved num. 2, for future readers the problem was I sent null instead of an empty json from the source url.
Regarding num. 1, I've done as suggested and now my JQuery js code looks like this:
$( "#searchid" ).autocomplete({
source: "/autocomplete_url.php?more=1",
});
$("#searchid").result(function (event, data, formatted)
{
alert("o"); // just to check if got here
$('#formid').submit();
});
However, The result function is never invoked (I've added a simple alert to verify that). Any idea why?

For 1.) you can simply submit the form through jquery from within the result(handler). Look at this - http://docs.jquery.com/Plugins/autocomplete if you look at the last code sample on the page, instead of redirecting, you can simply submit the form instead within the result call.
Regarding the 2.) point, well jquery autocompletes works just like that, perhaps you're doing something wrong or expecting something wrong, please give more information regarding the same.

Related

How to change an attribute of a javascript prototype object

html base
<html>
<head>
</head>
<body>
<input type="text" class="abc"/>
</body>
</html>
So I have my prototype object
function AnArray(){
this.anArray=[];
}
AnArray.prototype.getAnArray=function(val){
return this.anArray[val];
}
AnArray.prototype.setData=function(index,val){
this.anArray[index].data=val;
}
var objAnArray=new AnArray();
the object ends up looking like this
id: 1, pid: "questions-worth-asking", num: 1, data: null
and I'm trying to change an attribute in it like so
objAnArray.setData(0,$(".abc").eq(0).val());
When I've rune console.log messages using getAnArray() before and after the above line, it returns the same value as it has not been changed.
My question is how do you change attributes of a prototype object?
edit: This link led me down the right path http://www.gpickin.com/index.cfm/blog/websql-when-is-a-javascript-object-not-a-javascript-object
You're missing a lot of information from your post that makes it difficult to debug.
From my understanding the problem is that:
You want your jQuery object's value property to be stored in an array that you wrapped in an object.
You want to store this property with the setData function you wrote.
You want to retrieve that object by using the getAnArray function you wrote.
I don't think this is an issue with prototypes, but with the lack of information given to us, it could be any number of things. I wouldn't be surprised if you came back and said "Oh, it was something else completely."
I've made a fiddle that successfully sets and gets data from the anArray objects that you can use as an example.
Here are some problems you want to look at that will help you debug:
You don't set the anArray[index] object in this snippet. So if we are to take this at face value, the setData function should throw a ReferenceError.
You haven't told us if you're calling the setData function inside an event or right when the page loads. If it's the latter, then according to the html you posted at the top, you won't have any data in the input field yet. You need to call the setData function only when there's data in the field.
You might be calling the jQuery object outside of the $(document).ready(function(){ ... }) call so the value you're obtaining with $(".abc") call is undefined.
Give those a try and hopefully those work.
To make your questions easier to debug going forward:
Write all your experimental code in an isolated environment so that all the confidential content content doesn't have to be removed before posting.
Run your code and make sure it runs as expected.
Show us all of that code so that we know where all the data comes from and how each element interacts with the other elements. For example, we currently don't know how the anArray array is populated so I've had to make assumptions. We also don't know how id, pid, or "questions-worth-asking" comes from so there might be side effects from how those are loaded in.
Write your code using some sort of style guide to make it easier to read. This will also help improve debug time for you and will help prevent errors from silly mistakes that you might make.
Edit:
I know you're calling console.log before and after the setData method. Consider putting console.log inside the setData method as well.
AnArray.prototype.setData = function (index, val) {
console.log("Entering setData with: ", index, val, this.anArray[index]);
this.anArray[index].data = val;
console.log("Exiting setData with: ", this.anArray[index]);
};
It seems to me that the problem isn't in your javascript. You're saying that you ran a console.log before and after your setData call on objAnArray. Perhaps it has something to do with your HTML input element not being updated, or the data not coming through in time.
Like Keane said, we need more info about your set up and logic flow.

Check for correct answer (quiz) using PHP and AJAX

I have a picture quiz with a single input field for each image. I need a way to check if the value entered into the input field matches the correct answer and if it does, perform a few operations like add/remove a few CSS classes and increase the score count. And I need this to be done in real time using AJAX.
This is the pseudo-code for the functionality that I want...
if input value == correct answer {
some jQuery to add/remove a few classes
some PHP (I assume) to add 1 to the score count
} else {
some jQuery to add/remove a few classes
}
However, how do I get the value of the input field in real time? Do I still use PHP Post to get the value? What AJAX do I need to do this without a page refresh?
Any help would be greatly appreciated... I'm okay with PHP but very little experience with AJAX. Thank you.
yes this can be done with AJAX, and with jquery (which is not the same).
You can get input string with $("#input_id").val() , show a simple error message with alert("my message"), and use the onchange event. see also what is e.preventDefault() to make the form not submitable if all is not correct
If you want to check if datas are correct with a php request, that's also possible with $.ajax()
See jquery documentation on the web for further information about all theses functions
In case this is useful for anyone else, this is how I achieved my original goal. Contrary to what I first thought, this can all be done using JS and does not require PHP or AJAX to update in real time.
$('input').keyup(function () {
if (($(this).val() == 'test') {
//Stuff
} else {
//Other Stuff
};
});
The .keyup() function is what allows this to work in real-time, as it is called whenever a key is hit on your keyboard.
Then within this, the .val() function is what is used to check the actual user-entered value of the input field. In this case, if this value equals 'test', then it performs whatever you place in the if statement.
Hope that helps if anyone has stumbled across this question hoping for this answer!

Object has no method 'charAt' in jQuery plugin

I am attempting to use the autoNumeric jQuery plug-in which helps with the conversion of various currencies in jQuery.
The plug-in itself works when I use it in a jsFiddle example.
$(function () {
$('.money').autoNumeric('init', {
aSign: '$',
vMin: '-999999999.99',
nBracket: '(,)'
});
});
However, as soon as I integrate it into a big, legacy project, I start receiving the above error on line 194. I know why I'm getting the error - a string is not being passed into the negativeBracket function (negativeBracket(s, nBracket, oEvent) is the signature). Instead, it seems to be a jQuery object - e.fn.init1. I'm confused on how this might be happening. I realize the community may not be able to give a direct answer, but I would love (and will accept as an answer) being pointed in the right direction as nothing has jumped out at me so far.
Update
So, have some additional info that may be of help. It still has me stumped how it's happening (unfortunately, the answers below didn't help to provide any additional insight). When I link in autoNumeric, I key it off of any text field with the class money. It does work as I am typing in the box. I can see see formatting. However, when I tab into a new box, the box I just finished typing in clears itself completely after hitting line 152 in autoNumeric with the same exact error.
#Carlos487 was correct in his answer when he said I have an object that is not a string. I instead have an object that, I believe, is a function. Here's what I'm seeing in Chrome debugger tools:
e.fn.init[1]
> 0: input#price.money required
> context: input#price.money required
length: 1
selector: ""
> __proto__: Object[0]
The "arrowed" items can be further expanded out. I don't know if this provides any more clues, but it's at least something a bit different.
The errors like
no method XXXXX in Object
are produced because you are trying to call obj.XXXX() and obj is not of the desired type, in your particular case a string.
Have you tried in another browser because older or IE can be a little troublesome. I would recomend using chrome developer tools with your legacy app to see if anything else is conflicting or producing the error
I will bet money that you are using a second library which is interfering with jQuery. It has probably overridden $ with its own function.
Try using jQuery instead of $:
jQuery(function () {
jQuery('.money').autoNumeric('init', {
aSign: '$',
vMin: '-999999999.99',
nBracket: '(,)'
});
});
It turns out that the issue was a myriad of issue compounding into the error I saw. A couple things that was happening:
The validator plug-in was wrapping the jQuery object in its own structure (hence the charAt issue).
Once I fixed that, I also learned that some homegrown code was also wiping and rewriting data into the field to provide formatting (which is what autoNumeric is also doing), so autoNumeric would bomb out because it would get a null value and attempt to format it.
There was some other random craziness that also needed cleaned up. So...issue resolved! Still more to work on, but at least this hurdle is past. Thanks all for your help.

how to use jquery or javascript to get the selected VALUE from telerik radcombobox? val() not working

I have a listview that has a nested listview which contain radcomboboxes in the itemtemplate. As such, the IDs (as far as I know) are useless to me.
For example, if I have 30 items, each one of those items is going to generate a new combobox so the names are going to be generated by asp. What I need is to be able to grab the selected value from whichever combobox is being worked by the user. I'm currently using jQuery and some absurd parent().parent().children() type nonsense in order to find the correct combobox in relation to the submit button.
When submit button is clicked, I need it to find the selected value of the it's respective combobox so that I can send that to the post submission handler. The problem is that the .val() jQuery method is not working. When I use that with something like:
$(this).parent().parent().children().children(".statusCbo").val();
I end up getting the text value, not the selected value. I triple checked to make sure that I had the fields bound correctly in the aspx file;
DataTextField = '<%#Eval("name") %>' DataValueField = '<%#Eval("id") %>'
But as I said, I'm ending up with the DataTextField value of the selected item. The best explanation I could get was that it had something to do with how the control is requesting the content (via ajax).
So at any rate, could anyone offer some suggestions on how to accurately get the selected value from the combobox?
UPDATE:
I was able to gain reference to the object through a different means:
$(".submitTag").click(
function () {
var topLevel = $(this).closest(".CommentTopLevel");
var status = topLevel.find(".StatusTag").get_value();
//stub to test value
alert(status);
return false;
});
from here, if use status.val(), it will give me the text instead of the value (same issue as before). The documentation implies that I should use status.get_value(); but this is blowing up saying that the method is not supported from the object. Any ideas?
UPDATE:
nevermind, I found that it is a jquery object being returned, so the method isn't included. Continuing to dig.
SOLUTION:
There was just an extra step i needed to do to use traditional methods. I don't know what it took so long for it to click with me:
$(".submitTag").click(
function(){
var topLevel = $(this).closest(".CommentTopLevelTag"); //gets the parent container
var comboBoxID = topLevel.find(".StatusTag").attr("ID"); //gets the clientID of the jQuery object
var comboBoxRef = $find(comboBoxID); //finds the control by id and brings back a non-jQuery object (useable)
var comboBoxSelectedValue = comboBoxRef.get_value(); //uses the Telerik method to get the selected value
});
Its been a little while since I've dealt with Telerik controls, but what you're doing is bypassing the apis Telerik has made for you to use, and that strikes me as a very bad thing. The next release of Telerik Controls could easily break your code.
Look, it shouldn't be that hard to pass the client id from the listview. There's several methods I'd tackle but I'll let you figure that on your own for now. Once you DO have the ClientID for the control, follow the example on telerik's site:
http://demos.telerik.com/aspnet-ajax/combobox/examples/programming/addremovedisableitemsclientside/defaultcs.aspx
Once you have that id do some
var combo = $find(someVarReferencingTheId);
Now you have a reference to the combobox in its clientside form. Now find some function that gets what you want from here:
http://www.telerik.com/help/aspnet-ajax/combobox-client-side-radcombobox.html
...
PROFIT!
EDIT: that first link to demos.telerik.com isn't really even needed, I just showed that because that's what I used to get that line of code (I could never remember if it's $get or $find I needed to use, unless I was doing a lot of Telerik clientside stuff at the time.).
EDIT 2: $get and $find are ASP.NET constructs, not Telerik's.

select value not changing after ajax call

I have written a piece of code to generate a chart by values generated by an ajax call.
The problem is, the select (years) is not changing its value after the call is done loading. The weird thing is, i can see its value changing (if i alert its current value) but it simply won't change.
The code:
http://pastebin.com/RNfLmdWy
The $.load_x function is a custom loader but it behaves the same as a regular $.getJson call.
Found it! This part is responsible:
var option = $(this).attr('id').split('option_');
$('#'+option[1]).val(String($cur_val));
setTimeout(function(){$('#'+option[1]).val(String($cur_val))}, 1000);
I don't know what were you trying to do here, but basically, the option variable becomes a array ["", "years"], and in the next step you are setting $("#"+option[1]) value to $cur_val variable which is anything found in the #option_years input.
Soooo to wrap it up. To get rid of the "my select is not changing its value" issue in this case just get rid of those lines or at least let me know what you wanted to do there :)
EDIT: Here's the example that works for me: http://pastebin.com/sFRT3GJa (tested on FF and Chrome). As you can see it the source I use jQuery 1.6.1, jQuery UI 1.8.16 and jqPlot 1.0.0b2_r792. Other than that I've moved the callback function of $.load_x and named it handleJSON. Then I passed the JSON data you've pasted in your question to mock the successfull response of the $.load_x function.
Before you make get_port_graph call, give some time for select box to change the dropdown since its heavy call. It will work.
function year_chart(year)
{
settTimeout(function(){
var d = new Date();
get_port_graph("Uitporteringen "+year,d.getMonth(), year,'outport', 'chart1', 'bar');
}, 100);
}

Categories

Resources