Avatar of tuchfeld
tuchfeld
 asked on

Activate JQuery Autocomplete when a checkbox is clicked

Hello,
I use JQuery Autocomplete,
Now I'd like that if the user click a Checkbox such as SearchIn_Book1 or SearchIn_Book2
See attached code.
I'd like to reactivatethe the JQuery Autocomplete (with the same existing input string (notice that the checkbox value is passed as parameter).
Thanks, Aryeh.
<SCRIPT type="text/javascript">
$(function() {
	$("#book_words").autocomplete("./Book_Search.aspx", {
		scroll: true,
		matchSubset: false,
		parse: function(data) {
			var parsed = [];
			var rows = eval(data);
			for (var i=0; i < rows.length; i++) {
				var row = $.trim(rows[i]);
				if (row) {
					parsed[parsed.length] = {
						data: rows[i],
						result: row
					};
				}
			}
			return parsed;
		},
		extraParams: {
			search_in: function() { var res = ""; if 

(document.getElementById("SearchIn_Book1").checked) res = "1"; if 

(document.getElementById("SearchIn_Book2").checked) res += "2"; return res; }
		},
		formatItem: function(row, i, n) {
			return row;
		}
	});
});
</SCRIPT>

Open in new window

JavaScriptAJAX

Avatar of undefined
Last Comment
Michel Plungjan

8/22/2022 - Mon
Michel Plungjan

Not sure what you are asking

Perhaps this?
extraParams: { 
  search_in: $("#SearchIn_Book1").is(':checked')?1:2
}

Open in new window

tuchfeld

ASKER
See the html part attached.
research_jquery() function should be writen.
Hope it is understood now.
Thanks, Aryeh.
<FORM method="get">
        Search in Books:
	<INPUT id="book_words" name="book_words" type="text" />
	<INPUT language="javascript" id="SearchIn_Book1" type="checkbox" value="on" onclick="research_jquery();" />Book_1
      <INPUT language="javascript" id="SearchIn_Book2" type="checkbox" value="on" onclick="research_jquery();" />Book_2
    </FORM>

Open in new window

Michel Plungjan

none of that makes sense.

the language attribute is incorrect syntax

the onclick does not need to do anything

Do you want to search EITHER book1 or book2?
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
tuchfeld

ASKER
The idea is that once a checkbox is checked or unchecked the search result changes!
therefore the autocomplete needs to be reactivated. without the need to focus on book_words input.
Michel Plungjan

Ah..

that is not autocomplete. that is a new ajax.

function research_jquery(rad) {
  var url = "./Book_Search.aspx?"+rad.name+"="+rad.value+"&book_words="+escape($("#book_words").val());
  $("#results").load(url);
}

<INPUT id="SearchIn_Book1" name="search_in" type="radio" value="1" onclick="research_jquery(this);" />Book_1
<INPUT id="SearchIn_Book2" name="search_in" type="radio" value="2" onclick="research_jquery(this);" />Book_2
tuchfeld

ASKER
I have tested your code, but it does not operate as I expect,
i.e. when I change the checkbox I expect to see a different autocomplete list,
but I see no autocomplete list at all
shouldn't the .autocomplete be involved - use the existing code and just reactivate the process..?
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Michel Plungjan

No. My code was designed to call the search and present the search results using the same keyword already in the input field. It is likely not possible to execute the auto complete without a rewrite of the actual plugin code since clicking the radio will blur the field and interrupt the auto complete. I suggest two fields instead
Michel Plungjan

I found the documentation: http://docs.jquery.com/Plugins/Autocomplete/setOptions#options

Try this

function research_jquery(rad) {
  $("#book_words").setOptions({extraParams: { "search_in":rad.value}});
  $("#book_words").search();
}
tuchfeld

ASKER
Yes, maybe .search should be called...
But I've tested your code and it still doesn't work for me
i.e. the autocomplete search list is not reactivated when the checkbox is clicked.
hmm.. notice the the focus is not on book_words element maybe this is a problem..
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
Michel Plungjan

Perhaps.
I cannot help you further without a URL to test
tuchfeld

ASKER
Can I post Html and ASP.Net (VB) files?
Michel Plungjan

No. I cannot test ASP.

If you do not want to publish the site, you can email me a link. My email is in my profile
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
tuchfeld

ASKER
my site is ASP.Net based and the html code is deep inside..
I made an ASP.Net example so maybe I'll open a new Question...
Michel Plungjan

Sure...
tuchfeld

ASKER
anyway here is the code
files TestAutocompleteCheckBox.htm and TestAutocompleteCheckBox.vb
after running you should type only "b" in the srch_string input
it should give suggestions.
if only Book1 is checked it should return: b1a1, b1a2
else if only Book2 is checked it should return: b2a1, b2a2
else if both are checked it should return: b1a1, b1a2, b2a1, b2a2
This should happen simultaneousely when you check and uncheck the checkboxes.
I hope someone can read and tell me how to fix it.
Thanks.
<HTML>
<HEAD>
  <TITLE>Test Autocomplete with Checkbox</TITLE>
</HEAD>

<SCRIPT src="/jQuery/jquery.js" type="text/javascript"></SCRIPT>
<SCRIPT src="/jQuery/jquery.autocomplete.js" type="text/javascript"></SCRIPT>

<SCRIPT type="text/javascript">
function get_args()
{
  var res = "";
  if (document.getElementById("SearchInBook1").checked) res = "1";
  if (document.getElementById("SearchInBook2").checked) res += "2";
  return res;
}

function research_jquery() {
  $("#string").autocomplete("search"); // see: http://jqueryui.com/demos/autocomplete/#method-search
}

$(function() {
  $("#srch_string").autocomplete("/TestAutocompleteCheckBox.aspx", {
		scroll: true,
		scrollHeight: 180,
		minChars: 1,
		matchSubset: false,
		parse: function(data) {
			var parsed = [];
			var rows = (new Function("return " + data))(); // JSON.parse
			for (var i=0; i < rows.length; i++) {
				var row = $.trim(rows[i]['search_res']);
				if (row) {
					parsed[parsed.length] = {
						data: rows[i],
						result: row
					};
				}
			}
			return parsed;
		},
		extraParams: {
			search_in: function() { return get_args(); }
		},
		formatItem: function(row, i, n) {
			return row.search_res + " (" + row._n + ")";
		}})
});
</SCRIPT>

<BODY>
  <FORM method="get" name="form1" onsubmit="return false;">
        In Book 1&nbsp;<INPUT checked="CHECKED" language="javascript" name="SearchInBook1"
          onkeyup="research_jquery()" type="checkbox" />
        In Book 2&nbsp;<INPUT language="javascript" name="SearchInBook2" onkeyup="research_jquery()"
          type="checkbox" />&nbsp;
        <INPUT id="srch_string" autocomplete="off" name="srch_string" onkeypress="" type="text"
          value="">&nbsp;
  </FORM>
</BODY>
</HTML>

Open in new window

Imports System.Web.UI
Imports System.Web.Script.Serialization

Partial Public Class TestAutocompleteCheckBox
    Inherits Page

    Private Class search_res
        Sub New(ByVal search_res As String, ByVal _n As Integer)
            Me.search_res = search_res
            Me._n = _n
        End Sub
        Public search_res As String
        Public _n As Integer
    End Class

    Protected Overrides Sub Onload(ByVal e As System.EventArgs)
        Dim search_in As String = Request.QueryString("search_in")
        Dim search_res_list As List(Of search_res) = New List(Of search_res)
        If search_in.Contains("1") Then
            search_res_list.Add(New search_res("b1a1", 1))
            search_res_list.Add(New search_res("b1a2", 1))
        End If
        If search_in.Contains("2") Then
            search_res_list.Add(New search_res("b2a1", 1))
            search_res_list.Add(New search_res("b2a2", 1))
        End If
        Dim serializer As JavaScriptSerializer = New JavaScriptSerializer()
        Dim arrayJson As String = serializer.Serialize(search_res_list)
        Response.Write(arrayJson)
    End Sub

End Class

Open in new window

All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
ASKER CERTIFIED SOLUTION
Michel Plungjan

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
tuchfeld

ASKER
Greate, we have a progress.
Let's just look at part of the code that I used:
    $("input:checkbox[name='SearchInBook']").bind("click",function() {
       alert("here");
       $("#srch_string").autocomplete("search");
    });
It prints the alert, so we cought the event (no need to use the onclick= for the input element.
BUT, unfotunately the line:
$("#srch_string").autocomplete("search");
does not activate the autocomplete search.
I know it because I have a breakpoint at the server side but it is not reached.
Any suggestion?
Michel Plungjan

It does for me.

I have a demo here - (It is not hooked up to the back end but you can see it calls the server with the correct url)

http://plungjan.name/eetest/ajax/autocomplete.html
tuchfeld

ASKER
Ok, greate I bealive you solved it..
but as you can see I also pass the amount of search apearances (it is 1 in the example but it can be greater).
also, as you can see, I use a different (older?) version of JQuery Autocomplere.
I saw this http://www.learningjquery.com/2010/06/autocomplete-migration-guide
but it's not much assisting me.
Would you help me migrate My code (with the search_res  and _n fields).
Thanks allot.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Michel Plungjan

Sure. My code does not care how many checkboxes you have. Just call them all the same or give them the same class.
tuchfeld

ASKER
What I mean is that for example formatItem is not supported (you use source: ...).
Can you direct me how to implement it as I did before in your environment?
tuchfeld

ASKER
Oh it's simple, just need to change my initial code to this:
parsed[parsed.length] = {
  label: row + " (" + $.trim(rows[_i]['_n']) + ")",
  value: row
};
Thanks allot for the help!
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
Michel Plungjan

Great :)