I have two links called “Read More” (bottom of code) that contain different values. When clicked, they call a jquery function that send it to demo_search.php. Problem is, no matter which link I click, I keep getting the same values. If I were to use
var searchString = ($(this).attr("href"))
instead of
var searchString = ($(".more_info").attr("href"))
things work fine. But I cant use (this). How to solve this?
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Test Search</title>
<link rel="stylesheet" type="text/css" href="my.css">
<script type="text/javascript" src="http://localhost/dev/ajax/jquery.js"></script>
<script type="text/javascript">
$(function() {
$(".more_info").click(function() {
// getting the value that user typed
var searchString =($(".more_info").attr("href"));
// form the queryString
var data = 'search='+ searchString;
var imgLoad = '<img src="loading.gif">';
// if searchString is not empty
if(searchString) {
alert (searchString);
// ajax call
$.ajax({
type: "GET",
url: "demo_search.php",
data: searchString,
beforeSend: function(html) { // this happens before actual call
$(".word").html(searchString);
$(".imgProgress").html(imgLoad);
},
success: function(page_data){ // this happens after we get results
$("#results").empty();
$("#results").fadeIn(200);
$("#results").append(page_data);
$(".imgProgress").empty();
},
});
}
return false;
});
});
</script>
</head>
<body>
<div id="container">
<div style="margin:20px auto; text-align: center;">
<form method="post">
<input type="text" name="search" id="search_box" class='search_box'/>
<input type="submit" value="Search" class="search_button" /><br />
</form>
</div>
<div>
<div id="searchresults">Search results for <span class="word"></span><span class="imgProgress"></span></div>
<div id="results" class="update" style="display:none;"><ul></ul>
</div>
<div>
<a href="search=sony&offset=20&lang=en" class="more_info">Read More</a>
<a href="search=pioneer&offset=30&lang=en" class="more_info">Read More</a>
</div>
</div>
</div>
</body>
</html>
($(".more_info")will return you a collection of all elements with this class. Unless you specify a specific position in the array invoking further functions will always target the first element in this collection.Compare the change between
searchStringAandsearchStringBin the fiddle below when you click on the two different “read more”.thisof an invoked function is a JavaScript object and therefore it does not have a method.attr()wich belongs to jQuery scope. SeesearchStringCin the fiddleSo you have to cast
thisto a jQuery object via$(this)and then you can callI stripped down the original code and replaced the
<a>tags with<span>to make it more click friendly 🙂 You can find the fiddle here.I highly recommend it running with an open console to observe the error in the line: