I have a search box. I'm using jQuery and keyup to filter repeating divs.
Each div looks like this:
<div class="searchCell" id="searchCell' . $id . '">';
<div class="friendName">
// someNameOutputWithPHP.
</div>
</div>
Now, I want to filter based on the name text. If someNameOutputWithPHP contains the search query, the entire searchCell should show(). If it doesn't, the entire searchCell should hide().
This doesn't work, though:
<script type="text/javascript">
$(document).ready(function() {
$("#searchbox").keyup(function() {
var searchValue = $(this).val();
if(searchValue === "") {
$(".searchCell").show();
return;
}
$(".searchCell").hide();
$(".searchCell > .friendName:contains(" + searchValue + ")").show();
});
});
</script>
EDIT
New problem: I got the divs show() to show how I want. But the :contains isn't working exactly right.
For instance: say one of the name's is Ryan. When I search for 'Ryan', I get nothing. But when I search for 'yan' I get the Ryan div.
What's wrong?
Here's the :contains code:
$(".friendName:contains(" + searchValue + ")").parent().show();
That is because you are hiding the .searchCell and then showing its children .friendName divs, which though get display property will not show up because parent is hidden.
Try this:
<script type="text/javascript">
$(document).ready(function() {
$("#searchbox").keyup(function() {
var searchValue = $(this).val();
if(searchValue === "") {
$(".searchCell").show();
return;
}
$(".searchCell").hide();
//$(".searchCell:has(.friendName:contains(" + searchValue + "))").show();
// OR
//$(".friendName:contains(" + searchValue + ")").parents(".searchCell").show();
// OR
$(".friendName:contains(" + searchValue + ")").parent().show(); // If .searchCell is always a direct parent
});
});
</script>
Your selector
$(".searchCell > .friendName:contains(" + searchValue + ")")
will select all .friendName divs that contain the text from searchValue. That works just fine, but you need to .show() the parent element. Just invoke the .parent() method for that:
$(".searchCell > .friendName:contains(" + searchValue + ")").parent().show();
Demo: http://jsfiddle.net/d3ays/3/
And by the way, you HTML markup looks messed up too. There is a ; behind your div.searchCell for instance.
Related
I have an array of inputs generated from js code. I have set the name of the inputs like this: name="myTextInput[]"
How can I get the index of the selected input?
I tried something like:
onClick="oc(this);"
where:
function oc(inp)
{
return(inp.index);
}
but is not working.
I can use jQuery as well
You can use the EACH function in jquery. This will parse through the set of matched elements. You can put a custom function inside that will use the index of each element, as you parse through, as an argument.
$('input').each(function(index){
alert(index);
});
You can also get the value of each input like this:
$('input').each(function(index, val){
alert(index + ' has value: ' + val);
});
see details here: http://api.jquery.com/jQuery.each/
** EDIT **
If you want the value shown in an alert box on click, use the each function and the click function together. Remember to get the real-time value of the input, use $(this).val(). Return index and value data on click:
$('input').each(function(index, val){
$(this).click(function(){
alert(index + ' has value: ' + $(this).val());
});
});
You could get the input like this (not sure if you actually wanted the click event though)...
var inputs = $('input[name="myTextInput[]"]');
inputs.click(function() {
alert(inputs.index(this));
});
Please use the index() method to find the position of an element.
Check out this example: http://jsbin.com/uyucuv/edit#javascript,html
<ul>
<li id="foo">foo</li>
<li id="bar">bar</li>
<li id="baz">baz</li>
</ul>
$(function() {
$("li").on("click", function() {
alert($(this).index());
});
});
Check the index() documentation here: http://api.jquery.com/index/
Hope this helps!
The "jQuery way" is to avoid onClick="whatever()" and use pure JavaScript separate from the HTML tags. Try this between a pair of <script> tags (note: requires jQuery 1.7 or higher):
$('input').on('click', function() {
var varname = $(this).attr('name'),
$arr = $('input[name="'+varname+'"]'),
idx = $arr.index(this);
alert(idx);
});
http://jsfiddle.net/mblase75/EK4xC/
I have a multi level select chain, where by the value of the first select generates the options for the next select list. And within the second list some of the values will cause a div to display with another input.
My codes (below) seem to work just fine when tested on static content (ie: the second select is hard coded in the html). But when I add it with JQuery, the second level no longer triggers the .change function.
<script type="text/javascript">
$(document).ready(function() {
$dts = $("select[name='tourdes']");
$dts.change(function() {
var dtsValue = $(this).val();
var dtsString = '?tourdes=' + dtsValue;
$('#dateSelect').show();
$('#dateSelect').load('include/avdates.php' + dtsString).append();
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$tags = $("select[name='tourcode']");
$tags.change(function() {
if ($(this).val() == "private") {
$(".prvcal").css({"visibility":"visible"});
}
});
});
</script>
I am guessing something needs to be re-initialized, but I am getting no where with my experiments.
If you're using jQuery 1.7 you'll want to use on, as both live and delegate are deprecated.
$(document).on("change", "select[name='tourcode']", function() {
var dtsValue = $(this).val();
var dtsString = '?tourdes=' + dtsValue;
$('#dateSelect').show();
$('#dateSelect').load('include/avdates.php' + dtsString).append();
});
docs for on()
You are probably using dynamically-generated HTML elements. If that is the case, you need to use .delegate() to handle them:
$('select').delegate("[name='tourdes']", 'change', function() {
Trying to implement a simple "load more" functionality with jquery. The idea is to use it in the same way as one does pages. Click and a certain number of posts loaded from the database show up.
I have the following javascript:
$(function(){
var count = 0;
var num = 20;
$("#contents").load("posts.php");
$("#more").click(
function(){
var count = 0;
var num = 20;
$("#contents").load("posts.php");
$("#more").click(
function(){
$(".loading").show("fast");
count += num;
$.post("posts.php", {'page': count}, function(data){
$("#contents").append(data);
$(".loading").hide("slow");
});
}
);
and the following file posts.php
<?
echo "hello";
?>
And I have another file page.php with
<div id="contents"></div>
<div class="loading"><span style="text-decoration: blink;">LOADING...!</span></div>
<button id="more">More..</button>
When i click the "More Button" though nothing happens even though I'm just trying to print out a simple hello world here. I have loaded the javascript in the head of the file like
<script type ="text/javascript" src ="javascript/load.js"></script>
Other javascript functionality I've implemented is working fine. Is there something to add to the "loading" or "contents" elements in page.php?
Your javascript lacks basic syntactic structure, and must be issuing a syntax error, unless you messed it up while posting here. Try this:
$(function(){
var count = 0;
$("#more").click(loadPosts);
loadPosts();
function loadPosts() {
var num = 20;
$(".loading").show("fast");
count += num;
$.post("posts.php", {'page': count}, function(data){
$("#contents").append(data);
$(".loading").hide("slow");
});
}
});
UPDATE
Edited the code above and removed $("#contents").load("posts.php");. It was not necessary, and redundant.
I have a table whose values are being generated dynamically with PHP, including the id and name attributes (e.g. id="question_".
How can I set an element attribute with this in mind? For example, I have a div whose text will change after a successful ajax call, but the id is dynamic.
I have tried making the following test function, and calling it on an onclick event:
function approve(question_id)
{
var div = 'suggestion_status_' + question_id;
$('#div').html('test');
}
But that does not work. How can make the value of variable 'div' the selector?
The problem with your example is that div is a variable, not a string; so the following will work:
function approve(question_id)
{
var div = 'suggestion_status_' + question_id;
$('#' + div).html('test');
}
Or even:
function approve(question_id)
{
$('#suggestion_status_' + question_id).html('test');
}
Another approach would be to utilize classes, and add a known class to your elements. Without seeing the full HTML, I can't provide a full example, but something like this would be the way to go:
$('.yourCommonClass').bind('click', function () {
var that = this;
jQuery.get('/accept.php', {
id: this.id
}, function (msg) {
$(that).html('Accepted!');
});
});
Bearing in mind that jQuery.get parameters are the target url, optional data attributes that are encoded in the request, and then a callback function.
you defined div as a variable then used it as a string try concatenating it instead
function approve(question_id)
{
var div = 'suggestion_status_' + question_id;
$('#'+ div).html('test');
}
or shorten like this
function approve(question_id)
{
$('#suggestion_status_' + question_id).html('test');
}
$('#suggestion_status_' + question_id).html('test');
$('#suggestion_status_' + question_id)
I think you want this:
function approve(question_id)
{
var div = 'suggestion_status_' + question_id;
$('#'+div).html('test');
}
this. $('#suggestion_status_' + question_id).html('test');
For some reason the script below is unable to get the id of the draggable divs using attr('id'), but it works on the other static elements on the page. I am totally confused as to why this wont work and if anyone has a solution for me it would me much appreciated.
$(document).ready(function(){
//$(".draggable").draggable();
$(".draggable").draggable({ containment: '#container', scroll: false });
$(".draggable").draggable({ stack: { group: '#container', min: 1 } });
$("*", document.body).click(function (e) {
var offset = $(this).offset();// get the offsets of the selected div
e.stopPropagation();
var theId = $(this).attr('id');// get the id of the selceted div
$("#result").text(this.tagName + " id=" + theId + " (" + offset.left + "," + offset.top +")");
$.post("http://localhost/index.php", "id=" + theId + "&x=" + offset.left + "&y=" + offset.top); //post x,y to php (and the id of the elemnt)
});
var req = function () {
$.ajax({
url: "out.php",
cache: false,
success: function(html){
$("#stuff").empty().append(html);
var css_attr = html.split(",");
$('#1').css('left', css_attr[0] + 'px').css('top', css_attr[1] + 'px');
},
complete: function(){
req();
}
});
};
req();
});
Note: This script is dependent on the following JavaScript sources.
jquery.js
http://jqueryui.com/latest/ui/ui.core.js
http://jqueryui.com/latest/ui/ui.draggable.js
http://jqueryui.com/latest/ui/ui.droppable.js
Currently you're attaching the click handler to all elements in the DOM with * (very very bad, don't do this!), including any children in those draggables.
You are correctly stopping the event from bubbling up using .stopPropagation(), but it's likely a child of a .draggable you've clicked, not the draggable itself. What you want is actually listening on the .draggable element themselves, like this:
$(".draggable").click(function (e) {
var offset = $(this).offset(),
theId = this.id;
e.stopPropagation();
$("#result").text(this.tagName + " id=" + theId + " (" + offset.left + "," + offset.top +")");
$.post("http://localhost/index.php", { id: theId, x: offset.left, y: offset.top });
});
The other changes here are id can be accessed directly, via this.id, and passing an object to $.post() is safer for serialization, like I have above.
Even the above isn't quite there though, you likely want to send the position when you stop dragging, by changing this:
$(".draggable").click(function (e) {
To this:
$(".draggable").bind("dragstop", function (e) {
...or in newer versions of jQuery (1.4.2+):
$(document.body).delegate(".draggable", "dragstop", function (e) {
Your click function works for me on a test page. Out of curiosity, if you move the 'e.stopPropogation()' line to the bottom of your click function, does it behave differently?
Be careful with *, you know, all means all, if you have <div><p><span><a></a></span></p></div> it means that the action is set to every single element. I'd specify classes or tags that should be affected by your function, to be always sure that you get what you want to be clicked.
Try your code replacing * with the object you think it's ID isn't get, and see if it works..
This may seem pretty obvious but are you sure that all the elements that your selecting actually have IDs. If your including everything (with the *) then it is likely that some elements don't have IDs.