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.
Related
HTML
<div>
<label>City:<input id="aqi-city-input" class="122" type="text" ></label><br>
<label>Point:<input id="aqi-value-input" type="text"></label><br>
<button id="add-btn">OK</button>
</div>
JavaScript
var CityName = document.getElementById('aqi-city-input');
var CityMore = document.getElementsByClassName('122');
var Quality = document.getElementById('aqi-value-input');
var Button = document.getElementById('add-btn');
console.log(document.getElementById('aqi-city-input')); //null
console.log(CityName); //null
console.log(CityMore); //html object
console.log(Quality); //null
console.log(Button); //null
There return null except the getElementsByClassName, do I have something wrong ?
You have to include your JavaScript after the HTML document like the following. If you are using a JavaScript file you have to include this after the HTML document too.
<div>
<label>City:<input id="aqi-city-input" class="122" type="text" ></label><br>
<label>Point:<input id="aqi-value-input" type="text"></label><br>
<button id="add-btn">OK</button>
</div>
<script src="path/to/your/script.js"></script>
<script>
var CityName = document.getElementById('aqi-city-input');
var CityMore = document.getElementsByClassName('122');
var Quality = document.getElementById('aqi-value-input');
var Button = document.getElementById('add-btn');
console.log(document.getElementById('aqi-city-input'));
console.log(CityName);
console.log(CityMore);
console.log(Quality);
console.log(Button);
</script>
You can also use the JavaScript before your HTML document, but in this case you have to wrap your code in a event listener DOMContentLoaded so the JavaScript executes if the HTML content is loaded (and JavaScript can see the HTML elements).
In case of a JavaScript file you should wrap your code into the event listener.
<script src="path/to/your/script.js"></script> <!-- content is wrapped in event listener -->
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var CityName = document.getElementById('aqi-city-input');
var CityMore = document.getElementsByClassName('122');
var Quality = document.getElementById('aqi-value-input');
var Button = document.getElementById('add-btn');
console.log(document.getElementById('aqi-city-input'));
console.log(CityName);
console.log(CityMore);
console.log(Quality);
console.log(Button);
});
</script>
<div>
<label>City:<input id="aqi-city-input" class="122" type="text" ></label><br>
<label>Point:<input id="aqi-value-input" type="text"></label><br>
<button id="add-btn">OK</button>
</div>
Move your javascript code below your HTML.Or execute it after the page has finished loading.In JQuery you can do like below:
<script>
$(document).ready(function() {
//... your code ...//
});
</script>
I have a similar problem to this post when trying to convert my apps script web app to use IFRAME Sandbox. I have converted to 'input = "button"' as suggested.
My web app is a simple form for students to use to sign in and out of a school library. The idea for the app is for it to be as easy as possible for students to use. Students should enter their id number and be able to either click the submit button or hit the enter key. Their ID is then validated before being stored in a spreadsheet and they get a message back saying thanks for signing in or out, or please enter a valid ID Number. Then focus should return to the text box and be cleared, ready for the next student to enter their id.
I had it working as described above using NATIVE mode. When I tried to convert it to IFRAME mode, clicking the button works, but if you hit the enter key everything just disappears and no data goes to the spreadsheet. How can I get hitting the enter key to work the same as clicking the submit button?
index.html code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<body>
<h3>Please Sign In & Out</h3>
<div id="box" class="frame">
<form id="signSheet" onsubmit="google.script.run
.withSuccessHandler(updateInfo)
.validateID(this.parentNode)">
<input type="text" name="myID" id="myID" placeholder="Enter your student ID" autocomplete="off">
<input type="button" value="Submit" onmouseup="google.script.run
.withSuccessHandler(updateInfo)
.validateID(this.parentNode)">
</form>
<span id="thank_you" hidden="true"></span>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<?!= include('javascript'); ?>
</body>
</html>
javascript.html code:
<script>
function updateInfo(ret){
if(ret[0]){
$( "#thank_you" ).removeClass("error");
$( "#thank_you" ).addClass("valid");
}
else{
$( "#thank_you" ).removeClass("valid");
$( "#thank_you" ).addClass("error");
}
$( "#thank_you" ).text(ret[1]);
$( "#thank_you" ).show("slow");
$( "#signSheet" )[0].reset();
$( "#myID" ).focus();
console.log(ret);
}
</script>
Code.gs code:
//spreadsheet key is needed to access the spreadsheet.
var itemSpreadsheetKey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
//Open the spreadsheet and get the sheet objects
var openedSS = SpreadsheetApp.openById(itemSpreadsheetKey);
var studentList = openedSS.getSheetByName("Student List");//Spreadsheet must match with sheet name
var studentRecord = openedSS.getSheetByName("Sign In-Out Record");
function doGet() {
var html = HtmlService.createTemplateFromFile('index').evaluate()
.setTitle('Sign In/Out Sheet')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
return html;
}
function include(filename) {
Logger.log('enter include');
Logger.log(filename);
var html = HtmlService.createHtmlOutputFromFile(filename).getContent();
Logger.log(html);
return html;
}
function validateID(form){
var idNum = form.myID;
var valid = false;
var numIdList = studentList.getLastRow()-1; //-1 is to exclude header row
//get the item array
var idArray = studentList.getRange(2,1,numIdList,1).getValues();
i= idArray.length;
while(i--){
if(idArray[i][0]==idNum & idNum!='') {
valid=true;
break;
}
}
if(valid)
return [1, updateRecord(idNum)];
else return [0, "ID number " + idNum + " not recognized. Please enter a valid ID number."];
}
function updateRecord(idNum){
studentRecord.appendRow([idNum]);
var formulas = studentRecord.getRange("B2:D2").getFormulasR1C1();
var lRow = studentRecord.getLastRow();
var range = studentRecord.getRange(lRow, 2, 1, 3);
range.setFormulas(formulas);
var vals = range.getValues();
var now = new Date();
studentRecord.getRange(lRow, 5, 1, 1).setValue(now);
now = Utilities.formatDate(now, "EST", "HH:MM a");
idNum = "Thanks " + vals[0][0] + ", you have signed " + vals[0][2] + " at " + now;
return idNum;
}
Update: I found this post and added the following code to javascript.html:
$(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13) {
var idVal = $("#myID").val();
google.script.run.withSuccessHandler(updateInfo).validateID(idVal);
return false;
}
});
})
This solved the the problem for me with a little more tweaking to parts of index.html and Code.gs
I found this post and added the following code to javascript.html:
$(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13) {
var idVal = $("#myID").val();
google.script.run.withSuccessHandler(updateInfo).validateID(idVal);
return false;
}
});
})
This listens for the enter key and sends the value of the text field to the apps script function. In this case I didn't need to use `event.preventDefault();'
Then I had to adjust the button's onmouseup function to take this.parentNode.myID and change my apps script function to take a value instead of a form object.
You must remove the onsubmit attribute from the <form> tag:
Currently you have:
<form id="signSheet" onsubmit="google.script.run
.withSuccessHandler(updateInfo)
.validateID(this.parentNode)">
Change it to this:
<form id="signSheet">
You already have a call to google.script.run in your button, so leave that.
im trying to change a line of text if a link is clicked, however it doesnt seem to be calling my script to change it.
<script >
var paragraphToChange = document.getElementById("q1");
paragraphToChange.innerHTML ="Quotation is by:" + Antole France
</script>
<div id="body">
<p>javascript.html - JavaScript page</p>
<a href id="q1">Quotaion is by:</a>
</div>
What you're trying to accomplish is probably something like this:
HTML
<div id="q1">
<a onClick="javascript:clickFunction()">Quotation is by</a>
</div>
JavaScript
clickFunction = function() {
document.getElementById("q1").innerHTML = "<a href='http://www.quotationspage.com/quote/1463.html'>Antole France</a>";
}
JSFiddle
Sir you have to set the value of "newValue" to the quotation.
var newValue = '"Quotation is by:" + Antole France'
paragraphToChange.innerHTML = newValue;
You are missing the click event on the Html tag. Hence, this paragraphToChange.innerHTML ="Quotation is by:" + Antole France"
never gets call.
Why don't you start with this example first:
<p id="display"></p>
<button onclick="displayBob">Bob</button>
<button onclick="displayTom">Tom</button>
<script>
displayBob = function ()
{
document.getElementById("display").innerHTML = "Hello Bob";
}
displayTom = function ()
{
document.getElementById("display").innerHTML = "Hello Tom";
}
</script>
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>
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.