views:

32

answers:

2

I'm trying to assign a variable from a html text input value and then have that variable used in a function that uses the jquery ":contains" selector to hide divs that don't match the variable...here is the code I have...

<head>
<script language="JavaScript" type="Text/JavaScript" src="jquery.js"></script>
<script language="JavaScript" type="Text/JavaScript">
var myform = document.forms[0];
var FilterText = myform.FilterText.value;

function FilterBlocks()
{
$("div.block").hide();
$("div.block:contains(FilterText)").show();
}
</script>
</head>

<body>
<form action="#">
<input class="navButtons" type="text" name="FilterText">
<input class="navButtons" type="button" name="FilterButton" value="Filter Videos"     onMouseUp="FilterBlocks()">
<br /><br />
</form>
<div class="block"><a href="1.html"><img src="images/1.jpg">This is the title<a></div>
</body>

I tried doing an alert() with the variable that I an trying to use but it's coming back undefined.

Any help would be greatly appreciated...thanks!

+2  A: 

Try $("div.block:contains(" + FilterText + ")").show(); instead. You'll need to 'escape' special characters too ((, ), etc), but this should work on simple strings.

And BTW, what you are coding in called Javascript, not Java.

Nikita Rybak
Thanks for the help...and so that I'm clear...Java is the program and what I'm writing is the Javascript...right?Thanks!
@user430264 - No, Java and javascript doesn't have any connection at all. they are 2 different language with some few similarities.
Reigel
+1  A: 

you might want to do it this way,

function FilterBlocks(){
   $("div.block").hide();
   $("div.block:contains("+FilterText+")").show();
}

and also, calling var myform = document.forms[0];, in your code above, would result myform as undefined because DOM is not yet ready.

you might want it this way,

<script language="JavaScript" type="Text/JavaScript">
$(function(){
   // call it when DOM is ready
   var myform = document.forms[0];
   var FilterText = myform.FilterText.value;

   function FilterBlocks(){
     $("div.block").hide();
     $("div.block:contains("+FilterText+")").show();
   }
});
</script>

for better jQuery style codes, I suggest this,

<input class="navButtons" type="button" name="FilterButton" value="Filter Videos"     onMouseUp="FilterBlocks()">

to just,

<input class="navButtons" type="button" name="FilterButton" value="Filter Videos" >

your jQuery would be,

<script language="JavaScript" type="Text/JavaScript">
$(function(){
   // call it when DOM is ready
   var myform = document.forms[0];

   $('.navButtons:button').click(function(){
     var FilterText = myform.FilterText.value;
     $("div.block").hide();
     $("div.block:contains("+FilterText+")").show();
   });
});
</script>
Reigel
Thanks for the help...your last cleaned up jQuery seems to wok great! alot to take in for a beginner but I will enjoy dissecting it...