Set var value from other JavaScript file using jQuery - javascript

I have a two JavaScript files:
Main.js
Pmt.js
I'm also using thick box (Ajax call)
in Main.js
$(document).ready(function() {
var cnt=0;
$("#btnPmt").click(function(){
cnt=cnt+1;
tb_show('Void Transaction','pmt.jsp?height=310&width=400', null);
});
});
The Pmt.js file is included in pmt.jsp as
<script src="js/Pmt.js" type="text/javascript"></script>
in Pmt.js
$("#btnPmtClose").click(function(){
cnt=0;
parent.tb_remove();
});
How we can reset the value of var cnt in Pmt.js that decalred in Main.js?
The above is not working, when I close the thickbox, I find the incremented value, not zero that set on close, even Ajax call.

in Main.js make cnt as global var by moving it outside any function :
var cnt=0;
$(document).ready(function() {
...
})

Related

jQuery getting text content of a span

I am trying to write a delete function in Dropzone.js. In order to do that I need the id of the file the way it was uploaded.
I tried to get a property of an object with no success. Now I am trying to use jQuery to get the value or text content of the span that has it.
this is the screenshot of the structure. The jQuery code I am trying is:
var loooot = $(".dz-filename").parents('span').text();
To be more specific I am trying to get the number 1_1477778745352 (which is a time stamp).
The Dropzone code is as follows:
<script>
var listing_id = "1";
// these are the setting for the image upload
Dropzone.options.pud = {
acceptedFiles: ".jpeg,.jpg,.png,.gif",
uploadMultiple: false,
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 1, // MB
addRemoveLinks: true,
maxFiles: 10,
renameFilename: function (filename) {return listing_id + '_' + new Date().getTime();},
init: function()
{
this.on("removedfile", function(file)
{
var loooot = $("span", ".dz-filename").html();
alert(loooot);
});
}
};
</script>
Try this use JQuery's .text(); to get inner text
Update: use this with DOM .ready() like that.
Deep selector
$(document).ready(function(){
var fname = $("#pud .dz-filename span [data-dz-name]").text();
});
OR (if your form is dynamic)
function get_fname(){
return $("#pud .dz-filename span [data-dz-name]").text();
}
Then use get_fname();
It becomes undefined because dropzone works dynamicly, use this:
$('body').find(".dz-filename").find('span').text();
Best way to do this is to declare dropzone:
//first declare somewhere variable
var my_drop;
// then on creating dropzone:
my_drop = new Dropzone('.dropzone', {
/* your setup of dropzone */
});
Then you can retreive information about files with this:
my_drop.files[0].name
The [0] represent's first file, you can loop through them if there's more then one.
Use:
var loooot = $("span", ".dz-filename").html();
Working Demo.
var loooot = $("span", ".dz-filename").html();
alert(loooot);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="dz-filename">
<span>Test</span>
</div>
EDIT
Since you are setting the text dynamically it may happens that jquery read the HTML before that you set it, to prevent this you have to call this function after the timestamp as a callback (i can't help you without seeing how you set the span text).
So do something like:
function setSpan(callback) {
// Set your stuffs
// Call the callback
callback();
}
function getText() {
// I'm the callback witch get the html
}
//Onload
setSpan(getText());
EDIT
For dropzone you can use queuecomplete that start a function after the queue, i'm not an dropzone expert but i suppose:
init: function () {
this.on("queuecomplete", function (file) {
//Get span html
alert("All files have uploaded ");
});
}
The working solution I found is this:
init: function()
{
this.on("removedfile", function(file)
{
var loooot = $(file.previewElement).find('[data-dz-name]').text();
alert(loooot);
});
}

Trying to access ejs array in a js file

I send info to the client that contains an array and I only show 3 elements of the array because I want to have a pagination effect. I wanted to write the pagination code in a js file
in file.js
$(function(){
$(".pageLinks a").on("click", function(e){
e.preventDefault();
var pageNum = $(this).attr("id")
var test = JSON.stringify(populated) // I wanted populated to be the array from node
//doesn't have to have the stringify part
// I know I can't do this prob bec. it's not in an ejs file but I wanted something like that
console.log(test)
})
})
I'm able to access it in the ejs file
<% var index = Math.floor( populated.reviews.length /3)%>
<div class = "pageLinks">
<%for(var i = 0; i < index; i++){%>
<%= i + 1 %>
<%}%>
</div>
</div> <!--reviewSide-->
You're right, you can't get to the raw object in the (static) js file in the same way.
However, you can populate it to a global variable in your ejs file like this:
<script type="text/javascript">
var populated = <%-JSON.stringify(populated)%>;
</script>
which you can then either check for in the click handler like this:
$(function(){
$(".pageLinks a").on("click", function(e){
e.preventDefault();
var pageNum = $(this).attr("id")
if (typeof(populated) != "undefined"){
// you want to check to make sure this exists before trying to use
// it, just in case someone manages to click a page link before the
// code in your .ejs file has run.
var test = JSON.stringify(populated)
console.log(test)
}
})
})
...or pass to the external file.js when you load, as long as you're exposing something to the global scope that it can call. Your current script wraps everything in an anonymous function, but you could wrap it in a named function like this:
.ejs file:
<script type="text/javascript">
initialiseMyAwesomeFunction( <%-JSON.stringify(populated)%> );
</script>
.js file:
function initialiseMyAwesomeFunction(populated){
$(function(){
$(".pageLinks a").on("click", function(e){
e.preventDefault();
var pageNum = $(this).attr("id")
var test = JSON.stringify(populated)
console.log(test)
})
})
}

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.

jquery from external file not loading

So I know this question has been asked many times but I can't seem to get this working, even though it looks correct to me. My jquery functions from an external file aren't loading properly.
My tableMethods.js external file looks like
$(function(){
// Write FITS
function writeFits(){
var data = $('.sastable').bootstrapTable('getData');
var name = $('#fitsname').val();
$.getJSON($SCRIPT_ROOT + '/writeFits', {'data':JSON.stringify(data),'name':name},
function(data){
$('#fitsout').text(data.result);
});
}
// Delete rows from data table
function deleteRows(){
var $table = $('.sastable');
var $delete = $('#delete');
var ids = $.map($table.bootstrapTable('getSelections'), function (row) {
return row.id
});
$table.bootstrapTable('remove', {
field: 'id',
values: ids
});
}
})
My html header looks like
<script type="text/javascript" src="/static/js/jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="/static/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/static/js/bootstrap-table.js"></script>
<script type='text/javascript' src="/static/js/tableMethods.js"></script>
When I check the inspector, it says the file has loaded yet when I click my button that looks like
<button id="delete" class="btn btn-danger" type='button' onClick='deleteRows()'>Delete Rows</button>
I get the error
Uncaught ReferenceError: deleteRows is not defined
This is a scoping problem. You have to move your functions outside of $(function() { ... })
In JavaScript, anything exclusively defined within a function, generally stays within a function:
var x = 3;
(function() {
var y = 1;
})();
console.log(x); // 3
console.log(y); // error
So if you’re defining a function within a function, you can only invoke it from that function you have defined it in. When trying to invoke it from anywhere else, the inner function will seem undefined.
In your case, you can simply remove the wrapper function:
$(function() { // Delete this...
...
}); // And this
For more information, read You Don’t Know JS: Scope & Closures

Javascript: Function does not get fired

I have somehow a beginner's question about the following structure:
<body>
<p id="text_object">Some text</p>
<button id="button_change_text">change text on click</button>
// Individual script on page template
// ----------------------------------
<script type="text/javascript">
var object = $('#text_object');
changeTextOnLoad(object);
</script>
// Footer from included footer.php with universal main.js file
// ------------------------------------------------------------
<footer>
<script type="text/javascript" src="main.js">
</footer>
</body>
My main.js contains the following:
// declaration of function for writing new text into text object on load
function changeTextOnLoad(object) {
object.text('New text');
}
// declaration of click function
$('#button_change_text').on('click', function() {
$('#text_object').text('New text');
});
My problem: My console tells me that changeTextOnLoad() is undefined. But clicking on the button and changing the text by this way works perfectly fine. Where is the reason? Why in my main.js file does the click function get fired but not the changeTextOnLoad function?
You are calling your changeTextOnLoad function before the main.js file has loaded. Either put the function call in an onload event callback or put the include above the call
window.onload = function(){
var object = $('#text_object');
changeTextOnLoad(object);
};
//Or using addEventListener
window.addEventListener("load",function(){
var object = $('#text_object');
changeTextOnLoad(object);
});
//Or since you are using jQuery
$(document).ready(function(){
var object = $('#text_object');
changeTextOnLoad(object);
});
//Or
$(function(){
var object = $('#text_object');
changeTextOnLoad(object);
});
OR
<script type="text/javascript" src="main.js"></script>
<script type="text/javascript">
var object = $('#text_object');
changeTextOnLoad(object);
</script>
because main.js is another file, browser takes time to download it. But you run changeTextOnLoad(object); before that.

Categories

Resources