I am loading html with javascript from php to a div using $.get() to a div. the button click event is working fine. then adding again same thing again to different div with different id, but it is not working. can anyone can help me. my code is this
<style>
.loadWindow {
width:333px;
height: 202px;
padding: 5px 5px 0 5px;
font: 12px Arial, Helvetica, sans-serif;
border:double;
}
#loadWindow {
display:none;
}
<div id="main-box">
<div class="loadWindow" id="loadWindow"></div><button id="make">make</button>
My javascript code is below
$(function(){
$('#make').click(function(){
var id = $('.loadWindow').length;
var aw = $('#loadWindow').clone().attr("id", "window"+id);
//load data from php
$.get("mydata.php", function(data) {
aw.html(data);
$('#main-box').append(aw);
aw.show();
}, 'json');
});
});
`
My mydata.php code is below
echo '<div><button id="closeBtn">Close</button></div><script>$("#closeBtn").click(function(){alert("Close button Clicked!");});</script>';
I want click event work for each window separately(individually) and display the alert. In this code click event is not working according to the window. What can I do?
Working demo http://jsfiddle.net/QYEWs/13/
Please use .on API to it attaches an event handler function for one or more events to the selected elements.
API: http://api.jquery.com/on/
Plz Note: your append will make the DOM invalid as your id will always be same make it a class
to attach click event on dynamically added html in DOM
This should help, :)
like this
Attaché click event to close button like this:
$("#main-box").on("click",".closeBtn", function() {
alert("Close button Clicked!");
});​
$(function(){
$('#make').on('click', function(){
var id = $('.loadWindow').length;
var aw = $('#loadWindow').clone().attr("id", "window"+id);
//load data from php
$.get("mydata.php", function(data) {
aw.html(data);
$('#main-box').append(aw);
aw.show();
}, 'json');
});
});
$(function(){
$('#make').click(function(){
var id = $('.loadWindow').length;
var aw = $('#loadWindow').clone(true).attr("id", "window"+id);
//load data from php
$.get("mydata.php", function(data) {
aw.html(data);
$('#main-box').append(aw);
aw.show();
}, 'json');
});
});
Related
i have image set div tag like below:
function printImg() {
pwin = window.open(document.getElementById("mainImg").src,"_blank");
window.print();
}
$(function () {
$("#gallery > img").click(function () {
if ($(this).data('selected')) {
$(this).removeClass('selected');
$(this).data('selected', false);
} else {
$(this).addClass('selected');
$(this).data('selected', true);
}
});
var selectedImageArray = [];
$('#gallery > img').each(function () {
if ($(this).data('selected')) {
selectedImageArray.print(this);
}
});
window.onafterprint = function(){
window.location.reload(true);
}
});
img.selected {
border: 3px solid green;
}
img:hover {
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="gallery" id="gallery">
<img name=imgqr[] id="mainImg" src="data:image/png;base64, {!! base64_encode(QrCode::format('png')->size(180)->generate($user->emp_code[$i])) !!} " width="100"; height="80"; >{{$user->emp_first_name}} {{$user->emp_last_name}} {{!!($user->dpt_name)!!}}</td></tr>
</div>
<input class="printMe" type="button" onclick="printImg()" value="printMe" />
i need to select image when user click on it, i added the script for this and it working, but i click print button it doesnt print qrcode image ,in meantime is printing whole page.
I also need check if image is selected and pass through array value to print seleted images +data name.
Window.print() will always print the entire current window. You could bypass this by adding the selected images to a pop up and then print that pop up.
popup = window.open();
popup.document.write("imagehtml");
popup.focus(); //required for IE
popup.print();
You can do this one window for one photo but ofcourse you can also add multiple photo's to one screen and then print it.
Your second question asks for an array with the selected images. Because you use jQuery you can just get them by
allSelectedImages = $('.selected');
You can loop that array en call the function .data() on it to get all data attributes!
Hope this helps!
You're calling print on the main window, call print from the window you opened
function printImg() {
pwin = window.open(document.getElementById("mainImg").src,"_blank");
pwin.print();
}
I do not think if there is any problem with your codes,
try this and let me know
Firefox :
Google Chrome:
I am trying to make a quote form appear on click, the element is first prepended it then needs to run through ajax to get the content for the element
HTML
<input type="button" class="used_result_icon used_result_nav_enquire" car="'.$full_listing_name.'" />
CSS
#used_car_quote {background:#fff; border:2px solid #bebebe; border-radius:5px; display:none; font-size:20px; left:500px; min-height:350px; position:fixed; width:640px; z-index:100;}
AJAX
$(document).on("click", ".used_result_nav_enquire", function() {
car = $(this).attr('car');
$('#used_car_quote').show();
$('#used_results_sort').prepend('<div id="used_car_quote"></div>');
$.ajax({
type : 'POST',
url : 'http://localhost/carprice/ajax/used-quote-results.php',
data : 'car='+car,
success : function(data) {
$("#used_car_quote").html(data);
}
});
});
Its very strange, I click on the button once, and nothing happens, then I click again, and the form appears.
Use this code in AJAX Success $('#used_car_quote').show();
$(document).unbind("click").bind('click', ".used_result_nav_enquire", function() {
car = $(this).attr('car');
$('#used_results_sort').prepend('<div id="used_car_quote"></div>');
$.ajax({
type : 'POST',
url : 'http://localhost/carprice/ajax/used-quote-results.php',
data : 'car='+car,
success : function(data) {
$("#used_car_quote").html(data);
$("#used_car_quote").show();
}
});
});
I am trying to style it as well, but this is very strange, if I click on it once, then it is not positioned right, close it then click again, and it is
$(document).on("click", ".used_result_nav_enquire", function() {
win_width = $(window).width();
form_width = $('#used_car_quote').width();
left = (win_width-form_width)/2;
win_height = $(window).height();
form_height = $('#used_car_quote').height();
top = (win_height-form_height)/2;
car = $(this).attr('car');
$('#used_results_sort').prepend('<div id="used_car_quote">test</div>');
$('#used_car_quote').css({'left':left,'top':top});
$.ajax({
type : 'POST',
url : 'http://localhost/carprice/ajax/used-quote-results.php',
data : 'car='+car,
success : function(data) {
$("#used_car_quote").html(data);
$('#used_car_quote').show();
}
});
});
So I'm having a little issue. I am working on a site and this is the first I have used ajax to post to to a page. I have a form with a submit button and a link on it. When the submit button is pressed everything works but users should be able to click the link to by pass a page but I still need some information posted to that page so I googled ho to post with out a submit button and ajax came up so I figured I'd give it a shot. It seems to not be working. Here is the code that I am using.
$('#chkEndAccDate').click(function(evt){
alert("before ajax");
var totalcost = $('#total_cost').val();
$.ajax({
type: "POST",
url: "http://sandbox.phareconsulting.com/complete_order.php",
`enter code here`data: {cost : totalCost}
});
alert("after ajax");
});
This code also doesn't work when i try it
$(document).on('click','#chkEndAccDate',function(){
cost = $('#total_cost').val();
$.post("http://www.sandbox.phareconsulting.com/complete_order.php",
{cost: cost},function(d){
alert("post");
});
});
In the php file right now I am simply doing print_r($_POST); but the post array is empty. Can some one please help me out. I think that some of us just don't understand ajax correctly. I thought I did but I am not able to get it to work.
Thank you.
This should be proper syntax:
data: "{'cost':'" + cost+ "'}"
Use this
data:{cost: cost}
for sending the data.
Use this code:
$(document).on('click','#chkEndAccDate',function(){
cost = $('#total_cost').val();
$.post("http://sandbox.phareconsulting.com/complete_order.php",
{cost: cost},function(d){
});
});
s.d and Thiefmaster have already written the correct syntax, however, it may be a good idea to change the name of your variable so as to avoid confusion.
var totalCost = $('#total_cost').val();
Then use:
data: {cost : totalCost}
Its a good idea to use the jQuery Form Plugin to send ajax forms this will by itself grab the data and send it to the form action url.
This plugin also gives you functions that control the sending process . This is an example :
var bar = $('#progressBar');
var percent = $('#percent');
var status = $('#status');
$('#form-id').ajaxForm({
beforeSend: function() {
//validate the data
status.empty();
var percentVal = '0%';
bar.width(percentVal);
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
// draw a progress bar during ajax request
var percentVal = percentComplete + '%';
bar.width(percentVal);
percent.html(percentVal);
},
complete: function(xhr) {
bar.width("100%");
percent.html("100%");
}
});
Html for the progress bar :
<div id="progress">
<div id="bar"></div >
<div id="percent">0%</div >
</div>
css :
#progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
#bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
#percent { position:absolute; display:inline-block; top:3px; left:48%; }
var count=0;
function createOne() {
var divTag = document.createElement("div");
dynamically created div
var br= document.createElement("br");
count++;
divTag.id = "div1"+count;
Id increment +1
divTag.setAttribute("align", "center");
divTag.style.margin = "0px auto";
divTag.style.width="430px";
divTag.style.height="35px";
divTag.style.background="olive";
divTag.className = "dynamicDiv";
divTag.innerHTML = "This HTML Div tag created "
+ "using Javascript DOM dynamically.";
document.body.appendChild(divTag);
document.body.appendChild(br);
}
> Need to save in php using Jquery.
<body>
<h1 align="center">
Click it
<input type="button" id="dev" onClick="createOne()" value="GET">
</h1>
</body>
If you are using jQuery then use it. Convert your function to jQuery and use jQuery's ajax functions.
JavaScript
jQuery(function($){
$('#dev').click(function(){ createOne(); });
window.count = 0;
function createOne() {
var new_id = 'div1' + (++count);
$('body').append('<div class="dynamicDiv" id="' + new_id + '" style="margin: 0px auto; width: 430px; height: 35px; background-color: olive;">This HTML Div tag created using Javascript DOM dynamically.</div><br/>');
$.get('/div-id-saver.php', { 'id': new_id }, function(response){
console.log('post response:' + response);
});
}
});
HTML
<body>
<h1>
Click it
<input type="button" id="dev" value="GET">
</h1>
</body>
More info: http://api.jquery.com/category/ajax/shorthand-methods/
In your createOne() function, you can do an AJAX post back to a PHP script passing through the ID of the element you just created.
You can find more information on JQuery's AJAX here
You haven't specified what you want to do with the information or when so this should help to get started.
In the ajax call, the data will look like:
var mydata = new Array ();
$("div[id^='div']").each (function (){
mydata.push ({$(this).attr ("id") : $(this).text ()});
});
I use the text of the div as the value, but you can change it to your needs...
I suggest you post the data by Ajax
createOne = function() {
var $div = $('#div1'+count);
$.ajax({
type: "POST",
url: "some.php",
data: { id: "div1"+count, html: $div.html() }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
** Using jQuery **
// Within your createone() function
// Location of your PHP file
var url = 'savemyvar.php';
$.post(url, { div : divTag.id }).success(function(data, status, xhr)
{
// Do something on success
}).error(function(data)
{
// Do something on error
});
Info on $.post a helper function for $.ajax
$.ajax documentation
This will send your divTag object to the PHP script that you can use
$_REQUEST['div']
to access.
Im a beginner in PHP, MYSQL, JQUERY.
I intended to load a photo gallery (ul) into a div.
The following snippet works well and the style applied to that element and its children works too.
The WHERE clause is enough to load 12 pictures with only one parameter (TabFotosVisivel=1).
Please check the following snippets out:
INDEX.PHP
<div id="idDivTC">
<ul>
$result = mysql_query("SELECT * FROM TabFotos WHERE TabFotosVisivel=1 ORDER BY TabFotosID DESC LIMIT 0,12");
while($row = mysql_fetch_array($result)){
$caminhoArquivo=$row["TabFotosCamArqMini"];
$descricao=$row["TabFotosDescricao"];
$titulo=$row["TabFotosTitulo"];
echo("<li><img class='claFotoMiniatura' src='".$caminhoArquivo."' title='".$titulo."' alt='".$descricao."'></li>");
}//fim do while
</ul>
</div><!-- /idDivTC -->
//-----------style of index.php------------------------
#idDivTC ul li {
display:inline;
}
#idDivTC ul li img{
margin:1px;
float:left;
}
Now I would like to load into the same structure another gallery and I use Jquery to call a page with pure PHP.
The additional parameter to WHERE clause id 'idLido'.
The code is
//------------- jquery of index.php----------------------
$(".claSubMenu").click(function (){
var idLido=$(this).attr("alt");
$.post("miniatura.php", { idLido:idLido})
.done(function(data) {
var arrayRetorno=new Array();
arrayRetorno=data.split("#");
for (i=0;i<arrayRetorno.length;i++){
$("#idDivTC ul").append(arrayRetorno[i]);
}
});
});
MINIATURA.PHP
<?php
require_once("bd.php");
$idLido=$_POST['idLido'];
$sentenca = "SELECT * FROM TabFotos WHERE TabFotosFKGalerias = ".$idLido." AND TabFotosVisivel=1";
$result = mysql_query($sentenca);
while ($row = mysql_fetch_array($result)){
$titulo=$row['TabFotosTitulo'];
$descricao=$row['TabFotosDescricao'];
$caminhoArquivo=$row['TabFotosCamArqMini'];
$retorno=$retorno."<li><img class='claFotoMiniatura' src='".$caminhoArquivo."' title='".$titulo."' alt='".$descricao."'></li>#";
}
echo $retorno;
mysql_close($con);
?>
After retrieve data, Jquery/javascript convert it into an array.
This is my point: I would like, as I said, to read each value of this array and append it to the that element/list, when I invoke
$(".claSubMenu").click(function (){
through
for (i=0;i<arrayRetorno.length;i++){
$("#idDivTC ul").append(arrayRetorno[i]);
}
It works, but the style doesnt applied anymore.
It seems to me that the former block is not the same the latter, although they have the same ID.
Besides, this click event
$("#idDivTC ul li > img").click(function (e){ ...
calls a JqueryUI dialog window, but It works only on the former structure as well.
How may I achieve my intent?
Thank you
In addition, this is the code to modal dialog window (Ui JQuery):
//--------------------modal of index.php ----------------
$("#idDivTC ul li > img").click(function (e){
e.preventDefault();
var titulo = $(this).attr("title");
var alternativa = $(this).attr("alt");
var imagemObj = new Image();
var caminhoArquivo=$(this).attr("src");
imagemObj.src= caminhoArquivo;
imagemObj.onload = function()
{
var largura=imagemObj.width;
var altura=imagemObj.height;
$(this).clone().dialog({
title: function (){
return titulo+" - "+caminhoArquivo;
},
modal: true,
resizable: false,
draggable: true,
width: function(){
return largura;
}
//fim da funcao da largura
});//fim da da this clone
};// fim da imagem load
});
//-----------------------------
For one, use event delegation to attach your click handlers: $("#idDivTC ul li > img").click(...) becomes $("#idDivTC ul").on("click", "img", ...).
The event isn't fired for the newly created elements because they don't have any click events bound to them.