Insert a form field into a popup page using jquery - javascript

I'm trying to insert a form field into a popup page. For some reason the form field doesn't get inserted. Any pointers. Pasted below is the code:
$(".ddlAddListinTo li").click(function () {
var urlstring = "../ActionTypes";
var ddlselectedVal = $(this).attr('id');
var $form = $("#frmPostToEmailReports");
var AgentId = $form.find("#AgentId").val();
var ReportName = $form.find("#ReportName").val();
var Params = $form.find("#Params").val();
if (ddlselectedVal != "None" && ddlselectedVal != "select") {
$.post(urlstring, { AgentId: AgentId, ReportName: ReportName, Params: Params },
function (data) {
window.open(urlstring);
$("#divfrmInfo").append($form);
});
} });
HTML for my popup window :
<html>
<head></head>
<body>
<h2>AddToCart</h2>
<form name="frmContact">
<div>
<div class="CartHeader">
<ul>
<li>
<span class="CartImage"></span>
<span class="Title">To Add Listing(s) to Cart</span>
<span class="SubTitle">Select your personal cart or add listings to a contact</span>
</li>
</ul>
</div>
**<div id="divfrmInfo"></div>**
</div>
</form>
</body></html>

Looking at it some more you could do something like this, in opener document.
$(".ddlAddListinTo li").click(function () {
...
function (data) {
$(window.open(urlstring)).load ( function() {
// Here "this" will be the window.
$(this.document).find("#divfrmInfo").append($form.clone())
});
}
This way you attach to load event for popup by jQuery.
Have a look at .clone() for the append part. If it is not cloned it will be "ripped" from your main document and placed inside the popup.
Old answer:
...
Here is a fiddle (With fixed typo/formatting).
Next problem is in your script you say:
$(".ddlAddListinTo li").click
However, there are no elements in DOM with class ddlAddListinTo.
OK, by comment:
after window.open(urlstring); you are still in DOM of document from where you opened the window. As such:
$("#divfrmInfo")
will look for an element in original document with that ID, not in the popup.
If you add something like this in the popup document*:
$(window).load(function() {
// Call function "fill()" in opener.
window.opener.fill(document);
});
And this in your opener document:
function fill(what) {
// Here "what" is document of popup.
what.getElementById("divfrmInfo").innerHTML = "TEST";
}

I think the selector in your AJAX callback is unable to get DOM elements in the popup. Try this:
var tmpWin = window.open(urlstring);
$(tmpWin.document).find("#divfrmInfo").append($form);

THe problem is you are tring to aceess the DOM of the spawned page before it is there. The window is loaded but the HTML is still being loaded at the time you are trying to access it. You will need to change the parent and popup page. On the parent page you will need a function to return what you want to populate the pop up with. On the popup page you will want to call the function on the parent page when the DOM is ready.
Something like:
Parent Page
//Add this OUTSIDE your document ready
function getContent(){
return $("#frmPostToEmailReports");
}
Popup
//Include Jquery in your prefered way
<script>
$(document).ready(function () {
$("#divfrmInfo").append(window.opener.getContent());
});
</script>
Alos make sure to remove where you attempt to pupulate in the success function. Also see: How to get element and html from window.open js function with jquery
Previous Useless Answer Below
See this answer to get you started.
Instance you will want something like:
$(".ddlAddListinTo li").click(function () {
var urlstring = "../ActionTypes";
var ddlselectedVal = $(this).attr('id');
var $form = $("#frmPostToEmailReports");
var AgentId = $form.find("#AgentId").val();
var ReportName = $form.find("#ReportName").val();
var Params = $form.find("#Params").val();
if (ddlselectedVal != "None" && ddlselectedVal != "select") {
$.post(urlstring, { AgentId: AgentId, ReportName: ReportName, Params: Params },
function (data) {
var popup = window.open(urlstring);
popup.document.$("#divfrmInfo").append($form);
});
} });

Related

Jquery .change() event fires only once

So I'm fairly novice with jquery and js, so I apologise if this is a stupid error but after researching I can't figure it out.
So I have a list of data loaded initially in a template, one part of which is a dropdown box that lets you filter the data. My issue is that the filtering only works once? As in, the .change function inside $(document).ready() only fires the once.
There are two ways to reload the data, either click the logo and reload it all, or use the search bar. Doing either of these at any time also means the .change function never fires again. Not until you refresh the page.
var list_template, article_template, modal_template;
var current_article = list.heroes[0];
function showTemplate(template, data)
{
var html = template(data);
$("#content").html(html);
}
$(document).ready(function()
{
var source = $("#list-template").html();
list_template = Handlebars.compile(source);
source = $("#article-template").html();
article_template = Handlebars.compile(source);
source = $("#modal-template").html();
modal_template = Handlebars.compile(source);
showTemplate(list_template,list);
$(".articleButton").click(function()
{
var index = $(this).data("id");
current_article = list.heroes[index];
showTemplate(article_template,current_article);
$('.poseThumb').click(displayModal);
});
$("#classFilter").change(function()
{
console.log("WOW!");
var classToFilter = this.value;
var filteredData =
{
heroes: list.heroes.filter(function(d)
{
if (d.heroClass.search(classToFilter) > -1)
{
return true;
}
return false;
})
};
console.log(filteredData);
showTemplate(list_template,filteredData);
$(".articleButton").click(function()
{
var index = $(this).data("id");
current_article = filteredData.heroes[index];
showTemplate(article_template,current_article);
$('.poseThumb').click(displayModal);
});
});
$("#searchbox").keypress(function (e)
{
if(e.which == 13)
{
var rawSearchText = $('#searchbox').val();
var search_text = rawSearchText.toLowerCase();
var filteredData =
{
heroes: list.heroes.filter(function(d)
{
if (d.name.search(search_text) > -1)
{
return true;
}
return false;
})
};
console.log(filteredData);
showTemplate(list_template,filteredData);
$(".articleButton").click(function()
{
var index = $(this).data("id");
current_article = filteredData.heroes[index];
showTemplate(article_template,current_article);
$('.poseThumb').click(displayModal);
});
}
});
$("#logo").click(function()
{
showTemplate(list_template,list);
$(".articleButton").click(function()
{
var index = $(this).data("id");
current_article = list.heroes[index];
showTemplate(article_template,current_article);
$('.poseThumb').click(displayModal);
});
});
//$("#logo").click();
});
function displayModal(event)
{
var imageNumber = $(this).data("id");
console.log(imageNumber);
var html = modal_template(current_article.article[0].vicPose[imageNumber]);
$('#modal-container').html(html);
$("#imageModal").modal('show');
}
I should note two things: first, that the search bar works perfectly, and the anonymous function inside both of them is nearly identical, and like I said, the filtering works perfectly if you try it after the initial load. The second is that the same problem occurs replacing .change(anonymous function) with .on("change",anonymous function)
Any help or advice would be greatly appreciated. Thanks.
I agree with Fernando Urban's answer, but it doesn't actually explain what's going on.
You've created a handler attached to an HTML element (id="classFilter") which causes part of the HTML to be rewritten. I suspect that the handler overwrites the HTML which contains the element with the handler on it. So after this the user is clicking on a new HTML element, which looks like the old one but doesn't have a handler.
There are two ways round this. You could add code inside the handler which adds the handler to the new element which has just been created. In this case, that would mean making the handler a named function which refers to itself. Or (the easier way) you could do what Fernando did. If you do this, the event handler is attached to the body, but it only responds to clicks on the #classFilter element inside the body. In other words, when the user clicks anywhere on the body, jQuery checks whether the click happened on a body #classFilter element. This way, it doesn't matter whether the #classFilter existed when the handler was set. See "Direct and delegated events" in jQuery docs for .on method.
Try to use some reference like 'body' in the event listeners inside your DOM like:
$('body').on('click','.articleButton', function() {
//Do your stuff...
})
$('body').on('click','#classFilter', function() {
//Do your stuff...
})
$('body').on('keypress','#searchbox', function() {
//Do your stuff...
})
$('body').on('click','#logo', function() {
//Do your stuff...
})
This will work that you can fire it more than once.

Pass Jquery Data to print.html

I have two page, the index.html and print.html
on my index.html page there is a calculator and i have a button called print that is located on index.html
when you click PRINT button, it would go to print.html. My problem is does not send the input value I made on index.html.
Note: This work if I dont go to print.html. the value shows up, but if set it on another page, the value does show up
PRINT.HTML
$(document).ready(function() {
$('#print_modal').click(function() {
e.preventDefault();
var rec_product = $('#rec_product').val();
var calc_height = $('#calc_height').val();
var calc_width = $('#calc_width').val();
var calc_depth = $('#calc_depth').val();
$('#srec_product').text(rec_product);
$('#sheight').text(calc_height);
$('#swidth').text(calc_width);
$('#sdepth').text(calc_depth);
window.print();
return false;
window.location.href = "print.html";
window.open(url, '_blank');
});
$("#print_modal").click(function(e) {
e.preventDefault();
var value = //get input value
$.get( "print.html", {"value":value});
});
this jQuery code will direct you to print.html?value=12(where 12 is your value).
You can then use PHP in print.html to retrieve the value ($_GET['value'])
You can use
window.location = '/print.html?rec_product='+$("#rec_product").val()+'&calc_height='+$("#calc_height").val();
for loading your print.html in same window tab.
If you are sending multiple parameter use following code to get value on print.html:
<script type="text/javascript">
load();
function load()
{
window.location.search.replace ( "?", "" ).split("&")
.forEach(function (item) {
var tmp = item.split("=");
document.getElementById(""+tmp[0]).value=tmp[1];
});
}
</script>
If you want to do it via jquery then use
$("#"+tmp[0]).val(tmp[1]);
insted of:
document.getElementById(""+tmp[0]).value=tmp[1];
You must have same name input type fields as send in parameter.
You can also use load function code in your
$( document ).ready(function() {
});
on print.html.

pass value/variable from fancybox iframe to parent

I'am trying to pass a variable/ value from the fancybox iframe to the parent window without success.
Fancybox is launched from a link with
class="fancybox fancybox.iframe"
My code in the fancybox.iframe is:
$(document).ready(function(){
$('.insert_single').click(function(){
var test = $('.members_body').find('{row.U_USERNAME}');
setTimeout(function(){ parent.$.fancybox.close();},300);return true;
});
});
Where '{row.U_USERNAME}' is the username to find in the iframe.
Then, in the parent there's the following code:
$(document).ready(function(){
$('.fancybox').fancybox(
{
openEffect:'fade',
openSpeed:500,
afterClose: function(){
alert($(".fancybox-iframe").contents().find(test));
$('#form input[name=username]').val()(test);return false;
}
}
);
});
But when the fancybox is closed, there's no alert showing up with the variable "test", nor the variable is showing up as a value or as a text in the input field of the form.
I've read and tried various solutions found here on stackoverflow without success.
Thanks in advance for helping
EDIT
Here's an Example
When the fancybox is closed the iframe is removed from the document. So you must use beforeClose event instead of afterClose
$(document).ready(function() {
$('a.fancybox').fancybox({
openEffect:'fade',
openSpeed:500,
beforeClose: function() {
// working
var $iframe = $('.fancybox-iframe');
alert($('input', $iframe.contents()).val());
},
afterClose: function() {
// not working
var $iframe = $('.fancybox-iframe');
alert($('input', $iframe.contents()).val());
}
});
});
JSFiddle: http://jsfiddle.net/NXY7Y/1/
EDIT:
I edited your jsfiddle (http://jsfiddle.net/NXY7Y/9/). Update is in this link
http://jsfiddle.net/NXY7Y/13/
Main page javscript:
$(document).ready(function() {
$('a.fancybox').fancybox({
openEffect:'fade',
openSpeed:500//,
//beforeClose: function() {
// // working
// var $iframe = $('.fancybox-iframe');
// alert($('input', $iframe.contents()).val());
//},
//afterClose: function() {
// // not working
// var $iframe = $('.fancybox-iframe');
// alert($('input', $iframe.contents()).val());
//}
});
});
function setSelectedUser(userText) {
$('#username').val(userText);
}
No need to use afterClose or beforeClose events. Just access the parent function setSelectedUser from the iframe on link click event like this:
$(document).ready(function() {
$('a.insert_single').click(function() {
parent.setSelectedUser($(this).text());
parent.$.fancybox.close();
});
});
Some clarifications :
You should use .find() to find elements by selector (you are trying to find a variable .find(test), which is not a valid format).
You should use .val() to get the contents of an input field or .val(new_value) to set the contents of an input field
You should use .html() or .text() to get the contents of any element other than input,
example: having this html code
<p class="test">hola</p>
... and this jQuery code
var temp = $(".test").html();
... temp will return hola.
On the other hand, if you have control over the iframed page and it's under the same domain than the parent page, then you may not need to set any jQuery in the child page.
so, having this html in the child (iframed) page for instance
<div class="members_body">
<p>GOOGLE</p>
<p>JSFIDDLE</p>
<p>STACKOVERFLOW</p>
</div>
You could set this jQuery in your parent page to get the contents of any clicked element in your child page :
var _tmpvar; // the var to use through the callbacks
jQuery(document).ready(function ($) {
$(".fancybox").fancybox({
type: "iframe",
afterShow: function () {
var $iframe = $('.fancybox-iframe');
$iframe.contents().find(".members_body p").each(function (i) {
$(this).on("click", function () {
_tmpvar = $('.members_body p:eq(' + i + ')', $iframe.contents()).html();
$.fancybox.close();
}); // on click
}); // each
},
afterClose: function () {
$('#form input[name=username]').val(_tmpvar);
}
});
}); // ready
Notice that we declared the var _tmpvar globally so we can use it within different callbacks.
See JSFIDDLE

Refresh view page without reloading the page manually

I have to refresh view page without clicking on refresh button.
Javascript code:--
<script type="text/javascript">
$(function () {
var metaId = $("#ID").val();
var img = $("##name input[type=hidden]").val();
if ("#found" == "False") {
$.post(rootURL + "Picture/AddThumb", { guidOrName: img, meta: metaId, id: contentId }, function (data) {
//arrangePoster([data]);
});
}
});
</script>
Post sometimes doesn't work.
It is better to use ajax jquery method.
http://api.jquery.com/jquery.ajax/
Then on Picture/AddThumb add printing parameters.
Use done to show data resulted ( to test also if it works correctly )

Resend AJAX request with link?

Is there anyway to reload just the AJAX request, so that it updates the content pulled from the external site in the code below?
$(document).ready(function () {
var mySearch = $('input#id_search').quicksearch('#content table', { clearSearch: '#clearsearch', });
var container = $('#content');
function doAjax(url) {
if (url.match('^http')) {
$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent(url)+
"%22&format=xml'&callback=?",
function (data) {
if (data.results[0]) {
var fullResponse = $(filterData(data.results[0])),
justTable = fullResponse.find("table");
container.append(justTable);
mySearch.cache();
$('.loading').fadeOut();
} else {
var errormsg = '<p>Error: could not load the page.</p>';
container.html(errormsg);
}
});
} else {
$('#content').load(url);
}
}
function filterData(data) {
data = data.replace(/<?\/body[^>]*>/g, '');
data = data.replace(/[\r|\n]+/g, '');
data = data.replace(/<--[\S\s]*?-->/g, '');
data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g, '');
data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g, '');
data = data.replace(/<script.*\/>/, '');
data = data.replace(/<img[^>]*>/g, '');
return data;
}
doAjax('link');
});
Right now I have a button which reloads the entire page, but I just want to reload the AJAX request. Is this even possible?
Edit: I need to specify more. While it can easily call the AJAX again, can it also replace the info that is already there?
You just need to call the doAjax function again on button click...
$("#buttonID").on("click", function() {
doAjax("link");
});
Add that into the above document.ready code and set the button ID correspondingly.
Then change
container.append(justTable);
to
container.html(justTable);
In your doAjax function you append HTML onto an element. If you overwrite the element's HTML instead of appending to it then the HTML will be "refreshed" each time the doAjax function runs:
Simply change:
container.append(justTable);
To:
container.html(justTable);
And of-course you can bind a click event handler to a link (or any element) like the rest of the answers show. Make sure you bind the click event in the proper scope (inside the document.ready event handler) so the doAjax function will be accessible from the click event handler.

Categories

Resources