code:
<input type="text" name="college_name" id="college_name" placeholder="Search By College Name" >
<div id="box"></div>
<script>
$(document).ready(function() {
$("#college_name").keyup(function() {
$.ajax({
type: "POST",
url: "colleges.php",
data: 'keyword=' + $(this).val(),
success: function(data) {
$("#box").show();
$("#box").html(data);
}
});
});
});
function selectCollege(val) {
$("#college_name").val(val);
college_name = $("#college_name").val();
location.href = "college-details.php?college_name=" + college_name;
$("#box").hide();
}
</script>
college.php
<?php
$tempcollege .= "<a href='#' style='color:#fff;'><li onClick=selectCollege('".$college_name."''".$field."');>".$college_name.$field."</li></a>";
?>
In this code I have created a autocomplete box where all colleges are displaying when I keyup on input field but when click on any college then it not go to link i.e. college-details.php. So, How can I fix this problem ?please help me.
Thank You
There seem to be multiple issues in your college.php:
normally <li> should be outside <a>,
href equals to "#", which in some cases causes browser to load/reload a page and since click event is also bubbled to <a>,
You can avoid this two ways.
Either replace href='#' with href='javascript:void(0)'
<?php
$tempcollege .= "<li onClick=selectCollege('".$college_name."''".$field."');><a href='javascript:void(0)' style='color:#fff;'>".$college_name.$field."</a></li>";
?>
or cancel event bubbling and executing default behaviour of <a> tag in onClick by returning false.
<?php
$tempcollege .= "<li onClick=\"selectCollege('".$college_name."''".$field."'); return false;\"><a href='#' style='color:#fff;'>".$college_name.$field."</a></li>";
?>
Worst case scenaro if you cannot edit the college.php, then add window.event.preventDefault(); to selectCollege() function:
function selectCollege(val) {
window.event.preventDefault();
$("#college_name").val(val);
college_name = $("#college_name").val();
location.href = "college-details.php?college_name=" + college_name;
$("#box").hide();
}
There is also another error: selectCollege('".$college_name."''".$field."'); generates code selectCollege('Some college name''Some field');, which contains two apostrophes going in a row. It seems you wanted selectCollege('Some college nameSome field');, so really you should also fix the code to selectCollege('".$college_name.$field."'); or selectCollege('".$college_name."'+'".$field."');
Replace
<?php
$tempcollege .= "<a href='#' style='color:#fff;'><li onClick=selectCollege('".$college_name."''".$field."');>".$college_name.$field."</li></a>";
?>
With
<?php
$tempcollege .= "<a href='#' style='color:#fff;'><li onclick=selectCollege('".$college_name."''".$field."');>".$college_name.$field."</li></a>";
?>
$tempcollege .= "<li><a onclick='callfunction();' style='color:#fff;'>click</a></li>";
When you set click event on <a> tag at time please remove href="#" attribute with href some cases causes browser reload a page and since click event not work.
Related
$(function() {
$("#register").dialog({
autoOpen:false,
show: {
effect:"",
duration: 1000
},
hide: {
effect:"",
duration: 1000
}
});
$("#register-opener").click(function() {
$("#register").dialog("open");
});
});
<td><a id="register-opener" href="?id=<? echo "$members_row[id]"; ?>"><i class="glyphicon glyphicon-pencil" title="Edit"></i></a></td>
So what I'm trying to accomplish is to click on a link to be able to edit a certain users information, the problem is I can only get the popup to occur when replacing the href with href="#". Can someone assist. Thanks.
You need to make some changes in jQuery to achieve this.
$("#register-opener").click(function(e) {
e.preventDefault();
$("#register").dialog("open");
});
Above script will make sure that when ever user clicks on link it doesn't go to URL mentioned in href and execute following codes.
https://api.jquery.com/event.preventdefault/
If e.preventDefault() is called then default action of the
event(click in above case) will not be triggered.
There seems to be problem with dialogue function you have. Use prompt instead and be sure to remove icon inside a tag
jQuery("#register-opener").click(function() {
var person = prompt("Please enter your name", "Harry Potter");
if (person != null) {
document.getElementById("#yourid").innerHTML =
"Hello " + person + "! How are you today?";
//Or do your thing
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<a id="register-opener" href="?id=<?php echo '$members_row[id]'; ?>">
icon<i class="glyphicon glyphicon-pencil" title="Edit">
</i>
</a>
</div>
This might be better accomplished by putting your ID in a data- attribute rather than using href, which is meant to be used for specifying a URL for the web browser to follow.
<td><a id="register-opener" href="#" data-id="<? echo $members_row[id]; ?>"><i class="glyphicon glyphicon-pencil" title="Edit"></i></a></td>
You can then access the value of the data-id attribute in jQuery by using
$("register-opener").attr("data-id");
I'm working on a portfolio for someone who isn't very technically proficient at the moment. He is going to need to regularly add new content to his portfolio, which means that either he is going to need to learn how to hard code new buttons, text, and pictures into his website, or I'm going to need to regularly do this for him.
My current design for the website includes a php script that automatically populates a navigation bar based on the contents of a directory. My goal is that when a user clicks on one of the navigation buttons, it will trigger an ajax event that calls a php script to load all of the images from that particular event into my main content div. Here is the script for the nav bar:
<div id="eventsbar">
<div id="eventslistleft">
<?php
$eventlist = preg_grep('/^([^.])/', scandir('events'));
foreach($eventlist as $i => $event){
if($i == 0 || $i % 2 == 0){
echo '<div class="eventbutton" id='.$event.'><img src="/events/'.$event.'/0.jpg"></div>';
}
}
?>
</div>
<div id="infobutton">
</div>
<div id="eventslistright">
<?php
$eventlist = preg_grep('/^([^.])/', scandir('events'));
foreach($eventlist as $i => $event){
if($i != 0 && $i % 2 != 0){
echo '<div class="eventbutton" id='.$event.'><img src="/events/'.$event.'/0.jpg"></div>';
}
}
?>
</div>
</div>
The rendered HTML:
<div id="eventsbar">
<div id="eventslistleft">
<div class="eventbutton" id="fifth"><img src="/events/fifth/0.jpg"></div>
<div class="eventbutton" id="fourth"><img src="/events/fourth/0.jpg"></div>
<div class="eventbutton" id="third"><img src="/events/third/0.jpg"></div></div>
<div id="infobutton"></div>
<div id="eventslistright">
<div class="eventbutton" id="first"><img src="/events/first/0.jpg"></div>
<div class="eventbutton" id="second"><img src="/events/second/0.jpg"></div>
</div>
</div>
And here is the script to call the image load function:
<script>
$(".eventbutton").click(function(){
alert("clicked");
currentevent = this.id;
$.ajax({
type: "GET",
url: "scripts/load.php",
data: "cevt="+currentevent,
success: function(msg){
$('#Content').html(msg);
}
});
});
</script>
For whatever reason, though, the click event only triggers when I click on the last navigation button. I suspect that the click event is not triggering at all because I do not see the alert that says "clicked" when I click any navigation buttons except for the one which is rendered last. Does anyone have experience with a similar issue? Any suggestions for what I can do to correct this problem?
if($i != 0 && $i % 2 != 0){
echo '<div class="eventbutton" id='.$event.'><img src="/events/'.$event.'/0.jpg"></div>';
}
Because all the the buttons are dynamically added to the form so the event should be attached to the parent.
$("#eventslistright .eventbutton").on( "click", function() {});
or
$( "body" ).on( "click", ".eventbutton" ,function(){});
If you add navigation button dynamically in page you should use
.on() Read more ... or .live() Until version 1.7 Read more ...
$("#eventsbar .eventbutton").on( "click", function() {
alert("clicked");
currentevent = this.id;
$.ajax({
type: "GET",
url: "scripts/load.php",
data: "cevt="+currentevent,
success: function(msg){
$('#Content').html(msg);
}
});
});
DEMO
If your code loads elements dynamically then method .click wouldn't work because it is declared for elements already existing during js loading. To add some click event action for js loaded elements you must use .on with parameter 'click'. Example above:
<script>
$(function(){
$("html").on('click','.eventbutton', function(){
var currentevent = $(this).attr('id');
alert(currentevent);
$.ajax({
type: "GET",
url: "scripts/load.php?cevt=" + currentevent,
success: function(msg){
$('#Content').html(msg);
}
});
});
});
</script>
I have a page that loaded with ajax complete,
I have buttons on the page (load with ajax), so I want after click the button run an alert event,
I try bind,delegate,live,on Event to attach the Event to handler but no result.
I'm try add test btn manually and that call the event but the buttons that load via ajax not call Event.
My html code:
<body>
<a href='#' class='insert_cm'>test btn</a>
<div class="header"></div>
<div class="wrap">
<div class="rightmenu"></div>
<div class="content">
</div>
</div>
</body>
my JQuery code:
$(function(){
$(".header").load("header.html");
$(".rightmenu").load("sidebar.html");
$.ajax({
type:'POST',
url:'timeline.php',
success:function(data){
$(".content").html(data);
}
});
//insert comment after click the cm-btn
$( ".insert_cm" ).live( "click", function() {
alert( "User clicked on 'foo.'" );
})
});
and the php code:
<?php
include('db_inc.php');
include("myfunc.php");
$functionId=$_POST[functionId];
switch($functionId){
case "":
$music_query = $connection->query("SELECT * FROM music LIMIT 15") or die($connection->error);
while($music = $music_query->fetch_array()){
$music_id=$music['msuic_id'];
$music_thumb =$music['music_thumb'];
$music_name=$music['file_name'];
echo "<div class='music-item'>
<div class='music-avatar'>
<img src=admin/thumb/$music_thumb alt='avatar'>
</div>
<div class='music-post'>
<h3> $music_name <a href='#' class='like_music' >لایک</a></h3>
<p> $music_composer </p>";
$comment_query=$connection->query("SELECT * FROM comments where f_music_id = '$music_id'") or die($connection->error);
while($comments = $comment_query->fetch_array()){
$username = get_username($comments['f_user_id']);
echo "
<div class='username_comment'>
<h4> $username <span>:</span></h4>
$comments[comment];
</div>
";
}
echo "<textarea id='txt_cm' name='txt_cm'></textarea>
<a href='#' class='insert_cm'>insert comment</a>";
}
}
?>
always use $(document).on() for dynamically created element if you want to bind an event to them.
$(document).on("click", ".insert_cm", function() {
alert( "User clicked on 'foo.'" );
return false;
});
the event binder should sit on document level so that it recognize whenever there are more elements added to DOM
more info on $(document).on() : Is it possible to capture keydown globally on dynamically added text inputs?
Use .on() with updated syntax in the jQuery version > 1.8:
$(".content").on( "click",".insert_cm", function() {
alert( "User clicked on 'foo.'" );
})
Syntax:
$(selector/Closest parent).on(event,target,function(){});
That is called EventDelegation!
Where .content reffers to the closest parent element, you can also use document, document.body too.
Try:
$(document).on("click",".insert_cm",function() {
alert("User clicked on 'foo.'");
return false;
});
i have a while loop in my coding
while (($i < $num3b)&&($i < ($start+$perpage))) {
$tododetail_id=mysql_result($result3b,$i,"tododetail_id");
$comment=formatUrlsInText(mysql_result($result3b,$i,"comment"));
$staff_name=mysql_result($result3b,$i,"staff_name");
echo "<tr><td><span><font color='#5858FA'>" . $staff_name . nl2br($comment) . "</font>
<span style='float:right' id='create-user'>Reply Message</span>";
$i++;}
How can onclick "Reply Message" jquery will popup $staff_name and $comment accordingly.
This is my jquery code
$( '[id^="create-user"]')
.click(function() {
var nameStf = $(this).data('id');
alert (nameStf);
$( "#dialog-form" ).dialog( "open" );
});
Thanks
You could use the data-attributes
HTML
<span style='float:right' class="reply" data-staffname="staffname" data-comment="staff comment">Reply Message</span>
jQuery
$(document).ready(function() {
$('span.reply').click(function() {
var staffname = $(this).data('staffname');
var comment = $(this).data('comment');
alert(staffname + ': ' + comment);
});
});
When you echo tags, I can't see you are closing them anywhere. Your HTML must be correct in order for jQuery to work properly. Also ID must be unique so use class.
HTML
<tr>
<td>
<span style="color: #5858FA;">SOMETHING 2</span>
<span class="create-user">Reply Message</span>
</td>
</tr>
JS
$('.create-user').click(function(){
var $text = $(this).prev().text();
alert($text);
});
DEMO
Your HTML is a mess, and your jQuery doesn’t correspond with it. You have this line:
$( "#dialog-form" ).dialog( "open" );
But you haven’t shown us any HTML that includes an element with the ID dialog-form.
You should restructure your HTML so you don’t use the font tag, every ID is unique, and tags are properly nested and closed. Run your output HTML through the validator if you’re not sure.
Then, you can do something like this:
$('span').click(function(){
alert($(this).closest('.comment'));
});
Obviously you’ll have to put the comment data in an element with the class comment.
Also, if you want to select an element by its ID with jQuery:
// Incorrect
$('[id^="create-user"]')
// Correct
var $createUser = $('#create-user');
// Also correct (normal JavaScript)
var createUser = document.getElementById('create-user');
id must be unique give it as something like the id from the database. Then put the jquery script inside the loop. or else in the html use a onclick function which passes the id to the JavaScript function.
<?php
echo "<tr><td><span><font color='#5858FA'>" . $staff_name . nl2br($comment) . "</font>
<span style='float:right' id="<?php echo $row['id'];">Reply Message</span>";
$i++;
?>
<script type="text/javascript">
$( "#<?php echo $row['id']; ?>")
.click(function() {
var nameStf = $(this).data('id');
alert (nameStf);
$( "#dialog-form" ).dialog( "open" );
});
</script>
<?php }?>
Try not to use html inside an echo statement since echo is a php statement which loads from the server which is slower than normal html which loads in the browser.
I've got this problem that I can't solve. Partly because I can't explain it with the right terms. I'm new to this so sorry for this clumsy question.
Below you can see an overview of my goal. I want to search some stuff from a database (with ajax) and display the results in a div below the search. This I can get this to work. But now, I want to be able to click on a result and get it in a div on top of the page.
I learned it is normal that ajax can not handle this sort of actions and it is not possible to run jquery or other ajax-calls into an ajax-call.
I also read things about jquery live() to work around this problem.
Still it is not clear to me how to make things work.
Is it possible to put me on the right track? Are there tutorials I missed?
thank you!
step one
<div id="top">here comes an image</div>
<textfield> for the ajax search string + a button </textfield>
<div id="search">target of the ajax-search</div>
step two: after a search we get this
<div id="top">here comes an image</div>
<textfield> for the ajax search string + a button </textfield>
<div id="search">result 01 with link to a php-file: a
result 02 with link to a php-file: b ... </div>
step tree: after click on result 01 or 02 ...
<div id="top">content of php-file: a</div>
<textfield> for the ajax search string + a button </textfield>
<div id="search">result 01 with link to a php-file: a
result 02 with link to a php-file: b ... </div>
ok, here comes part of the (relevant) code
search_page.php
<div id=top"></div>
<div class="client_search_field">
<form id="ui_element" class="sb_wrapper" action="" method="post" name="search_ID" ONSubmit="xmlhttpPost('search_stream_client_v02.php', 'ui_element', 'txtHint', '<img src=\'images/wait.gif\'>'); return false;">
<p> <span class="sb_down"></span>
<input name="search_string" type="text" class="sb_input" id="search_string" value="<?php echo $_POST['search_string']; ?>"/>
<button type="submit" class="submitmag" id="search_submit" > </button>
</p>
</div>
<span id="txtHint"></span>
search_stream_client_v02.php
<?php
$sql .= "SELECT *";
$sql .= ", MATCH(description, keywords) AGAINST ('".$_POST['search_string']."') AS score FROM archief WHERE MATCH(description, keywords) AGAINST('".$_POST['search_string']."' IN BOOLEAN MODE)";
$sql .= " AND showa = '1' ";
$sql .= $q_sort." ".$q_order." LIMIT 0,".$q_num_result;
$result04 = mysql_query($sql) or die(mysql_error());
while ($row04 = mysql_fetch_assoc($result04)){
$hint .= "<div class=\"tb-kader\">";
$hint .= "<span id=\"".$row['thumbnail']."\">";
$hint .= "<a href=\"".$row04['link']."\" class=\"fra tooltip lazy\" id=\"".$row04['ID']."\" TITLE=\"header=[".$row04['headline']."] body=[".$row04['description']."]\">";
$hint .= "<img src=\"$row04[thumbnail]\" border=\"0\" alt=\"".$row04['headline']."\"/></a>";
$hint .= "<div class=\"tb-kader-price\">".$pic_list_solo_final[$items03]['prijs']." €</div></span>";
$hint .= "</div>";
}
echo $hint;
?>
so, at the end the
<a href=\"".$row04['link']></a>
should open in the
<div id="top"></div>
thank you guys for your effort!!
EDIT
This one is not working:
$('#search').delegate(".fra", "click", function() {
$("#top").attr("src","href");
});
$('#search').delegate(".fra", "click", function() {
$("#top").attr("src","href");
});
What this does is just setting the scr attribute of #top to "href". That's not what you want ;) What you need is, I think:
$('#search').delegate(".fra", "click", function() {
var link = $(this),
url = link.attr("href");
$.ajax({
url: url,
dataType: "html",
success: function(data) {
$("#top").html(data);
}
})
});
so you want to do something like:
$('.search-result-class').live('click', function() {
//this binds to the click of each result. So you can do an ajax call here and on the success callback you could then load the result into the div
});
Or you can use .delegate, like this:
html
<div id="search">
result 01 with link to a php-file: a
result 02 with link to a php-file: b ...
</div>
js
// binds a click event on each result, even if they've been loaded via ajax
$('#search').delegate(".result", "click", function() {
var link = $(this),
url = link.attr("href");
// do your ajax magic...
$.ajax({url: url...})
});
It's basically the same idea than Victor's answer, but .delegate is more performant I think.