i've got a chat (without any design until now)
<div id="chatHtml">
<input type="text" id="input-text-chat" placeholder="Enter Text Chat">
<div id="chat-container">
<div id=chatOutput class="chat-output"></div>
</div>
</div>
Now I have a button, which calls ja javascript function to open a new window
<button type="button" v-on:click="openChat">open chat</button>
openChat: function() {
win = top.consoleRef = window.open('', 'myconsole',
'width=350,height=250' +
',menubar=0' +
',toolbar=1' +
',status=0' +
',scrollbars=1' +
',resizable=1')
chat = document.getElementById("chatHtml").innerHTML;
win.document.write(chat);
}
And last there is the code that the chat is working
document.getElementById('input-text-chat').onkeyup = function(e) {
if (e.keyCode != 13) return;
// removing trailing/leading whitespace
// this.value = this.value.replace(/^\s+|\s+$/g, '');
if (!this.value.length) return
connection.send(this.value);
console.log(connection.send);
console.log(this.value);
appendDIV(this.value);
this.value = '';
};
var chatContainer = document.querySelector('.chat-output');
function appendDIV(event) {
var div = document.createElement('div');
div.innerHTML = event.data || event;
chatContainer.insertBefore(div, chatContainer.firstChild);
div.tabIndex = 0;
div.focus();
document.getElementById('input-text-chat').focus();
win.document.write(chatContainer.innerHTML);
}
My Problem:
The chat is not working in the new window but on the "index window" it is.
Im completely new to javascript and i dont know whats the problem.
I thik its because of the ID's or sth.
Can sb help me, that i can use the chat in the new window?
Thanks :)
the input of your new page hasn't have event yet so bind it's event
just add this
openChat: function(){
win =top.consoleRef=window.open('','myconsole',
'width=350,height=250'
+',menubar=0'
+',toolbar=1'
+',status=0'
+',scrollbars=1'
+',resizable=1')
chat = document.getElementById("chatHtml").innerHTML;
win.document.write(chat);
win.document.getElementById('input-text-chat').onkeyup = function(e) {
if (e.keyCode != 13) return;
// removing trailing/leading whitespace
// this.value = this.value.replace(/^\s+|\s+$/g, '');
if (!this.value.length) return
connection.send(this.value);
console.log(connection.send);
console.log(this.value);
appendDIV(this.value);
this.value = '';
};
}
after
win.document.write(chatContainer.innerHTML);
also it's better if you put a name it that event to lessen your code
Related
I am making an attempt to create my own chatroom using npm, as it stands everything is working smoothly but my main concern is SQL injection or people entering HTML because it will parse anything entered. There is no form being used and the input button, text field and output are all controlled by JavaScript. below is the part of the HTML I am referring to.
<div id="wrapper">
<div class="bubble-container" ></div>
</div>
<div id="sendCtrls">
<input type="text" placeholder="Your message here" id="text">
<button id="myBtn">Send</button>
</div>
This is my .php file which contains all the JavaScript.
<script>
// -------------------------
//var name = prompt('What is your name?');
var name = "<?php echo $_SESSION['username']; ?>";
var bubbles = 1;
var maxBubbles = 60;
var sock = new WebSocket("ws://localhost:5001");
sock.onopen = function() {
var bubble = $("#wrapper");
bubble = $('<div class="bubble-container"><span class="bubble"><div class="bubble-text">\
<p><b>*** Welcome '+name+' to the chat!</b><br>\
These are the rules, please read & follow them.<br>\
1. Be polite in chat.<br>\
2. Keep personal disputes out of chat.<br>\
3. No advertising.<br>\
4. Do not ask to become a Moderator.\
</p></div></div>');
myChat(bubble);
sock.send(JSON.stringify({
type: "name",
data: name
}));
}
// --------------------------
var maxLength = 200; // chars per bubble
sock.onmessage = function(event){
console.log(event);
var json = JSON.parse(event.data);
var bubble = $('<div class="bubble-container"><span class="bubble"><div class="bubble-text"><p><strong>'+json.name+':</strong> '+json.data+'</p></div></div>');
myChat(bubble);
}
// ---------------------------
document.querySelector('button').onclick = function (){
var text = document.getElementById('text').value;
if(text != "") {
if (text.length < maxLength) {
document.getElementById('text').value='';
sock.send(JSON.stringify({
type: "message",
data: text
}));
var bubble = $('<div class="bubble-container"><span class="bubble"><div class="bubble-text"><p><strong>'+name+':</strong> '+text+'</p></div></div>');
myChat(bubble);
}else{
var bubble = $('<div class="bubble-container"><span class="bubble"><div class="bubble-text"><p>*** Your message exceeds '+maxLength+' characters!</p></div></div>');
myChat(bubble);
};
}
};
// --------------------------
var input = document.getElementById("text");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("myBtn").click();
}
});
// --------------------------
function myChat(bubble){
$("#msgText").val("");
$(".bubble-container:last").after(bubble);
if (bubbles >= maxBubbles) {
var first = $(".bubble-container:first").remove();
bubbles--;
}
bubbles++;
$('.bubble-container').show(250, function showNext() {
if (!($(this).is(":visible"))) {
bubbles++;
}
$(this).next(".bubble-container").show(250, showNext);
$("#wrapper").scrollTop(9999999);
});
};
</script>
I have not included the server script which is also just JavaScript but can do so if needed. PHP has no interaction with what is being submitted. 2nd question is, will I need to write anything server side to protect against SQL injection or to prevent HTML being entered?
I'm certain I'm doing something stupid, or missing something silly but I get the follow 2 error messages, from client side onClick of a button:
Cannot set property 'class' of undefined
Cannot set property 'scrollTop' of null
All I'm trying to do is style an inputTextArea, and then scroll to the top of a scrollable content div that I have.
document.getElementById(x$("#{id:obj1Error}").Attributes["class"] = "has-error");
var myDiv = document.getElementById(x$("#{id:contentWhiteBackground}"));
myDiv.scrollTop = 0;
Any pointers appreciated. Cheers
UPDATE:
Client code on button:
// Make sure user has entered content into the first objective at minimum
var objcolparent = document.getElementById("ObjColOuter").children[0];
var objValue = objcolparent.getElementsByTagName("TEXTAREA")[0].value;
if(objValue ==""){
var o = {};
o.title = "Validation Failed";
o.body = "You must enter at least one objective before submitting";
o.alertIcon = "fa-thumbs-down fa-lg";
o.alertType = "danger";
var myDiv = document.getElementById("#{id:contentWhiteBackground}");
//document.getElementById("#{id:obj1Error}").className = "has-error";
myDiv.scrollTop = 0;
bootAlert.show('alertServer',JSON.stringify(o));
return false;
}
if(confirm("Are you sure you want to submit your objectives?")){
return true;
}else{
return false;
}
Code on xpage, which contains the obj1Error div:
<xp:repeat id="repeat1" rows="100"
value="#{viewScope.fields}" var="fieldName">
<xp:text escape="true"
id="computedField4" styleClass="h5">
<xp:this.value><![CDATA[#{javascript:"Objective "+#RightBack(fieldName, 16)}]]></xp:this.value>
</xp:text>
<br />
<xp:div id="obj1Error">
<xp:text escape="true"
id="computedField1" styleClass="h6">
<xp:this.value><![CDATA[#{javascript:"Details"}]]></xp:this.value>
</xp:text>
<xp:inputTextarea
id="inputTextarea1" style="height:100px;resize:none;"
showReadonlyAsDisabled="true">
<xp:this.value><![CDATA[#{document1[fieldName]}]]></xp:this.value>
<xp:this.disabled><![CDATA[#{javascript:try{
var strStatus:string = document1.getItemValueString("status");
var booDisabled:boolean = true;
if(strStatus == "New" || strStatus == "Draft" || strStatus == "Returned") {
booDisabled = false;
}
return booDisabled;
}catch(e){
writeToLog("Error - ccObjectives disable objective details: " + e);
}}]]></xp:this.disabled>
</xp:inputTextarea>
</xp:div>
<br />
</xp:repeat>
You just need to write
var myDiv = document.getElementById("#{id:contentWhiteBackground}");
to get the DOM element.
To set an element's class(es) you have to write:
document.getElementById("#{id:obj1Error}").className = "has-error";
I would recommend to work with the dojo toolkit in xpages instead of native javascript:
dojo.addClass('#{id:obj1Error}','has-error');
var myDiv = dojo.byId('#{id:contentWhiteBackground}');
myDiv.scrollTop = 0;
I have a form, and I would like to clear the input field every time I enter the submit (plus) button.
I have tried using this, it does not work. I may be implementing it in the wrong spot.
document.getElementById('add-item').value='';
My Javascript code is below.
window.addEventListener('load', function(){
// Add event listeners
document.getElementById('add-item').addEventListener('click', addItem, false);
document.querySelector('.todo-list').addEventListener('click', toggleCompleted, false);
document.querySelector('.todo-list').addEventListener('click', removeItem, false);
function toggleCompleted(event) {
console.log('=' + event.target.className);
if(event.target.className.indexOf('todo-item') < 0) {
return;
}
console.log(event.target.className.indexOf('completed'));
if(event.target.className.indexOf('completed') > -1) {
console.log(' ' + event.target.className);
event.target.className = event.target.className.replace(' completed', '');
document.getElementById('add-item').value='';
} else {
console.log('-' + event.target.className);
event.target.className += ' completed';
}
}
function addItem() {
var list = document.querySelector('ul.todo-list');
var newItem = document.getElementById('new-item-text').value;
var newListItem = document.createElement('li');
newListItem.className = 'todo-item';
newListItem.innerHTML = newItem + '<span class="remove"></span>';
list.insertBefore(newListItem, document.querySelector('.todo-new'));
}
function removeItem(event) {
if(event.target.className.indexOf('remove') < 0) {
return;
}
var el = event.target.parentNode;
el.parentNode.removeChild(el);
}
});
This is what you need:
document.getElementById('new-item-text').value = "";
regarding your need, you will need to put it at the end of your addItem()
you can refer this simple code:
<html>
<body>
<input type="text" id="test">
<button onclick="func()">remove</button>
<br/>
Value = <span id="val"></span>
<script>
function func(){
alert("clicked");
document.getElementById('val').innerHTML = document.getElementById('test').value;
document.getElementById('test').value = '';
}
</script>
</body>
</html>
Use form reset method to clear inputs in one go.
document.getElementById("myForm").reset();
You can set your textbox value = '' in submit button.
and you can create a ClearFunction and then you can call it everytime you need it.
function cleartextbox() {
$('#name').val("").focus();
$('#selectgender').val("");
$('#telephone').val("");
}
Currently I have a working app that could change the values of the buttons depending on the button clicked. It is written using javascript (in script.js). However I want to make it nicer so i am trying to use jQuery instead. However, when i insert the jQuery js and css file to index.html, the buttons' values are gone and i don't know how to change it completely to jQuery without affecting its function.
here is part of the original javascript: (let me know if you want to see the whole script)
ajax_status.onreadystatechange = function() {
if(ajax_status.readyState == 4 && ajax_status.status == 200) {
if(ajax_status.responseText == "ready_vid") {
document.getElementById("video_button").disabled = false;
document.getElementById("video_button").value = "record video start";
document.getElementById("video_button").onclick = function() {send_cmd("ca 1");};
document.getElementById("image_button").disabled = false;
document.getElementById("image_button").value = "record image";
document.getElementById("image_button").onclick = function() {send_cmd("im");};
document.getElementById("timelapse_button").disabled = false;
document.getElementById("timelapse_button").value = "timelapse start";
document.getElementById("timelapse_button").onclick = function() {send_cmd("tl " + (document.getElementById("tl_interval").value*10));};
document.getElementById("md_button").disabled = false;
document.getElementById("md_button").value = "motion detection start";
document.getElementById("md_button").onclick = function() {send_cmd("md 1");};
document.getElementById("halt_button").disabled = false;
document.getElementById("halt_button").value = "stop camera";
document.getElementById("halt_button").onclick = function() {send_cmd("ru 0");};
document.getElementById("mode_button").disabled = false;
document.getElementById("mode_button").value = "change mode to image";
document.getElementById("mode_button").onclick = function() {send_cmd("pm");};
halted = 0;
}
else if(ajax_status.responseText == "ready_img") {
document.getElementById("video_button").disabled = true;
document.getElementById("video_button").value = "record video start";
document.getElementById("video_button").onclick = function() {};
document.getElementById("image_button").disabled = false;
document.getElementById("image_button").value = "record image";
document.getElementById("image_button").onclick = function() {send_cmd("im");};
document.getElementById("timelapse_button").disabled = false;
document.getElementById("timelapse_button").value = "timelapse start";
document.getElementById("timelapse_button").onclick = function() {send_cmd("tl " + (document.getElementById("tl_interval").value*10));};
document.getElementById("md_button").disabled = true;
document.getElementById("md_button").value = "motion detection start";
document.getElementById("md_button").onclick = function() {};
document.getElementById("halt_button").disabled = false;
document.getElementById("halt_button").value = "stop camera";
document.getElementById("halt_button").onclick = function() {send_cmd("ru 0");};
document.getElementById("mode_button").disabled = false;
document.getElementById("mode_button").value = "change mode to video";
document.getElementById("mode_button").onclick = function() {send_cmd("vm");};
halted = 0;
}
HTML in index.html:
<input id="video_button" type="button">
<!--<button data-role="none" id="video_button"></button>
<button class="ui-btn ui-btn-inline" id="image_button"></button> //this is wad i tried-->
<input id="image_button" type="button">
<input id="timelapse_button" type="button">
<input id="md_button" type="button"><br>
<input id="halt_button" type="button">
<input id="mode_button" type="button">
I have some other jQuery scripts in index.html. The above javascript in in another file called script.js. My question is, do i also insert the link for jQuery.js in that script.js? And how about $(document).ready(function()? Do i put it in the script.js too?
For minimal change you can do following,
include the jquery library in tag as
<script type="text/javascript" src="static/jquery-1.10.2.min.js"></script>
replace document.getElementById('id') to $('#id').
document.getElementById("video_button") => $('#video_button')
Anything after the document.getElementById() get bit different in jquery
document.getElementById("video_button").disabled = false;
$('#video_button').removeAttr('disabled');
document.getElementById("video_button").value = "record video start";
$('#video_button').val('record video start');
document.getElementById("image_button").onclick = function() {send_cmd("im");};
$('#image_button').click(function() {send_cmd("im");});
references
https://api.jquery.com/removeAttr/
http://api.jquery.com/val
http://api.jquery.com/click/
I am having a problem setting/getting a hidden input's value with JavaScript, and can't see what I'm doing wrong.
What I am basically trying to do is maintain the state of expandable/collapsable divs on my page across form submissions. So I put a hidden input on the page to hold the state of the divs. When a div is expanded/collapsed, I change the value of the input. When the page loads, I read the value of the input and set the state of the divs.
But the value of the input is getting lost. I verify through alerts that it is being set correctly, and then when I read it on load, I verify with an alert that it is empty. Here is the pertinent code:
<input type="hidden" name="ECState" id="hdnECState" />
<script language="javascript" type="text/javascript">
<!--
var ecValue;
function ec(div, btn) {
//expands or collapses an error detail div
var e = document.getElementById(div);
var b = document.getElementById(btn);
var ecStr = div.toString() + ',' + btn.toString() + '|'
if (e.style.display == 'block') {
e.style.display = 'none';
b.src = '../../Images/plus.gif';
ecValue = ecValue.replace(ecStr, '');
}
else {
e.style.display = 'block';
b.src = '../../Images/minus.gif';
ecValue = ecValue + ecStr;
}
alert(ecValue);
document.getElementById('hdnECState').value = ecValue;
}
function reexpand() {
//restores the expanded state of the error detail divs
var pipe, comma, db, div, btn, e, b;
var n = document.getElementById('hdnECState').value;
alert('n=' + n);
if (n != '') {
pipe = n.indexOf('|');
while (pipe > 0) {
db = n.substring(0, pipe);
comma = db.indexOf(',');
if (comma > 0) {
div = db.substring(0, comma);
btn = db.substring(comma + 1);
e = document.getElementById(div);
b = document.getElementById(btn);
e.style.display = 'block';
b.src = '../../Images/minus.gif';
}
n = n.substring(pipe+1);
pipe = n.indexOf('|');
}
}
}
reexpand();
//-->
</script>
When I expand a div, I see the alert from ec() showing that ecValue is 'foo,bar|'.
But after submitting the form, I see the alert from reexpand() saying 'n='.
Anybody see what I'm missing?
You haven't posted Html part of your code. So I am a bit confused, But I think you should put some value first.
<input type="hidden" name="ECState" id="hdnECState" value="1" />
Rudu supplied the answer in a comment, but since I can't mark a comment as the answer, here it is:
I was forgetting that hidden inputs don't automatically keep their value in ViewState across form submissions. I needed to re-value the hidden input on the back end in page load and then everything worked fine.