Using prototype in javascript - javascript

I have defined a couple of functions inside my javascript which work perfectly, but when I put it inside a prototype it just doesn't seem to work.
wall.html:
<script type="text/javascript" src="Jquery/jquery-1.4.4.js"> </script>
<script type="text/javascript" src="src/CommentManager.js"> </script>
<script type="text/javascript" src="src/Reply.js"> </script>
<script type="text/javascript" src="src/Comment.js"> </script>
<script type="text/javascript">
$(document).ready(function(){
CommentManager();
$("form#newMessage").submit(function(){
var message = $("input#newMessageTxt").val();
var newComment = new Comment(message);
});
});
</script>
</head>
<body>
<div class="message">
<form id="newMessage">>
<input type="text" id="newMessageTxt" height="200px" value="Write a message" onfocus="if(this.value==this.defaultValue) this.value='';" onblur="if(this.value=='') this.value=this.defaultValue;" />
<input type="submit" value="Submit" ></button>
</form>
</div>
</body>
but the weird part is when I run the debugging tool in googlechrome, the $("form#newMessage").submit doesn't call at all. So Comment(message) is never created (which is where I have set up the prototype functions)
Comment.js:
function Comment(message){
var self = this;
var message = message;
var comment = document.createElement("li");
comment.id = "comment";
comment.textContent = message;
//empty reply field
var replyField = document.createElement("ul");
replyField.id = "replyField";
//create the appropriate buttons
createButtons(comment);
//append the replyField
comment.appendChild(replyField);
//insert into wall
addComment(comment);
//effect after insertion
Effect(comment);
$(comment).mouseleave(function() {mouseOut(comment);});
$(comment).mouseenter(function() {mouseOver(comment);});
return comment;
}
Comment.prototype={
deleteComment : function (comment){
$(comment).fadeOut();
setTimeout(function() {comment.parentNode.removeChild(comment);},500);
},
//there are more methods here
}
Commentmanager.js:
function CommentManager(){
var owner = null;
var wall = document.createElement("ul");
wall.id = "wall";
document.body.appendChild(wall);
return wall;
}
function addComment(comment){
var wall = document.getElementById("wall");
wall.appendChild(comment);
}

Where is createButtons defined? (in Comment.js)?
Also, you you titled that last file as Commentmanager.js, but wall.html has CommentManager.js (notice the capital M in wall.js). I'm assuming that's a typo here in the SO question, but make sure that your filenames on the server match the html script tags.

Related

Clearing a text box using a JavaScript function

I have the following code for a jscript implementation of skulpt to run Python in the browser. I have added a "clear" button, and when it is clicked, I want the text inside the textbox, as well as any "run" code, to be deleted/cleared from the screen.
The below shows my attempt (the function "clearit") but it doesn't work. Any suggestions - please post code for that function with an explanation for what I was doing wrong/corrections.
Relevant function
function clearit(){
var prog = document.getElementById("yourcode").value;
mypre.innerHTML = 'TRY SOME NEW CODE';
<textarea id="yourcode" cols="40" rows="10">
print("Hello World")
</textarea>
}
I paste the full code below, because it could be down to the fact that I am putting the function in wrong place. It stops working altogether once I add this function.
Full code (page.html)
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js" type="text/javascript"></script>
<script src="http://www.skulpt.org/js/skulpt.min.js" type="text/javascript"></script>
<script src="http://www.skulpt.org/js/skulpt-stdlib.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
// output functions are configurable. This one just appends some text
// to a pre element.
function outf(text) {
var mypre = document.getElementById("output");
mypre.innerHTML = mypre.innerHTML + text;
}
function builtinRead(x) {
if (Sk.builtinFiles === undefined || Sk.builtinFiles["files"][x] === undefined)
throw "File not found: '" + x + "'";
return Sk.builtinFiles["files"][x];
}
// Here's everything you need to run a python program in skulpt
// grab the code from your textarea
// get a reference to your pre element for output
// configure the output function
// call Sk.importMainWithBody()
function runit() {
var prog = document.getElementById("yourcode").value;
var mypre = document.getElementById("output");
mypre.innerHTML = '';
Sk.pre = "output";
Sk.configure({output:outf, read:builtinRead});
(Sk.TurtleGraphics || (Sk.TurtleGraphics = {})).target = 'mycanvas';
var myPromise = Sk.misceval.asyncToPromise(function() {
return Sk.importMainWithBody("<stdin>", false, prog, true);
});
myPromise.then(function(mod) {
console.log('success');
},
function(err) {
console.log(err.toString());
});
}
<script>
function clearit(){
var prog = document.getElementById("yourcode").value;
var mypre = document.getElementById("output");
<textarea id="yourcode" cols="40" rows="10">
print("Hello World")
</textarea>
}
</script>
</script>
<h3>Try This</h3>
<form>
<textarea id="yourcode" cols="40" rows="10">
print("Hello World")
</textarea><br />
<button type="button" onclick="runit()">Run</button>
</form>
<p>Output below</p>
<button type="button" onclick="clearit()">Clear</button>
<pre id="output" ></pre>
<!-- If you want turtle graphics include a canvas -->
<div id="mycanvas"></div>
<script src="js/skulpt.min.js" type="text/javascript"></script>
<script src="js/skulpt-stdlib.js" type="text/javascript"></script>
</body>
</html>
I also tried some other iterations of the function, see below.
<script>
function clearit(){
var prog = document.getElementById("yourcode").value;
var mypre = document.getElementById("output");
mypre.innerHTML = 'TRY SOME NEW CODE';
<textarea id="yourcode" cols="40" rows="10">
print("Hello World")
</textarea>
}
</script>
To clarify: The mypre.innerHtml worked...but not clearing the textbox with the code. The part I want to implement is to clear the textarea. If I remove the part with <textarea id..) etc the code works fine, and also clears the OUTPUT console. I need the next bit (clearing the textarea) working.
You have an un-necessary HTML tag textarea inside your clearit function, which was causing an error (check in console). It is not required since you already have textarea in your HTML block. Try below (It is not full code only clearit implementation):
function clearit() {
var prog = document.getElementById("yourcode").value;
var mypre = document.getElementById("output");
document.getElementById("yourcode").value = '';
}
<h3>Try This</h3>
<form>
<textarea id="yourcode" cols="40" rows="5">
print("Hello World")
</textarea><br />
<button type="button" onclick="runit()">Run</button>
</form>
<p>Output below</p>
<button type="button" onclick="clearit()">Clear</button>
<pre id="output"></pre>
<!-- If you want turtle graphics include a canvas -->
<div id="mycanvas"></div>
</body>
Your function should look like this:
function clearit(){
document.getElementById('yourcode').value = '';
document.getElementById('output').innerHTML = '';
}
You also have too many script tags, remove the ones around the clearit() function.

How to push data from custom HTML form into Sharepoint list

I´be been searching this for some time now and have not found a working solution yet.. I have custom form written in HTML (it is quite big and complicated) and some rules in JS attached to it and what I need is to insert it into iframe (web content editor) in SP and push the data into existing list on the same site.. I have found some JS libraries like SPservices and Sharepoint plus but was not able to make it work..
I cannot use infopath unfortunately - otherwise it would be easy.
Does anybody know how to do it or give me some simple example of code?
Thanks in advance!!!
Edit:
So I have this simple html form inserted using web content editor is SP:
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/jquery-ui.min.js"></script>
<script src="_layouts/15/sp.js" type="text/javascript"></script>
<script src="js/list.js"></script>
Nadpis: <input type="text" id="nadpis"> <br>
Text: <input type="text" id="text"> <p></p>
<input type="button" value="Odeslat" id="submit">
and this is list.js
$("#submit").click(function(){
var vnadpis = document.getElementById("nadpis").value;
var vtext = document.getElementById("text").value;
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() {
var ctx = SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle("Test");
var itemCreateInfo = new SP.ListItemCreationInformation();
var oListItem = list.addItem(itemCreateInfo);
oListItem.set_item("Nadpis",vnadpis);
oListItem.set_item("Text",vtext);
oListItem.update();
ctx.load(oListItem);
ctx.executeQueryAsync(
Function.createDelegate(this, function(){alert("Success!")}),
Function.createDelegate(this, function(){alert("Error!")}));
}
});
but nothing happens.. suggestions?
try to wrap your code inside $( document ).ready(). So that your code will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
Refer below code. It will work for you.
$(document).ready(function() {
$("#submit").click(function() {
var vnadpis = document.getElementById("nadpis").value;
var vtext = document.getElementById("text").value;
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() {
var ctx = SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle("Test");
var itemCreateInfo = new SP.ListItemCreationInformation();
var oListItem = list.addItem(itemCreateInfo);
oListItem.set_item("Nadpis", vnadpis);
oListItem.set_item("Text", vtext);
oListItem.update();
ctx.load(oListItem);
ctx.executeQueryAsync(
Function.createDelegate(this, function() {
alert("Success!")
}),
Function.createDelegate(this, function(sender, args) {
alert("Error!")
}));
});
});
});
HTML -->
Note - Change JS reference path accordingly. And try to reference JS files in this sequence.
<script src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>
<script src="/_layouts/15/sp.runtime.js"></script>
<script src="/_layouts/15/sp.js"></script>
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/jquery-ui.min.js"></script>
<script src="js/list.js"></script>
Nadpis: <input type="text" id="nadpis"> <br>
Text: <input type="text" id="text"> <p></p>
<input type="button" value="Odeslat" id="submit">
It is like a cooking recipe. It is fairly easy. Following example takes the List "MyList" and adds a new Item with title "MyNewItem" to it. Make sure you included the necessary sharepoint javascript libraries.
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() {
var ctx = SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle("MyList");
var itemCreateInfo = new SP.ListItemCreationInformation();
var oListItem = list.addItem(itemCreateInfo);
oListItem.set_item("Title","MyNewItem");
oListItem.update();
ctx.load(oListItem);
ctx.executeQueryAsync(
Function.createDelegate(this, function(){alert("Success!")}),
Function.createDelegate(this, function(){alert("Error!")}));
}
So just replace the string with your input value (retrieved by plain JS or with jQuery)

calling Jquery Function not working

I'm currently following a tutorial and the person in the tutorial is coding css, html, and jquery all in one file. I split them up into seperate files. My problem is the code in the tutorial works when calling a function and mine does not, even though the code is exactly the same. Here is some of my code
//Jquery File
function username(){
$("#container").html("<span class = 'bot'>Chatbot: </span>Hello, what is your name?");
}
$(function(){
username();
$("#textbox").keypress(function(event){
........
HTML File
<div id = "container">
</div>
<div id = "controls">
.....
Tutorial Code
<script type="text/javascript">
function username(){
$("#container").html("<span class = 'bot'>Chatbot: </span>Hello, what is your name?");
}
$(function(){
username();
$("#textbox").keypress(function(event){
.......
It's exactly the same but for some reason my code does not work, I tested out both. And i know I'm linking to the correct jQuery files because my other function work fine no problem.
Full HTMl
JQuery Chatbot Tutorial
jQuery Chatbot v. 1.0 Tutorial
<div id = "container">
</div>
<div id = "controls">
<textarea id = "textbox" placeholder = "Enter your message here..."></textarea>
<button id = "send">Send</button>
<br>
<input checked type = "checkbox" id = "enter"/>
<label>Send on enter</label>
</div>
<script type="text/javascript" src="jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="chatbot.js"></script>
</body>
Full JQuery File
function username(){
$("#container").html("<span class = 'bot'>Chatbot: </span>Hello, what is your name?");
}
$(function(){
username();
$("#textbox").keypress(function(event){
if ( event.which == 13){
if ( $("#enter").prop("checked") ){
$("#send").click();
event.preventDefault();
}
}
});
});
$("#send").click(function(){
var username = "<span class ='username' = >You: </span>";
var newMessage = $("#textbox").val();
$("#textbox").val("");
var prevState = $("#container").html();
if (prevState.length > 3){
prevState = prevState + "<br>";
}
$("#container").html(prevState + username + newMessage);
$("#container").scrollTop($("#container").prop("scrollHeight"));
});
You might have error in the code before the call. Try:
$(function(){
alert('Debug me 2');
username();
alert('Debug me 2');
...
and see what happens.

Issue trying to get website to work - possible issue with my html code?

SO I have code that I'm trying to implement from my jsfiddle into an actual working website/mini-app. I've registered the domain name and procured the hosting via siteground, and I've even uploaded the files via ftp so I'm almost there...
But I'm thinking there's something wrong with my HTML code or JS code or how I implemented my JS code into my HTML code, because all of the HTML and CSS elements are present, but the javascript functionality is absent.
Here is my fiddle:
jsfiddle
^^ Click on start to see the display in action (which doesn't work in the actual website, which leads me to believe there's an issue with my JS file - whether it be code-related or whether that's because I integrated the file incorrectly) (or maybe even uploaded to the server incorrectly, perhaps?)...
And here is the actual site:
http://www.abveaspirations.com/index.html
And here's my HTML code uploaded to the server via FTP:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div id='frame'>
<div id='display'>
<h1 id='output'></h1>
</div>
</div>
<div class="spacer">
</div>
<div id="main"> <!-- 11main -->
<h1 id='consoleTitle'>Control Board</h1>
<h5 id='consoleSub'><i>Double-click on an entry to remove. And add entries to your heart's desire...</i></h5>
<div id="controlbox"> <!-- ##controlbox -->
<div id="controlpanel"></div>
<div class="spacer"></div>
<div id="formula"> <!--formula -->
<form id="frm" method="post">
<input id="txt" type="text" placeholder="Insert your own entry here..." name="text">
<input id='submitBtn' type="submit" value="Start">
<input id='stop' type="button" value="Stop">
<select id="load1">
<option id='pre0' value="Preset 0">Preset 0</option>
<option id='pre1' value="Preset 1">Preset 1</option>
<option id='pre2' value="Preset 2">Preset 2</option>
</select>
<!-- These are for buttons as opposed to OPTION...
<input id="load" type="button" value="Preset 1">
<input id="load2" type="button" value="Preset 2"-->
</form>
</div> <!-- formula -->
</div> <!-- ##controlbox -->
</div> <!-- 11main -->
</body>
And my JS code, also uploaded to server via FTP (I didn't include the accompanying CSS file, but if that would help, I can provide ):
$(document).ready(function () {
var txtBox = $('#txt');
var frm = $('#frm');
var output = $('#output');
var subBtn = $('#submitBtn');
var stopBtn = $('#stop');
var loadBtn = $('#load');
var loadBtn2 = $('#load2');
var loadBtnA = $('#load1');
var pre0 = $('#pre0');
var pre1 = $('#pre1');
var pre2 = $('#pre2');
var txt = $('#display');
var preset1 = ["1", "2", "3"];
var preset2 = ["a", "b", "c"];
var container = ["What we do in life echoes in all eternity.", "Find your purpose and give it life.", "When you work your hardest, the world opens up to you."];
var console = $('#controlpanel');
var oldHandle;
function loadPreset0() {
container = [];
console.empty();
container = ["What we do in life echoes in all eternity.", "Find your purpose and give it life.", "When you work your hardest, the world opens up to you."];
updateConsole();
};
function loadPreset1() {
container = [];
console.empty();
container = preset1;
updateConsole();
};
function loadPreset2() {
container = [];
console.empty();
container = preset2;
updateConsole();
};
$(pre0).data('onselect', function() {
loadPreset0();
});
$(pre1).data('onselect', function() {
loadPreset1();
});
$(pre2).data('onselect', function() {
loadPreset2();
});
$(document).on('change', 'select', function(e) {
var selected = $(this).find('option:selected'),
handler = selected.data('onselect');
if ( typeof handler == 'function' ) {
handler.call(selected, e);
}
});
function updateConsole() {
for (var z = 0; z < container.length; z++) {
var resultC = container[z];
var $initialEntry = $('<p>' + '- ' + resultC + '</p>');
console.append($initialEntry);
};
};
updateConsole();
frm.submit(function (event) {
event.preventDefault();
if (txtBox.val() != '') {
var result = txtBox.val();
container.push(result); //1.
var resultB = container[container.length-1];
var $entry = $('<p>' + '- ' + resultB + '</p>');
console.append($entry); //2.
}
var options = {
duration: 5000,
rearrangeDuration: 1000,
effect: 'random',
centered: true
};
stopTextualizer();
txt.textualizer(container, options);
txt.textualizer('start');
txtBox.val('');
});
$("#controlbox").on('dblclick', 'p', function() {
var $entry = $(this);
container.splice($entry.index(), 1);
$entry.remove();
});
function stopTextualizer(){
txt.textualizer('stop');
txt.textualizer('destroy');
}
$(stopBtn).click(function() {
stopTextualizer();
});
});
Any help would be appreciated. I guess I'm just not sure what to do after uploading the html file to the server via ftp. Or maybe I did that correctly and there's something wrong with my code that I'm overlooking. Basically I'm lost. So help please!
You forgot to load jQuery. Make sure that you use <script src="../path-to-jquery/jquery.js"></script> before you load your script.js script.
Also, I noticed that you're loading your scripts in the head tag. This is bad practice, load them right before </body>.
I believe your site is missing jQuery. Add this to the top of your code to hotlink to google's jQuery.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

Google Places Autocomplete on dynamic inputs

Good day.
I'm trying to add Google Places Autocomplete on dynamically created inputs using code below:
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
var _autoComplCounter = 0;
function assignAutoCompl(_id)
{
var _autocomplete = new google.maps.places.Autocomplete(document.getElementById(_id));
_autocomplete.setTypes(['geocode']);
google.maps.event.addListener(_autocomplete, 'place_changed', function()
{
//processing code
});
}
function CreateElem()
{
var _id = "AutoCompl" + _autoComplCounter;
_autoComplCounter++;
var container = document.getElementById('AutoComplInputs');
container.innerHTML += "<br>" + _id;
var _elem_for_upd = document.createElement("input");
_elem_for_upd.type = "text";
_elem_for_upd.id = _id;
container.appendChild(_elem_for_upd);
assignAutoCompl(_id);
}
</script>
</head>
<body>
<div id="AutoComplInputs"></div>
<input type='button' value='Add' onclick='CreateElem();'>
</body>
</html>
But when I press on button, autocomplete works only on last input, and all prevoius become broken. I think that it can be connected to dynamic creation of inputs, as the code below works fine:
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
var _autoComplCounter = 0;
function assignAutoCompl(_id)
{
document.getElementById(_id).hidden = false;
var _autocomplete = new google.maps.places.Autocomplete(document.getElementById(_id));
_autocomplete.setTypes(['geocode']);
google.maps.event.addListener(_autocomplete, 'place_changed', function()
{
//processing code
});
}
function CreateElem()
{
assignAutoCompl("AutoCompl0");
assignAutoCompl("AutoCompl1");
}
</script>
</head>
<body>
<div id="AutoComplInputs">
<input id="AutoCompl0" type="text" hidden>
<input id="AutoCompl1" type="text" hidden>
</div>
<input type='button' value='Add' onclick='CreateElem();'>
</body>
</html>
I don't understand what I'm doing wrong ...
Don't use innerHTML to add content to container, you will lose all handlers bound to existing elements.
Use appendChild instead:
container.appendChild(document.createElement('br'));
container.appendChild(document.createTextNode(_id));

Categories

Resources