Jquery - .change won't work

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
pizzipie
Forum Commoner
Posts: 87
Joined: Wed Feb 10, 2010 10:59 pm
Location: Hayden. ID

Jquery - .change won't work

Post by pizzipie »

I am trying to develop a program where I can load choices from a .php file.
One version of this program uses .click function and a prompt to get a name to search for. This works fine.
The other version of this program uses a form and .change function to input a name to search for. This DOES NOT WORK. The jquery .load() doesn't access the .php file.

Sorry about the code below but this forum won't let be upload files with extensions of .txt, .html, .php so I don't know how to do it.

Thanks in advance for any help.

RP

Version 1.

Code: Select all

<!DOCTYPE HTML PUBLIC
                 "-//W3C//DTD HTML 4.01 Transitional//EN"
                 "http://www.w3.org/TR/html401/loose.dtd">
<html>
<head>

<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" >
<title>Page Loader</title>

<script type="text/javascript" src="../jquery/jquery-1.6.js"></script>

</head

<body>
<!--
<div id="container">

	<fieldset>
 		<form id="getPartName" action="" > 
  			<p> Type Partial Name to Search for a Name: and Click<br></p>
   			<p><input type="text" name="partnm" id="partnm"></p> 
    			
  		</form>
   </fieldset>  
</div>
-->

<div id="container">
<a href="#" id="loadData">Click This Link To Load My Favorite Movies</a>
</div>


<script type="text/javascript">

$(document).ready(function() {

	$("#loadData").click(function() {
	
	lukupname=prompt("Enter Partial Name to Search for:", 'All Names');
		
	alert("lukupname "+lukupname);
		
	$(this).text("...One Moment Please...");
	$("#container").append('<div id="favoriteMovies"></div>')
	.children("#favoriteMovies").hide()
	.load("A-theOtherPage2.php ul#favoriteMovies", {'myname':lukupname}, function() {
			$("#loadData").remove();
			$("#favoriteMovies").show(); //.slideDown("slow");
		});
	return false;
	});
});

</script>

</body>

</html>


Version 2.

Code: Select all

<!DOCTYPE HTML PUBLIC
                 "-//W3C//DTD HTML 4.01 Transitional//EN"
                 "http://www.w3.org/TR/html401/loose.dtd">
<html>
<head>

<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" >
<title>My Dysfunctional Page Loader</title>

<script type="text/javascript" src="../jquery/jquery-1.6.js"></script>

</head>

<body>


<div id="container">

	<fieldset>
 		<form id="getPartName" action="" > 
  			<p> Type Partial Name to Search for a Name: and Click<br></p>
   			<p><input type="text" name="partnm" id="loadData"></p> 
    			
  		</form>
   </fieldset>  
</div>

<!--
<div id="container">
<a href="#" id="loadData">Click This Link To Load My Favorite Movies</a>
</div>
-->


<script type="text/javascript">

$(document).ready(function() {

	$("#loadData").change(function() {
	
		lukupname=$('#loadData').val();

		$(this).text("...One Moment Please...");
		$("#container").append('<div id="favoriteMovies"></div>')
		.children("#favoriteMovies").hide()
		.load("AtheOtherPage2.php ul#favoriteMovies", {'myname':lukupname}, function() {
			$("#loadData").remove();
			$("#favoriteMovies").show(); //.slideDown("slow");
		});
	return false;
	});
});

</script>

</body>

</html>

PHP File:

Code: Select all


<?php 

	$name=$_POST['myname'];

 ?>



<!DOCTYPE HTML PUBLIC
                 "-//W3C//DTD HTML 4.01 Transitional//EN"
                 "http://www.w3.org/TR/html401/loose.dtd">
                 
<html>

<head>

<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" >
<title>Movie Titles</title>

</head>

<body>



<ul id="favoriteMovies">
	<li style="font-weight: bold; list-style-type: none;">My Favorite Movies</li><br>
	<?php echo "<li>".$name."</li>\n"; ?>
	<li>Contact</li>
	<li>Shawshank Redemption</li>
	<li>Napoleon Dynamite</li>
	<li>Back To The Future</li>
	<li>The Goonies</li>
	<li>Cinderella Man</li>
	<li>Apollo 13</li>
</ul>

</body>

</html>

phpHappy
Forum Commoner
Posts: 33
Joined: Wed Oct 26, 2011 1:58 pm

Re: Jquery - .change won't work

Post by phpHappy »

.change isn't for links
pizzipie
Forum Commoner
Posts: 87
Joined: Wed Feb 10, 2010 10:59 pm
Location: Hayden. ID

Re: Jquery - .change won't work

Post by pizzipie »

phpHappy,

Thanks for the reply.

I'm not using .change in a link. It is as below. I commented out the link in version2 above.

Code: Select all

<div id="container">

        <fieldset>
                <form id="getPartName" action="" >
                        <p> Type Partial Name to Search for a Name: and Click<br></p>
                        <p><input type="text" name="partnm" id="loadData"></p>
                       
                </form>
   </fieldset>  
</div>
<script type="text/javascript">

$(document).ready(function() {

        $("#loadData").change(function() {
       
                lukupname=$('#loadData').val();

                $(this).text("...One Moment Please...");
                $("#container").append('<div id="favoriteMovies"></div>')
                .children("#favoriteMovies").hide()
                .load("AtheOtherPage2.php ul#favoriteMovies", {'myname':lukupname}, function() {
                        $("#loadData").remove();
                        $("#favoriteMovies").show(); //.slideDown("slow");
                });
        return false;
        });
});

</script>
phpHappy
Forum Commoner
Posts: 33
Joined: Wed Oct 26, 2011 1:58 pm

Re: Jquery - .change won't work

Post by phpHappy »

now it's on input type="text"
.change is only for <select>
pizzipie
Forum Commoner
Posts: 87
Joined: Wed Feb 10, 2010 10:59 pm
Location: Hayden. ID

Re: Jquery - .change won't work

Post by pizzipie »

I reworked this to :

Code: Select all

<script type="text/javascript">
		
		$(document).ready(function() {
		
			$(function() {
			    $('form').bind('submit',function() { showValues(); return false; });
			});

			function showValues() {
			
			    var searchName=$('#partnm').val();			
			    var str = $("form").serialize();
				$(".results-box").fadeIn();
			     $(".results").text(str);
			     $(".results").text("Result of Name Search for " + searchName + " is:");
			    
			    
	$(".results").append('<div id="addrsNames"></div>')
	.children("#addrsNames").hide()
	.load("makeSelectList.php select#addrsNames", str , function() {        //
			$("#loadData").remove();
			$("#addrsNames").show(); //.slideDown("slow");
		});			    
			    
			}

		});
		
		
		</script>
This works !! BUT, I wanted to do it without clicking a submit button. I don't know enough about jquery to do that yet. Am I on the right track??

Thanks for your help.

RP
KCAstroTech
Forum Commoner
Posts: 33
Joined: Sat Aug 27, 2011 11:16 pm

Re: Jquery - .change won't work

Post by KCAstroTech »

Actually .change does work on all inputs, however, it will only register the "changed" event when you leave (tab or click out of) the input area. If I understand what you are wanting, I would use something more like:

Code: Select all

$("#loadData").keyup(function(e) {
	if(e.keyCode == 13) {//Check if the enter key was pressed
		if($("#loadData").val().length < 3)	return false; //check if the input text is less than 3 character's long and if so leave the function now
		lukupname = $('#loadData').val();

		$(this).text("...One Moment Please...");
		$("#container").append('<div id="favoriteMovies"></div>').children("#favoriteMovies").hide().load("AtheOtherPage2.php ul#favoriteMovies", {
			'myname' : lukupname
		}, function() {
			$("#loadData").remove();
			$("#favoriteMovies").show();
			//.slideDown("slow");
		});
		return false;
	} else {
		if(window.lukupnameTimer) clearTimeout(window.lukupnameTimer); //Check if a timer already exists if so clear it so we can start the timer over
		window.lukupnameTimer = setTimeout(function(){
			e = jQuery.Event("keyup"); //create a new keyup event
			e.which = 13 //set the event to think the enter key was pressed
			$("#loadData").trigger(e); //trigger the newly created event to simpulate the enter key being pressed
		}, 500); //set the timer wait 500ms before triggering this function
	}
});
What I did there was simply use the keyup event that does a few things. First it checks if the key that was pressed was the enter key (decimal character 13). If the enter key was either pressed or simulated it next checks if the input length is less than 3 characters long and if so end the function without running the lookup. What this does is to help avoid trying to lookup on a string that may be too short (1-2 characters long). If the string passes these two checks then it will continue with the rest of your function. However, if the key entered wasn't the enter key it then creates a timer to wait 500 milliseconds then simulates the enter key being pressed. What this does is allow for ample time for the user to type something, then if they don't press the enter key and are just waiting it does it for them! :D
pizzipie
Forum Commoner
Posts: 87
Joined: Wed Feb 10, 2010 10:59 pm
Location: Hayden. ID

Re: Jquery - .change won't work

Post by pizzipie »

Thank you KCAstroTech,

WOW!

The direction I'm trying to go with this is to produce a "simple" single line input giving a partial spelling of a name which, when submitted to the server by .click(), .change(), or Submit and presented as - LIKE '%var%' - to MySql will result, after being processed by PHP, in a SELECT list to pick a choice from. If no partial name is given all names in the database are returned in the SELECT list. It really doesn't matter how few characters are typed into the INPUT line. Few characters result in more names returned and if nothing is typed the user (ME or my wife) will sit until the submit button is pressed.

ie: sort of a cascading dropdown. This works fine using the code in the reply before your answer and appears to my novice jquery programming as much simpler, though not what I want.

Any other ideas? I'm learning tricks from you!!

Thanks,

RP
KCAstroTech
Forum Commoner
Posts: 33
Joined: Sat Aug 27, 2011 11:16 pm

Re: Jquery - .change won't work

Post by KCAstroTech »

I thought that might be what you wanted but wasn't sure. If that is the case then there are several "autocomplete" jQuery plugins out there. The one that I have used the most is probably the jQueryUI one (http://jqueryui.com/demos/autocomplete/). This has the ability to both do a local look up for the autocomplete or a server side MySQL look up as well as many display options that should suit your needs! Simply look at the autocomplete examples (menu on the right) and you can look at the example's code by clicking the "view source" link at the bottom of the example. The whole jQueryUI plugin system is quite extensive and has many cool and useful features so be sure to check them all out. :-D
pizzipie
Forum Commoner
Posts: 87
Joined: Wed Feb 10, 2010 10:59 pm
Location: Hayden. ID

Re: Jquery - .change won't work

Post by pizzipie »

Thanks KCAstroTech,

I will get to your suggested link but I would appreciate it if you could look at my latest effort. In researching ".change() won't work" on the internet I came across a solution and tried it (check out the function ... "addSelectChange"...). It actually works. Now, however, I have a new problem. In returning the result of a selection from the options list the alert() works and reports that the choice I made is "such and such". I want to use the GLOBAL variable used in alert(), "choiceOfNames", to report my choice to go to the server again and search for data associated with the returned name. It does not work. Here is the code that I have: I CAN'T FIGURE OUT HOW TO UPLOAD MY FILE (IT WON'T LET ME) SO: CODE Below.

It seems that the program is locked into a loop that returns the selected choice, as it is supposed to do, but you can't break out of this without the program just stopping. ie: code won't execute any instruction after the alert(). I think I'm close to making this all work and a clue I've been reading about may be the .unbind() the event. I don't have a clue how to do this, however. I may be totally wrong. Help!!

Thanks again,

RP

Code: Select all

<!DOCTYPE HTML PUBLIC
                 "-//W3C//DTD HTML 4.01 Transitional//EN"
                 "http://www.w3.org/TR/html401/loose.dtd">
<html>
<head>

<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" >
<title>Pizzi Address Book</title>


<link rel="stylesheet " type="text/css" href="../css/frontend.css" />
<link rel="stylesheet " type="text/css" href="../css/load.css" />
<link rel="stylesheet " type="text/css" href="../css/connect.css" />

<script type="text/javascript" src="../jquery/jquery-1.6.js"></script>


<script type="text/javascript">
			
		$(document).ready(function() {
		
var choiceOfNames="";  // GLOBAL VAR ??
		
			$(function() {
			    $('form').bind('submit',function() { showValues(); return false; });
			});

			function showValues() {
			
			    	var searchName=$('#partnm').val();			
			    	var str = $("form").serialize();
				$(".results-box").fadeIn();
			     $(".results").text(str);
			     $(".results").text("Result of Name Search for " + searchName + ": Click on Your Choice for Data");
			    
			    
				$(".results").append('<div id="addrsNames"></div>')
				.children("#addrsNames").hide()
				.load("makeSelectList.php select#addrsNames", str , function() {        //
					$("#partname").remove();
					$("#addrsNames").show(); //.slideDown("slow");
					addSelectChange();
				});
					   
			} //show values
			
alert("Again my Selection was ..."+choiceOfNames); // DOESN'T WORK -- YOU NEVER SEE THIS	EXCEPT AT START WHEN choiceOfNames is blank !!
			
		}); // doc ready
			
</script>
		
<!-- ================================================== -->

<script type="text/javascript" >

function addSelectChange(){ 

   $('select').bind('change', function(){ 
   	var mySelection= $("option:selected", this).val();
   	choiceOfNames=mySelection;
   	alert("My Selection was ..."+choiceOfNames);  /////////////////  OK, lists choice I make EACH TIME I CLICK ON AN OPTION
	
  });} 

</script>

<!-- ================================================== -->

</head>
		
<body>

  	<div class="header">

 		<h1><img src="../images/AmericanFlag2.png" alt="Company logo" height="90px" />

				Rick and Polly&rsquo;s Contacts</h1>

   		<h3>&nbsp;&nbsp;&nbsp;&nbsp;Name Selector </h3>

	 </div>		

   		
<div id="partname">

	<fieldset>
 		<form id="getPartName" > 
  			<p> Type Partial Name, Submit: to Search for a Name:<br>
			Type Nothing, Submit: to Display all Names:<br></p>
   
   			<p><input type="text" name="partnm" id="partnm" ></p> 
   			<input type="submit" name="submit" class='hov' value="Submit">
   			
  		</form>
   </fieldset> 
    
</div>   		
   		
<div class="results-box" >  
   		

	<div class="results" >

	</div>		

</div>


</body>
</html>

KCAstroTech
Forum Commoner
Posts: 33
Joined: Sat Aug 27, 2011 11:16 pm

Re: Jquery - .change won't work

Post by KCAstroTech »

Just from reading over the code, the issue would appear to be with this:

Code: Select all

                                $(".results").append('<div id="addrsNames"></div>')
                                .children("#addrsNames").hide()
                                .load("makeSelectList.php select#addrsNames", str , function() {        //
                                        $("#partname").remove();
                                        $("#addrsNames").show(); //.slideDown("slow");
                                        addSelectChange();
                                });
jQuery is chainable which means that you can run multiple actions on a single target. Therefore your code above does this:

1: Append a div with id "addrsNames" into element(s) with class of ".results".
2: Look for the child node with id "addrsNames" that is within ".results" (the one we just added) and hide it (now "addrsNames" is the new target).
3: Retrieve the HTML results of load("makeSelectList.php") into "#addrsNames".

The problem is with command 3. The .load function retrieves and HTML results from and ajax command and replaces the content of the target element ("#addrsNames") but when you add the "select#addrsNames" to the load's url it makes that the new target and "select#addrsNames" doesn't exist as #addrsNames is a div not a select. Thus, when it goes to load the data the entire script fails never getting to anything after.

What you will want to do is create and hide a static div box for the text and one for the contents of the select data being returned by load. For example:

Code: Select all

<div id="results-box" >  
        <div id="results_title">
       </div>
        <div id="results_data" >
        </div>
</div>
Then replace your document ready with:

Code: Select all

                $(document).ready(function() {
                
var choiceOfNames="";  // GLOBAL VAR ??
                
                        $(function() {
                            $('#getPartName').bind('submit',function() { showValues(); return false; }); // Bind to the getPartName form and not 'form'. $('form') will get and bind ALL forms on this page when you only want t bind one
                        });

                        function showValues() {
                        
                                var searchName=$('#partnm').val();                      
                                var str = $("form").serialize();
                                $("#results-box").fadeIn();
                             $("#results_text").text(str); // what is the purpose of this when you next replace the text with the below statement?
                             $("#results_text").text("Result of Name Search for " + searchName + ": Click on Your Choice for Data");
                            
                            
                                $("#results_data").hide().load("makeSelectList.php", str , function() {
                                        $("#partname").remove();
                                        $("#results_data").show(); //.slideDown("slow");
                                        addSelectChange();
                                });
                                           
                        } //show values
                        
alert("Again my Selection was ..."+choiceOfNames); // DOESN'T WORK -- YOU NEVER SEE THIS        EXCEPT AT START WHEN choiceOfNames is blank !!
                        
                }); // doc ready
Notice how I removed the div "addrsNames" from the script as it isn't needed since we are loading everything into "#results_data".

Hope this helps!
pizzipie
Forum Commoner
Posts: 87
Joined: Wed Feb 10, 2010 10:59 pm
Location: Hayden. ID

Re: Jquery - .change won't work

Post by pizzipie »

GREAT!! I will re-work my code to reflect what you have just showed me. Thanks very much for your explanations. We Newbies can learn a lot by this sort of dialog rather than the more common "look at 'http:// blah blah'". (Note: The above code is from a tutorial I have re-worked to fit my purposes. I did not fully understand what was going on until your last reply.)

Since I last was last in contact with you I did find a solution that does do what I wanted which was to transfer the variable 'mySelection' containing the selected name to the next .php page for a trip to MySql and a display page to show the data for 'mySelection'.

Code: Select all


function addSelectChange(){ 

   $('select').one('change', function(){ 
   	var mySelection= $("option:selected", this).val();
    	//alert("My Selection was ..."+mySelection);   	
   	window.location.href="ACtransferName.php?Display_Name="+mySelection; // go on to show data for the selected name

  });} 
For some reason, I do not understand, in the above function the line 'window.loc ....' does work and actually goes on to the .php page where I can '$_GET' the variable and go from there. I tried to have the function 'return mySelection;' in this page but it would not. Any reason you can see for that behavior?

Well, I had better get to writing the code changes you suggest and see what happens.

Again Thanks,

RP
KCAstroTech
Forum Commoner
Posts: 33
Joined: Sat Aug 27, 2011 11:16 pm

Re: Jquery - .change won't work

Post by KCAstroTech »

:D Thanks RP! I am all self taught and I know what it is like to be in your shoes so I try my best to pass down what I have learned in as meaningful a way as possible. :D

The full capabilities of jQuery and PHP are very nice and I have in my mind a more elegant solution that should work for what you want but don't have the time right now to type it up. However, if when if I get done with work early and get home at a descent time I will type up a mock scenario that should work for what you want and post the files here.

TTFN!
KCAstroTech
Forum Commoner
Posts: 33
Joined: Sat Aug 27, 2011 11:16 pm

Re: Jquery - .change won't work

Post by KCAstroTech »

My apologies, I have been slammed with work and haven't gotten back on this. Were you able to get it working?
pizzipie
Forum Commoner
Posts: 87
Joined: Wed Feb 10, 2010 10:59 pm
Location: Hayden. ID

Re: Jquery - .change won't work

Post by pizzipie »

Hi KC,

No apologies necessary. Been there.

I re-wrote the code I had to the following and it works just fine. I just don't understand why it is necessary to call a function [addSelectChange()] for the [ $('select').one('change', function(){ ] to work.

I would love to see your other solution to this when you have the time to do it.

Thanks,

RP


[inline]

$(document).ready(function() {

$(function() {
$('#getPartName').one('submit',function() { showValues(); return false; });
});

// ========== showValues() ===================

function showValues() {

var searchName=$('#partnm').val();
if(typeof(searchName)=="string" & searchName=="") searchName="All Names";
var str = $("#getPartName").serialize();
$(".results-box").fadeIn();
$(".results").html("Result of Name Search for <span style='color:red;'>"
+ searchName + "</span> : Click on Your Choice for Data");

$(".results").append('<div id="addrsNames"></div>')
.load("makeSelectList.php #addrsNames", str , function() {
$("#partname").remove();
$("#addrsNames").show();

addSelectChange();

}); // function
} //show values
}); // doc ready

// ============= addSelectChange() ===========

function addSelectChange(){

$('select').one('change', function(){
var mySelection= $("option:selected", this).val();

// show data for the selected name

window.location.href="ContactDisplay.php?Display_Name="+ encodeURIComponent(mySelection);


});}


[/inline]
jonyboker
Forum Newbie
Posts: 1
Joined: Thu Feb 16, 2012 12:15 am

Re: Jquery - .change won't work

Post by jonyboker »

this code is very helpful so thanks sharing this topic.
custom closets ft lauderdale
Post Reply