Append a script into a div - javascript

I've got a little problem and I'm stucking on it for a couple of days.
I downloaded a Javascriptcalendar plugin (Date Input) to add a little calendar in my form.
In this form I added a button wich add another line in this form to let user set severals dates.
<input type="button" value="Ajouter" onclick="ajoutChamp('creneau')" />
I made a little script :
var s = document.createElement('script');
s.type = "text/javascript";
s.text = "DateInput('creneau_2',true,'DD-MON-YYYY')";
$("#test").append(s);
But when I'm doing this, every time I press the button I've got my calendar who appears fullscreen. It's look like the script has been executed but no appened in the html page.
Little piece of my html code :
<table id="liste_creneau" class="add_champ">
<tr id="tr_creneau_1">
<td><label for="creneau_1">creneau 1</label></td>
<td><script id="ref_date">DateInput('creneau_1', true, 'DD-MON-YYYY')</script></td>
</tr>
</table>
<div id="test">
</div>
Atm I wanted to append the calendar in a div but at the end the calendar will be in the table.
I have done other tests too but every piece of code I made ended the same way...
So maybe you could help me! :)
Edit:
Ok I made a little test
var g = document.getElementById('test');
var s = document.getElementById('ref_date');
nb++;
var clone = s.cloneNode(true);
var param = clone.firstChild.data.split('\'');
param[1] = 'creneau_'+nb;
clone.firstChild.data = param.join('\'');
g.appendChild(clone);
After that, when I click on the button, there is a script tag inserted in the div but nothing shows up. When I inspect my html page I can see it but the calendar doesn't apear...
Bye
Edouard

I don't understand why you are not just running the date input line. It should have the same effect.
DateInput('creneau_2',true,'DD-MON-YYYY');
Regardless, you could just try and do it all in jQuery rather than mixing javascript selectors.
$("#test").append("<script type='text/javascript'>DateInput('creneau_2',true,'DD-MON-YYYY');</script>");

Well I chosen to use the jQuery-UI datepicker instead... So I guess it's solved, thanks a lot Agentminlindu and all the others :)

Related

Javascript document.getElementById not printing to element - strange issue

This context of this issue is it is a set of measurements needed for review by the user. I'm reviewing some of my code and changing it to bootstrap's classes. I have a php function - reviewSlide(); that prints out the necessary html. From there it calls javascript script - reviewGetMeasurement(); function to grab the measurements the user inputs.
The event that triggers the javascript function is -
<button onclick="slideforms_step17(event);reviewGetMeasurement();" class="mdk_slidesforms_btn"><?= (!empty($button_text)) ? $button_text : 'Next' ?></button>
The function runs then moves into the below function reviewSlide() however if I do have the following code everything runs perfectly and the measurements are gathered and printed to the page.
function reviewSlide() {
<table>
<tr width="33%">
<table class="pktsq_measurement_table_my_account_table">
<tr>
<td colspan="2" class="pktsq_measurement_table_my_account_td pktsq_measurement_table_my_account_td_title">
Personal
</td>
</tr>
<tr>
<td class="pktsq_measurement_table_my_account_td">
Height
</td>
<td class="pktsq_measurement_table_my_account_td pktsq_measurement_table_my_account_td_measurement" id="userHeight"></td>
</tr>
</table>
</tr>
</table>
...
}
If I remove the above table nothing works.
I have tried
function reviewSlide() {
<p id="userHeight"></p>
<p id="userWeight"></p>
...
}
at the top of my function (which is at this stage above the table) and nothing comes up.
I've looked at other people's issues, some of the main problems were the page wasn't loading and you would have to wait for the page to load as the javascript would not see any html. But I believe I have a bit of a quirky problem here regarding the table code
Any help would be grateful. Thank you.
UPDATE and CLARIFICATION (same as comments):
I didn't write this so bear with me but yes reviewSlide is in php. To clarify I have a function stepxx() in a shortcodes.php file. Each step represents a slide and reviewSlide() also represents another slide, in this case the review slide with all the measurements. All this is written in html/php. In stepxx() there is a button tag that calls a javascript function slideforms_stepxx(event);. When each step is complete 1-xx, slidesforms_stepxx(event) is called to check the input.
This is where we come to the review slide. On the slide before the review slide we go into slideforms_step17 check the input and submit the values to the server via jquery. Then we enter the reviewGetMeasurement() function as seen above by <button onclick="slideforms_step17();reviewGetMeasurement();....>. ReviewGetmeasurement's task is to print out the values and this is where my problem lies.
Inside reviewGetMeasurements(), if I print out the value for a variable let's say the height via console.log(height), it'll work and I can see the value in the console. But once if I try to print the value our by doing
document.getElementById("userHeight").innerHTML = height + "cm";
I get null. But I know there is a value height and it's not null. HOWEVER if I put the <table> code from above it will work and the values are printed out. If I use the <p> tags with the right id it won't work.
You can't just blindly put HTML inside of a Javascript or PHP function. What's in those functions must be the appropriate type of code, not HTML.
If it's Javascript, then using Javascript you can create DOM elements and then insert them into the page.
If it's PHP running at page render time on the server, then you can use PHP's echo to insert content into the page.
If it's PHP running in an Ajax call, then you can also use echo to construct a response to the Ajax call.
Here's an example of inserting content into the page from a user event using a Javascript function:
function insertContent(html) {
var div = document.createElement("div");
div.innerHTML = html;
document.body.appendChild(div);
}
document.getElementById("run").addEventListener("click", function() {
insertContent(document.getElementById("newContent").value);
});
<input id="newContent" value="Some Text"> <button id="run">Insert</button>

Basic JavaScript create table inquiry

I succeeded in creating a very basic (no 'for loops' used, I'm a beginner) table in JavaScript tagged onto an HTML button. It works perfectly!
<input type='button' value='Table' onclick='createTbl()' />
function createTbl() {
//set up elements
tbl = document.createElement('table');
tr = document.createElement('tr');
th1 = document.createElement('th');
th2 = document.createElement('th');
//contents
content1 = document.createTextNode('Last Name');
content2 = document.createTextNode('First Name');
//append
row1 = tbl.appendChild(tr);
row1.appendChild(th1).appendChild(content1);
row1.appendChild(th2).appendchild(content2);
//display
document.body.appendChild(tbl);
}
However, when I removed the enclosing function, ... :
//same code here but tagging the 'var' with each variable used
... everything disappears, leaving only the HTML button! I commented the button out, but no luck here as well.
How come? What is the magic table(t) to make it appear without enclosing it in a function?
Well, if it only works when it's within a function is because you call it from your onclick button. Otherwise the code is just there and nobody is calling it. Try calling the function when the dom has loaded to ensure everything is loaded (document.onload = createTbl)
Okay, so I partly figured out the problem: I forgot I was writing the script inside the head section of the HTML. I think that explained why the button worked flawlessly. So I moved only the code inside the function (coz I wanted it not to be a function) and placed it inside the script tag in the body section and hit refresh. At first nothing happened, until I added these:
<div id='table-div'>
<!--table here-->
</div>
script:
//display table
document.getElementById('table-div').appendChild(tbl);
And there it was! All that for a single row and two columns!
Out of curiosity, I wondered if it would work having the code back in the head section and applying my new found solutions. So with the code back in the head section, I made this slight change to display the table:
//display table
document.body.getElementById('table-div').appendChild(tbl);
No cigars here. Perhaps bad JavaScript lingo. Nevertheless, it was still good to find out that div was the magic table(t) my code needed.

How to remove a class via JavaScript (NOT jQuery) at Wordpress

I need your help at a problem of my Wordpress Webpage. My Wordpress-page is an Single-Page-App with 3 different boxes of content. The left and center boxes are static, the right one changes its content by clicking on links of the other boxes. I decided, to load all the content in the right box and show them with the CSS-command visibility. With a combination of pathJS and JS, i want the URL to change by clicking on the links. So far so good - all works fine, but i dont get managed via my JS-Function to remove the shown-class.
My script looks like this:
<script>
function showDetailContent(showid) {
//suche objekt right_id -> was du zeigen willst -> getelementbyid
alert("1");
var id = document.getElementsByClassName('shown');
alert("2");
id.classList.remove('shown');
alert("3");
document.getElementByID("right_" + showid).classList.add('shown');
alert("4");
}
//var c = document.getElementById('content'); -->do the function :)
Path.map("#/?p=<?php the_id();?>").to(function () {
showDetailContent(<?php the_id();?>);
});
Path.listen();
</script>
The alerts are just my way of "debugging". I think its not the best way to debugg, but i am very new in the world of prorgamming and this is kind of easy.
However, the first two alerts are shown, if i activate a link. So the (first) mistake is on the line
id.classList.remove('shown');
Normally, the right-box is hidden, so that only one content is load.
Do you understand my problem till here?
I would appreciate fast help!
Greetings, Yannic! :)
Look at this : http://snipplr.com/view/3561/ to know remove class pure javascript
getElementsByClassName gets multiple elements, try:
var id = document.getElementsByClassName('shown')[0];
Or iterate through them if you want to remove class from all elements with class shown;

Grails rendered content accessing id elements dynamically

AJAX content is being rendered with a remoteLink function inside the form to populate a accordion (just a little background info).
The function attatchEmail(test) which is being called on the double-click of each paragraph content of the JQuery Accordion widget. This is what happens running the function... Screenshot of 1st alert & Screenshot of 2nd alert.
Is it not possible to select the paragraph and get the contents from the paragraph like below?
(I have tried changing .val to .html and .text. I have also tried $('#'+testingID))
_form.GSP
function attatchEmail(test) {
$(document).ready(function()
{
var testingID = test.id;
alert(testingID);
var testingValue = $(testingID).val();
alert(testingValue);
});
};
_contactListAjax.GSP
<g:each in="${contactList}" status = "i" var="contact">
<h3>${contact.contactSurname +', '+ contact.contactForename}</h3>
<div><p id="contact${contact.id}" ondblclick="attatchEmail(this)">${'Email: '+contact.email}</p></div>
</g:each>
Run out of avenues to explore, I'm sure I've done something simple like this before perfectly fine :/
See two screenshots please for better insight, thanks
Well, it looks like you're using jQuery but it also looks like you're not really buying into the jQuery methodology. Mixing behavior with markup is not really considered a good practice these days, especially when using a library like jQuery. I'm not sure of your exact issue but I would recommend changing it to something like the following:
<g:each in="${contactList}" status = "i" var="contact">
<h3>${contact.contactSurname +', '+ contact.contactForename}</h3>
<div><p class="contact-email" data-id="${contact.id}">${'Email: '+contact.email}</p></div>
</g:each>
$(function() {
$("body").on("dblclick", ".contact-email", attachEmail);
});
function attatchEmail(event) {
var $element = $(event.target);
var id = $element.data("id");
};
This should help fix any issues with dynamic rendering because of the way the jQuery on function works.

Need Solution on NicEdit Insert HTML text into Instance

i am using this function to insert text into NicEdit,
function insertAtCursor(editor, value){
var editor = nicEditors.findEditor(editor);
var range = editor.getRng();
var editorField = editor.selElm();
editorField.nodeValue = editorField.nodeValue.substring(0, range.startOffset) +
value +
editorField.nodeValue.substring(range.endOffset, editorField.nodeValue.length);}
This code works fine for simple text but when i pass HTML content into it, it does not render the HTML output in div instead it dumps the HTML code as it is into the Instance Div.
Example:
<div class="one">Some text here</div>
This must show in the Instance as "Some text here"
and remaining code hidden in source code.
Can any one give me a solution to fix this problem?
After working whole night and trying different solutions I had finally got it working! :)
In case any one wants to know solution for this, I had to add a Replace function
replace()
for the content and made it support HTML.
See my answer HERE. It's a plugin I created to insert html at the cursor position.

Categories