I have a JavaScript within which am dynamically creating an HTML form with a Confirm button. When clicking on the confirm button, certain JavaScript variables need to be passed to another JS method within the same file. But am getting an error in the code that I've written that doesn't adhere to the same js file but another jsp file, though it doesn't directly link or is affected by it in any way.
JS Function with the Button onclick
if (dropElem == "stream ui-draggable ui-draggable-handle") {
var newAgent = $('<div>');
jsPlumb.addEndpoint(newAgent,connectorProperties);
newAgent.attr('id', i).addClass('streamdrop');
var elemType = "table";
$("#container").addClass("disabledbutton");
$("#toolbox").addClass("disabledbutton");
$('#container').append(newAgent);
$("#lot").append(
"<h4>TABLE</h4></br>"+
"<h5> Select a Table </h5></br>"+
"<div class='col-md-12'>"+
"<select id='attr-combobox-style' name='attr-combobox-style' class='form-control' id='tableListDropDownCombo'>"+
"<option value='Select an option'>Select an option</option>"
);
for(var q=0;q<StreamArray.length;q++)
{
$("#attr-combobox-style").append(
"<option value="+StreamArray[q][0]+">"+StreamArray[q][0]+"</option>"+
"</select>"+
"</div>"
);
}
$("#lot").append(
"<div class='form-group'></br>"+
"<label class='col-md-12 control-label' for='tableFormConfirmButton'></label></br>"+
"<label class='col-md-12 control-label' for='tableFormConfirmButton'></label></br>"+
"<label class='col-md-12 control-label' for='tableFormConfirmButton'></label></br>"+
"<label class='col-md-2 control-label' for='tableFormConfirmButton'></label>"+
" <button id='tableFormConfirmButton' name='tableFormConfirmButton' class='btn btn-primary' onclick='storeTableFormInfo("+newAgent+","+i+","+e+","+mouseTop+","+mouseLeft+","+elemType+")'>Confirm</button>"+
"  <button id='tableFormCancelButton' name='tableFormCancelButton' class='btn btn-danger'>Cancel</button>"+
"</div></br>"
);
$("property").show();
$(".toolbox-titlex").show();
$(".panel").show();
i++; //Increment the Element ID for the next dropped Element
finalElementCount=i;
}
Error on Console
Since I didn't make any changes to any other files, I'm guessing that the error caused here is due to the syntax line where I've tried to pass the multiple javascript variables(newAgent,i,e,mouseTop,mouseLeft,elemType) in the onclick function of the Confirm button.
Any suggestions in this regard will be highly appreciated.
You need to declare javascript global variable and need to define first in script tag like below
<script type='text/javascript' >
var myGlobalVariable = false;
</script>
<script type='text/javascript' src='js/Other.js'></script>
...
<script type='text/javascript' >
// other java script code that depend on Other.js
</script>
Related
Select2 initializes for the first item generated with on click and then on generating new div item with on click the select2 property is removed from the first item and initializes on the 2nd.
$(document).ready(function(){
$("#packages #add_package").on("click", function(){
$(this).before(
"<div class='col-12 packageCard'>"+
"<div class='col-4'>"+
"<div class='form-group'>"+
"<label>Container Type</label>"+
"<select name='cntType' id='cntType' class='form-control select2' data-dropdown-css-class='select2' style='width: 100%;'>"+
"<option value='0' selected='selected' disabled>Select Container Type</option>"+
"<option>20 feet</option>"+
"<option>40 feet</option>"+
"</select>"+
"</div>"+
"</div>"+
"</div>");
$('.select2').select2();
});
})
If you check your browser's devtools console, you will see a Javascript error thrown when you try to add the second select2:
Uncaught query function not defined for Select2 undefined
If you search for that error, you will find some other questions about this, for eg this one: "query function not defined for Select2 undefined error"
And if you read through the answers and comments, you will find several which describe what you are doing:
This comment:
This problem usually happens if the select control has already been initialized by the .select2({}) method. A better solution would be calling the destroy method first. Ex: $("#mySelectControl").select2("destroy").select2({});
This answer:
One of its other possible sources is that you're trying to call select2() method on already "select2ed" input.
Also this answer:
I also had this problem make sure that you don't initialize the select2 twice.
... and possibly more. These describe what you are doing - calling .select2() on elements which are already initialised as select2s.
The second time $('.select2').select2() runs, as well as trying to initialise your new select2, it is re-initialising the first select2 as a select2 again.
You have another problem in your code - every select has the same ID: id='cntType'. IDs must be unique on the page, so this is invalid HTML.
We can solve both problems at once by keeping track of how many selects you have on the page, and giving each new one an ID including its number, like say cntType-1, cntType-2, etc. Then we can target just the new ID to initialise it as a select2.
Here's a working example.
$(document).ready(function () {
// Track how many selects are on the page
let selectCount = 0;
$("#packages").on("click", function () {
// New select! Increment our counter
selectCount++;
//. Add new HTML, using dynamically generated ID on the select
$(this).before(
"<div class='col-12 packageCard'>" +
"<div class='col-4'>" +
"<div class='form-group'>" +
"<label>Container Type</label>" +
"<select name='cntType' id='cntType-" + selectCount + "' class='form-control select2' data-dropdown-css-class='select2' style='width: 100%;'>" +
"<option value='0' selected='selected' disabled>Select Container Type</option>" +
"<option>20 feet</option>" +
"<option>40 feet</option>" +
"</select>" +
"</div>" +
"</div>" +
"</div>");
// Initialise only our new select
$('#cntType-' + selectCount).select2();
});
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.0.0/select2.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/2.1.0/select2.min.js"></script>
<button id="packages">Add</button>
Inside my content.js I am writting a new HTML page with a pre polulated form, which contains var a and var b. Those 2 variables are created before, inside content.js, so I can easily use them inside my HTML page. Now I want to override those variables a and b as the user finishes editing the form and presses the button Accept. Is there anyway I can achieve this?
This is a part of the code
var a="FName";
var b="LName";
var myWindow = window.open("Accept", "myWindow", "width=450, height=300");
myWindow.document.write(
"<html>"+
"<head>"+
'<script> function closeWindow(){ var x = document.getElementById("firstname").value alert(x); window.close();}'+
"</script>"+
"</head>"+
"<body>"+
"<form>"+
"<div id=leadinformation>"+
"<p id=titleParagraph>You are about to create a new Lead:</p>"+
"First Name....."+ "<input type=text id=firstname value="+a+">" +"<br>"+
"Last Name....."+ "<input type=text id=lastname value="+b+">" +
"</div>"+
"<div>"+
"<button id=Accept onClick=closeWindow() >Accept</button>"+
"<button id=Close onClick=closeWindow() >Close</button>"+
"</div>"+
"</form>"+
"</body>"+
"<html>"
);
myWindow.document.getElementById('Accept').onclick=Accept;
myWindow.document.getElementById('Close').onclick=Close;
function Accept(){
alert(myWindow.document.getElementById('firstname').innerText);
}
function Close() {//do smthing
}
Sorry for bad formating.
Currently the output of the Accept(); is empty at the moment. How can I get first name input result?
What I want to achieve:
1) I am creating a button on a page
2) When I click on the button a new html page pops out (the one that I am hardcode writing it)
3) I pre populate the form with some variables that I created before
4) When Clicking The Accept button on the form the Accept() function is triggered where I would want to use those input values the user has written.
This should help you: Sharing global javascript variable of a page (...).
The question is about "How to share a variable to another page in an iframe", but this works for a new windows as well.
i.e.:
myWindow.document.write(
"<html>" +
"<head>" +
'<script>' +
'function closeWindow(){' +
'var x = document.getElementById("firstname").value;' +
'alert(x);' +
'// do something to parent.a and parent.b here, just because you can:' +
'parent.a = "Oh, would you look at it, it works!";' +
'parent.b = "And it is so pretty too!";' +
'window.close();' +
'}' +
"</script>" +
"</head>" +
" Your body code here, etc " +
"</html>"
);
Also, please note that your code lacks a semicolon (;) after inserting value to var x in your new window's JavaScript code. That will most probably make your code malfunction. The closing </html> tag lacks the slash, but I don't know if that's gonna break anything; you'd better fix that as well, just in case.
i have created one button in my javascript code, after clicking on this button it should go to the product.html
var outputb2 = "<p align=right>"+ "<input type=button value=productandservices onClick=window.location=product.html>" + "</input>" +"</p>";
$('#product').append(outputb2);
where product is the div id in the product.html.but when i click on this button product and services..its not going to this product.html.how can i do..?
I don't know why you are using javascript for this, unless you are sending some data with the click event. there is a simple html code to do what you want.
product and services
If you must use java-script try this
onclick="javascript:location.href='product.html#product'"
Check this out
<script>
var outputb2 = "<p align=right>"+ "<input type=button id='productandservices' value=productandservices >" + "</input>" +"</p>";//added id
$('#product').append(outputb2);
$(document).ready(function()
{
$(document).on("click","#productandservices",function()
{
alert('clcik');
window.location='product.html';
});
});
</script>
or
Enclose filename in quotes '
<script>
var outputb2 = "<p align=right>"+ "<input type=button id='productandservices' value=productandservices onClick=window.location='product.html' >" + "</input>" +"</p>";
$('#product').append(outputb2);
</script>
Probably you need some escape characters in your code, it will work
var outputb2 = "<p 'align=right'>"+ "<input type='button' value='productandservices' onClick='window.location=\"product.html?someParam=hi\"'>" + "</input>" +"</p>";
$('#product').append(outputb2);
var outputb2 = "<p align=right>";
outputb2 += "<input type='button' value='productandservices' onClick='window.location=product.html'>"
outputb2 += "</p>";
$('#product').append(outputb2);
var outputb2 = "<p align='right'><input type='button' value='productandservices' onClick='window.location=product.html'></input></p>";
$('#product').append(outputb2);
right syntax to use:
<input TYPE="button" value=productandservices onclick="window.location.href='http://www.wherever.com'">
Another option is to create a link in the button:
<button type="button">Link link</button>
Then use CSS to style the link and button, so that the link takes up the entire space within the button (so there's no miss-clicking by the user):
button, button a{position:relative;}
button a{top:0;left:0;bottom:0;right:0;}
but the point of a link is to go to another page. So trying to make a button act like a link is the wrong solution. My suggestion is that you should use a link and style it to look like a button.
<a href="/page2>Continue</a>
Try this :
var outputb2 = "<p align='right'>"+
"<input type='button' value='productandservices 'onClick='window.location=\"product.html\"' />" +
"</p>";
$('#product').append(outputb2);
Add ' like this : onClick='window.location=\"product.html\"'
Live demo
How can I copy an entire div to a popup window?
What I`m trying to do:
function ImprimirTela() {
var text = "<html>\n<head>\n<title>Impressão Guia</title>\n";
text += "<script src='~/js/jquery-1.4.2.js' type='text/javascript' language='javascript' />\n";
text += "</head>\n<body>\n";
text += "<input type='button' value='Imprimir esta página' onclick='window.print();' style='float: right' />\n";
text += "<div id='conteudo'>\n";
text += $("#divDadosBasicos").html($(querySelector).html());
text += $("#divHipotesesDiagnosticas").html($(querySelector).html());
text += "</div>\n/body>\n</html>";
var newWindow = window.open('', 'Impressao', 'width=900,height=700');
newWindow.document.write(text);
}
I dont know if this is the better way to do it. If you think/know a easier way to do it, please share
Thanks in advance!
Fix some of these errors and it will work fine
Script tag is not closed properly
body tag not closed properly
querySelector is not defined. (I am commenting that portion)
function ImprimirTela() {
var text = "<html>\n<head>\n<title>Impressão Guia</title>\n";
text += "<script src='~/js/jquery-1.4.2.js' type='text/javascript' language='javascript'></script>\n";
text += "</head>\n<body>\n";
text += "<input type='button' value='Imprimir esta página' onclick='window.print();' style='float: right' />\n";
text += "<div id='conteudo'>\n";
//define querySelector
//text += $("#divDadosBasicos").html($(querySelector).html());
//text += $("#divHipotesesDiagnosticas").html($(querySelector).html());
text += "</div>\n</body>\n</html>";
var newWindow = window.open('', 'Impressao', 'width=900,height=700');
newWindow.document.write(text);
}
You could use a Jquery Modal Popup
http://jqueryui.com/demos/dialog/
Check it out, it has the functionality that you need.
It has several events you can tweak to modify the data.
Just tested this, and the code seems to be working just fine as long as querySelector is defined, and it's in a document.ready function and you are testing this on an actual webserver (like WAMP/LAMP etc.). It will not work in places like jsFiddle etc.
I have a lot of JavaScript code that creates HTML. For example:
function Reply(postId) {
if (!document.getElementById("reply" + postId)) {
$("#root" + postId).after("<div id='reply" + postId + "'><textarea cols='70' rows='8' style='margin-bottom: 10px'></textarea><br/><span style='margin-bottom: 30px'><input type='button' value='Submit' /><input type='button' value='Cancel' onclick='$(\"#reply" + postId + "\").remove();'/></span></div>");
}
}
How can I use jQuery to make this more readable? What's the best way to go about making new elements in JavaScript? Can I see an example?
The standard way is not to create html and then appending or prepending it but to create dom elements and adding them.
Please read this wonderful article on innerHTML vs DOM. by Tim Scarfe. It's very well written and and points and counter points.
You can read more on DOM here. and a Lot of information at the Gecko DOM Reference..
Sorry for only pasting links but it's a lot to go through.
If you want a quickstart. Look at this part of the Gecko DOM Reference. where they talk about createElement. Which is the magical method you're looking for.
First of all you need to know where you want to append the HTML, here you'll see the documentation: for "manipulation": here.
So lets say you want to create a paragraph inside a DIV with the ID "insideme".
$("#insideme").append("<p>I'm adding this</p>");
That is for creation, now lets say you want to insert an existent DIV:
$("#insideme").append($("div#existent"));
Check the documentation, there you'll find every function that is used to add before, after, inside, etc.
Hope it helped you.
If you want to fully use jquery functions, see if the following works (I have not tested it). Howerver, I would actually advise against this since I understand that direct HTML-string parsing/rendering is optimized a lot faster than a bunch of js function calls.
function Reply(postId) {
var rid = "reply"+postId;
if (!$('#'+rid)) {
$('#root'+postID)
.append("<div/>").attr('id',rid)
.append("<textarea/>").attr({'cols',70,'row',8,'style','margin-bottom: 10px'})
.after("<br/>")
.after("<span />").attr('style','margin-bottom: 30px');
.append("<input type='button' value='Submit' />")
.after("<input type='button' value='Cancel' />")
.onclick(function(){
$("#"+rid).remove();
});
}
}
Two ways:
Improve the formatting of that string
Install event handlers programatically
Eg:
function Reply(postId) {
if (!document.getElementById("reply" + postId)) {
// Generate HTML
var html = "<div id='reply" + postId + "'>";
html += "<textarea cols='70' rows='8' style='margin-bottom: 10px'></textarea><br/>";
html += "<span style='margin-bottom: 30px'>";
html += "<input type='button' value='Submit' />";
html += "<input class='cancelButton' type='button' value='Cancel' />";
html += "</span>";
html += "</div>";
// Insert into DOM
$("#root" + postId).after(html);
// Install event handlers
$("#root .cancelButton").bind("click", function() {
$("#reply" + postId).remove();
});
}
}
Using the DOM is methods directly is specifically discouraged by jQuery since it's so slow.
Update: As Chris says, move those styles to a CSS file to further tidy this up.
For such things I always use EJS.
http://embeddedjs.com/
Remove the angle brackets from your jQuery.
$( ".cancel" ).live( 'click', function() { $( this ).remove(); });
function reply( postId ) {
if ( $( "#reply" + postId ).size() == 0 ) {
var context = { postId: postId };
$( "#root" + postId ).after(new EJS({ url: '/template.ejs' }).render( context ));
}
}
Put them in a template with all their pointy little friends.
<div id="reply<%= postId %>">
<textarea cols="70" rows="8" class="reply_editor"></textarea>
<br>
<span class="ok_cancel">
<input type="button" value="Submit">
<input type="button" value="Cancel" class="cancel">
</span>
</div>
Inline styles are the devil's handiwork.
.reply_editor {
margin-bottom: 10px
}
.ok_cancel {
margin-bottom: 30px;
}
For extra legibility, don't attach handlers in your HTML. Attach them using jQuery.
Move the style stuff to a CSS file.
Remove the onclick event handler, replace it with a jQuery live.
Wrap the elementId in a variable.
$(".cancelButton").live("click", function(){$(this).remove();});
function Reply(postId) {
var elementId = "reply" + postId;
if (!document.getElementById(elementId )) {
var element = $("#" + elementId).after("<div id='" + elementId + "'><textarea cols='70' rows='8' ></textarea><br/><span ><input type='button' value='Submit' /><input type='button' value='Cancel' class='cancelButton'/></span></div>");
}
}