Different Jquery hover popup divs on different links - php

I've a php for loop which finds data from an Json object, and creates based on these information different divs and different links:
echo $remoteTownFB . " - " .
"<a href=\"#\" id=" . $remoteTownFB . "_trigger>" .$eventName . "</a></br>";
After that, I wrote a Java Script to create different divs (with different names) wich should pop up on mouseover (with a Jquery Script)
<script type="text/javascript">
var samplediv = document.createElement('div');
samplediv.id = '<?php echo $remoteTownFB . "_info" ?>';
var txt = document.createTextNode("Informationen über: <?php echo $eventName?>");
document.getElementById('pop-up').appendChild(samplediv);
document.getElementById('pop-up').appendChild(txt);
</script>
My problem is now the Jquery Script. I tried around with $.each on an Array where every Town name is in, but I couldn't figure it out.
This is my base:
$(function() {
var moveLeft = 20;
var moveDown = 10;
$('a#trigger').hover(function(e) {
$('div#pop-up').show().;
}, function() {
$('div#pop-up').hide();
}
);
$('a#trigger').mousemove(function(e) {
$("div#pop-up").css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);
});
});
Any help or ideas?

First of you forgot to close the id-property:
echo $remoteTownFB . " - " .
"" .$eventName . "</br>";
Then, for the pop-up to work you could try:
<script type="text/javascript">
var samplediv = document.createElement('div');
samplediv.id = '<?php echo $remoteTownFB . "_info" ?>';
samplediv.style.display = 'none';
var txt = document.createTextNode("Informationen über: <?php echo $eventName?>");
samplediv.appendChild(txt);
document.getElementById('pop-up').appendChild(samplediv);
</script>
The jquery part would be:
<script type="text/javascript">
$(function() {
$('a[id$="_trigger"]').hover(
function() {
var targetSelector = '#' + this.getAttribute('id').replace('_trigger', '_info');
$('#pop-up, ' + targetSelector).show();
},
function() {
var targetSelector = '#' + this.getAttribute('id').replace('_trigger', '_info');
$('#pop-up, ' + targetSelector).hide();
}
);
});
</script>
I'm not really sure what you are trying to do with the mousemove call so I left that alone.

Related

using array push in jquery by accessing php array variable

this is my php code:
if (($_SERVER["REQUEST_METHOD"] == "POST")&&(isset($_POST["btn_save"]))) {
$schoolsInput=$_POST['schoolsInput'];
echo $schoolsInput[0];
}
this is my jquery code:
<script type="text/javascript">
$(document).ready(function()
{
var counter=1;
var max_fields=5;
var add_button = $("#btn_addTxt");
var save_btn= $("#btn_save");
var wrapper= $("#prevSchoolTable");
$(add_button).click(function(e){
e.preventDefault();
if (counter == max_fields) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
$(wrapper).append('<tr><td><input type="text" name="schoolsInput' + counter + '" id="schoolsInput' + counter + '" class="textbox" style="width:400px;">'
+ '</td></tr>');
counter++;
}
});
var arrayFromPHP = <?php echo json_encode($schoolsInput); ?>;
$("#btn_save").click(function () {
var msg = '';
for(i=1; i<counter; i++){
msg += "\n " + $('#schoolsInput' + i).val();
}
alert(msg); \\array push must go here
});
});
</script>
I've search how can i access PHP variable and they say to use:
var obj = <?php echo json_encode($schoolsInput); ?>;
But everytime i put this on my jquery, the ADD function is not working.
any suggestion?

Words trimmed tooltip jquery

Basically I want my tooltip to display company names once company_id is being hovered. However instead of displaying "Company A" for example, it just displays "Company". I realized that it's just printing everything before a space.
Here's the script:
<script type="text/javascript">
$(document).ready(function() {
// Tooltip only Text
$('.masterTooltip').hover(function(){
// Hover over code
var title = $(this).attr('title');
$(this).data('tipText', title).removeAttr('title');
$('<p class="tooltip"></p>')
.text(title)
.appendTo('body')
.fadeIn('slow');
}, function() {
// Hover out code
$(this).attr('title', $(this).data('tipText'));
$('.tooltip').remove();
}).mousemove(function(e) {
var mousex = e.pageX + 20; //Get X coordinates
var mousey = e.pageY + 10; //Get Y coordinates
$('.tooltip')
.css({ top: mousey, left: mousex })
});
});
</script>
and here's my codes
<?php
$companyCtrl = new company_controller();
$companyInfoArr = $companyCtrl->retrieveAllCompanyInfo();
foreach($companyInfoArr as $info) {
$company_id = $info->getCompanyID();
$company_name = $info->getCompanyName();
echo "<a href='#' title=".$company_name." class='masterTooltip'>".$company_id."</a> <br>";
}
?>
There's not problem when i manually enter the text like this
Your Text
In this line:
echo "<a href='#' title=".$company_name." class='masterTooltip'>".$company_id."</a> <br>";
You need to add quotes around the title, so the HTML you're generating will be properly formed. Like this:
echo "".$company_id." <br>";

JQuery ignoring click() and change()

Advance note: I have already looked at and looked at and tried the solutions in the SO question: Jquery checkbox change and click event. Others on SO deal more with reading the values rather than the issue that the event is not firing.
I will admit that I am a relative newbie to JQuery.
I am trying to make two changes. One when a text field changes and one when a checkbox is toggled. Both are within a form. The idea is that if the text field changes a computation is done and the return value is written into the text after the checkbox. The checkbox toggles that text on and off.
Once finished the form can be submitted.
the code (as seen below) also uses php.
I've pulled the relevant code. I read several examples on line so there is are attempts using
<span id="foo"><input></span>
<input class='romanCheck' id='romanCheck' type='checkbox'>
Neither alert is being called. JSFiddle kinda barfed on the PHP. For the checkbox I've tried both .change() and .click()
The browsers I've tested on are all Mac (my dev environ)
Safari: 7.0.3 (9537.75.14)
Chrome: 33.0.1750.152
Firefox: 28.0
I've attached the relevant code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Not Working.php</title>
<link rel="stylesheet" href="jquery-ui-1.10.4.custom/css/ui-lightness/jquery-ui-1.10.4.custom.css">
<script src="jquery-ui-1.10.4.custom/js/jquery-1.10.2.js"></script>
<script src="jquery-ui-1.10.4.custom/js/jquery-ui-1.10.4.custom.js"></script>
</head>
<body>
<script>
function romanize (num) {
return "(" + "roman for " + ")";
}
$(document).ready(function(){
$(".romanCheck").live("change",function() {
alert("#romanCheck.click has been hit");
var romanValue = "";
var roman = $("#romanCheck").is(':checked');
if ( roman ) {
var itValue = $(this).val();
romanValue="(" + romanize(itValue) +")";
}
$("#romanDisplay").text(romanValue);
});
$("span.iterationField input").live("change",function() {
alert("#iteration.change has been hit");
var romanValue = "";
var roman = $("#romanCheck").is(':checked');
if ( roman ) {
var itValue = $(this).val();
romanValue="(" + romanize(itValue) +")";
}
$("#romanDisplay").text(romanValue);
});
});
</script>
<form action='EventValidateProcess.php' method='post'>
<?php
$doesShow = 1;
$isRoman = 1;
$iteration - 13;
print "<table>\n";
print "<tr>\n\t<td>Iteration</td>\n\t";
print "<td><span id='iterationField'><input type='text' name='iteration' value='" . $iteration . "'></span></td>\n\t";
print "<td><input type='checkbox' name='doesShow' value='1'";
if ($doesShow == 1) {
print " checked";
}
print "> visible | ";
print "\n<input class='romanCheck' id='romanCheck' type='checkbox' name='isRoman' value='1'";
if ($isRoman == 1) {
print " checked";
}
print "> uses Roman numerals\n";
print "<span id='romanDisplay'>(XX)</span></td>\n</tr>\n";
?>
</table>
<button type='submit' name='process' value='update'>Update</button><br/>
</form>
</body>
.live() deprecated: 1.7, removed: 1.9
Use .on() as you are using jquery-1.10.2
Syntax
$( elements ).on( events, selector, data, handler );
$(document).on("change", "span.iterationField input" ,function() { //code here });
$(document).on("change", ".romanCheck" ,function() { //code here });
span.iterationField is not exist, instead span#iterationField,
and just use:
$(document).ready(function(){
$("input.romanCheck").on("change",function() {
alert("#romanCheck.click has been hit");
var romanValue = "";
var roman = $("#romanCheck").is(':checked');
if ( roman ) {
var itValue = $(this).val();
romanValue="(" + romanize(itValue) +")";
}
$("#romanDisplay").text(romanValue);
});
});
Note: make sure jquery library in imported
After a lot of finessing it seemed the answer that worked best was the following:
$(document).change("input.romanCheck", function() {
var romanValue = "";
var roman = $("#romanCheck").is(':checked');
if ( roman ) {
var itValue = $("#iterationField").val();
romanValue="(" + romanize(itValue) +")";
}
$("#romanDisplay").text(romanValue);
});
$(document).change("input.iterationField", function() {
var romanValue = "";
var roman = $("#romanCheck").is(':checked');
if ( roman ) {
var itValue = $("#iterationField").val();
romanValue="(" + romanize(itValue) +")";
}
$("#romanDisplay").text(romanValue);
});
Using:
print
"<input id='iterationField' type='text' name='iteration' value='";
print $iteration . "'/>";
print
"<input id='romanCheck' type='checkbox' name='isRoman' value='1'";
if ($isRoman == 1) {
print " checked";
}
print ">";
print "<span id='romanDisplay'>";
if ($isRoman == 1) {
print "(" . $romanIteration . ")";
}
print "</span>";
Im not sure what is your problem but try this.
function romanclick(){
//if event fire twice use namespace at 1. and 2. and put $(document).off('namespace') here
//your code romanclick
$('span.iterationField input').click(function(){
textchange();// call it again
});
}
function textchange(){
//if event fire twice use namespace at 1. and 2. and put $(document).off('namespace') here
//change text code
$('.romancheck').click(function(){
romanclick();// call it again
});
} ;
1.$(document).on("change", "span.iterationField input" ,function() { //call your function here });
2.$(document).on("change", ".romanCheck" ,function() { //call your function here });

Function Calls for Dynamically Loaded Content

I have a PHP file that serves up some HTML populated from a MySQL database and is loaded into the DOM. This data is loaded via jQuery load() method into the #navContent divide of the HTML document. This functions as planed.
At the very-bottom of the HTML doc, I have a click function that targets the #navItem div (see the first echo line of the php file) that was dynamically loaded into the DOM but this does not fire. I know the #navItem tag ID is there because my CSS styles it correctly.
What do I have wrong? For now, I just want all the divides that were dynamically created into the #navContent div to click thru to a URL.
I am a newB and just learning jQuery so corrected code would be very helpful. Thnx
In the HTML:
<html>
<head>
<script type="text/javascript">
. . .
var ajaxLoader = '';
var dns = 'http://www.someURL';
var navContent = '/folder/my_list.php';
var bodyContent = '/folder/index.php/somestuff #content';
$(document).ready(
function() {
loadPage(dns + navContent, "navContent");
loadPage(dns + bodyContent, "bodyContent")
});
. . .
</script>
. . .
</head>
<body>
. . .
<div id="navPanel">
<div id="navHeader">
<img src="images/ic_return.png" style="float: left;"/>
<img id="listSortBtn" src="images/ic_list_sort.png" style="float: right;"/>
<h4 id="navHeaderTitle"></h4>
</div>
<div id="navScrollContainer" class="navContentPosition">
<div id="navContent">NAVIGATION CONTENT GETS DUMPED IN HERE</div>
</div>
</div>
. . .
</body>
<!-- ================ Functions ===================================== -->
<!-- **************************************************************** -->
<script type="text/javascript">
/* --------------- Handle Pg Loading ----------------- */
function loadPage(url, pageName) {
$("#" + pageName).load(url, function(response){
$('#navHeaderTitle').text($(response).attr('title'));
// transition("#" + pageName, "fade", false);
});
};
/* ------------- Click Handler for the Nav Items------ */
$("#navItem").click(function(e) {
e.preventDefault();
var url = 'http://www.google.com';
var pageName = 'navContent';
loadPage(url, pageName);
});
. . .
</script>
</html>
Served PHP File:
<?php
$con = mysql_connect("localhost","root","pw");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("andaero", $con);
$result = mysql_query("SELECT * FROM some_list");
while($row = mysql_fetch_array($result))
{
echo "<div id='navItem' title='My Nav Title'>";
echo "<h1>" . $row['label'] . "</h1>";
echo "<h2>" . $row['title'] . "</h2>";
echo "<p>" . $row['description'] . "</p>";
echo "</div>";
}
mysql_close($con);
?>
You need to initialize that click method AFTER the DOM has been appended with your custom markup. This is a perfect example of a case where OOP programming would do wonders.
You also didn't load the click method into the doc-ready...
<script type="text/javascript">
function MyConstructor()
{
this.ajaxLoader = '';
this.dns = 'http://www.someURL';
this.navContent = '/folder/my_list.php';
this.bodyContent = '/folder/index.php/somestuff #content';
this.loadPage = function( url, pageName )
{
$("#" + pageName).load(url, function(response){
$('#navHeaderTitle').text($(response).attr('title'));
});
this.toggles();
}
this.toggles = function()
{
var t = this;
$("#navItem").click(function(e) {
e.preventDefault();
var url = 'http://www.google.com';
var pageName = 'navContent';
t.loadPage(url, pageName);
});
}
/**************************************
*Init Doc-Ready/Doc-Load methods
**************************************/
this.initialize = function()
{
this.loadPage( this.dns + this.navContent, "navContent");
this.loadPage( this.dns + this.bodyContent, "bodyContent");
}
this.initialize();
}
$( document ).ready( function(){
var mc = new MyConstructor();
//now, you can go ahead and re-run any methods from the mc object :)
//mc.loadPage( arg, 'ye matey' );
});
</script>

how to get result from mysql and display using jquery when radio button is clicked?

I would like to make a bus seating plan. I have seating plan chart using javascript function.I have two radio button named Bus_1 and Bus_2 queried from databases. When I clicked one of radio button, I would like to get available seats to show on the seating plan. Problem is I can't write how to carry radio value and to show database result on seating plan. Please help me.
<SCRIPT type="text/javascript">
$(function () {
var settings = { rowCssPrefix: 'row-', colCssPrefix: 'col-', seatWidth: 35, seatHeight: 35, seatCss: 'seat', selectedSeatCss: 'selectedSeat', selectingSeatCss: 'selectingSeat' };
var init = function (reservedSeat) {
var str = [], seatNo, className;
var shaSeat = [1,5,9,13,17,21,25,29,33,37,41,'#',2,6,10,14,18,22,26,30,34,38,42,'#','$','$','$','$','$','$','$','$','$','$',43,'#',3,7,11,15,19,23,27,31,35,39,44,'#',4,8,12,16,20,24,28,32,36,40,45];
var spr=0;
var spc=0;
for (i = 0; i<shaSeat.length; i++) {
if(shaSeat[i]=='#') {
spr++;
spc=0;
}
else if(shaSeat[i]=='$') {
spc++;
}
else {
seatNo = shaSeat[i];
className = settings.seatCss + ' ' + settings.rowCssPrefix + spr.toString() + ' ' + settings.colCssPrefix + spc.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) { className += ' ' + settings.selectedSeatCss; }
str.push('<li class="' + className + '"' +'style="top:' + (spr * settings.seatHeight).toString() + 'px;left:' + (spc * settings.seatWidth).toString() + 'px">' +'<a title="' + seatNo + '">' + seatNo + '</a>' +'</li>');
spc++;
}
}
$('#place').html(str.join(''));
}; //case I: Show from starting //init();
//Case II: If already booked
var bookedSeats = [2,3,4,5]; //**I don't know how to get query result in this array.This is problem for me **
init(bookedSeats);
$('.' + settings.seatCss).click(function () {
// ---- kmh-----
var label = $('#busprice');
var sprice = label.attr('pi');
//---- kmh ----
// var sprice= $("form.ss pri");
if ($(this).hasClass(settings.selectedSeatCss)){ alert('This seat is already reserved'); }
else {
$(this).toggleClass(settings.selectingSeatCss);
//--- sha ---
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) { item = $(this).attr('title'); str.push(item); });
var selSeat = document.getElementById("selectedseat");
selSeat.value = str.join(',');
//var amount = document.getElementById("price");
// amount.value = sprice*str.length;
document.getElementById('price').innerHTML = sprice*str.length;
return true;
}
});
$('#btnShow').click(function () {
var str = [];
$.each($('#place li.' + settings.selectedSeatCss + ' a, #place li.'+ settings.selectingSeatCss + ' a'), function (index, value) {
str.push($(this).attr('title'));
});
alert(str.join(','));
})
$('#btnShowNew').click(function () { // selected seat
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) { item = $(this).attr('title'); str.push(item); });
alert(str.join(','));
})
});
</SCRIPT>
You can use the onclick to tell AJAX to get your information and then what to do with it using jQuery.
<input type="radio" name="radio" onclick="ajaxFunction()" />
function ajaxFunction()
{
$.ajax({
type: "POST",
url: "you_script_page.php",
data: "post_data=posted",
success: function(data) {
//YOUR JQUERY HERE
}
});
}
Data is not needed if you are not passing any variables.
I use jQuery's .load() function to grab in an external php page, with the output from the database on it.
//In your jQuery on the main page (better example below):
$('#divtoloadinto').load('ajax.php?bus=1');
// in the ajax.php page
<?php
if($_GET['bus']==1){
// query database here
$sql = "SELECT * FROM bus_seats WHERE bus = 1";
$qry = mysql_query($sql);
while ($row = mysql_fetch_assoc($qry)) {
// output the results in a div with echo
echo $row['seat_name_field'].'<br />';
// NOTE: .load() takes this HTML and loads it into the other page's div.
}
}
Then, just create a jQuery call like this for each time each radio button is clicked.
$('#radio1').click(
if($('#radio1').is(':checked')){
$('#divtoloadinto').load('ajax.php?bus=1');
}
);
$('#radio2').click(
if($('#radio1').is(':checked')){
$('#divtoloadinto').load('ajax.php?bus=2');
}
);

Categories