I am working on a chat project, and have mostly finished everything that I needed. My chat box is a textarea and for the most part it works, until I wanted to implement changing the color of certain words in the chatbox by using regex.
But looking at how I have this set up:
function writeMessageToChatBox(message, from, serverMessage=false, direct=false){
let chat_box = $('#chatbox');
let val = chat_box.val();
if(!serverMessage){
if(direct){
console.log(replay);
if(replay){
chat_box.val(val + '[Whisper to: ' + tempRecepient + ' ] ' + from + ": " + message + "\n" );
replay = false;
tempRecepient = undefined
}
else{
chat_box.val(val + '[Whisper from: ' + from + ' ] ' + from + ": " + message + "\n" );
}
}
else{
chat_box.val(val + from + ": " + message + "\n");
}
}
else{
chat_box.val(val + message + "\n");
}
chat_box.scrollTop(document.getElementById("chatbox").scrollHeight);
I've come to realize that textareas hold text within them in their value, but the text are not elements within the textarea so I cannot pick and choose which text gets style. From some research I saw that what I'm trying to do is not possible with a textarea. What would be another option, I assume a div container that can hold text elements?
Use, <div> with contenteditable attribute.
.textarea{
width:200px;
height:50px;
border:1px solid black;
}
<div class='textarea' contenteditable>
</div>
contenteditable Attribute
Refactored the function but I had to guess on some parameters. Used Template Literals which are Strings on steroids -- they should be your best friend dealing with all that text. The method html() is used extensively so markup can be typed or inserted in as a string.
Demo
function writeMessage(message, from = '', reply = '', serverMessage = false, direct = false) {
let tempRx = '';
let chat = $('.chatbox');
let val = chat.text();
if (!serverMessage) {
if (direct) {
console.log(reply);
if (reply) {
chat.html(`${val} <mark>[Whisper to: ${tempRx} ]</mark> ${from}: ${message}<br>`);
reply = false;
tempRx = undefined;
} else {
chat.html(`${val} <mark>[Whisper from: ${from} ]</mark> ${from}: ${message}<br>`);
}
} else {
chat.html(`${val} ${from}: ${message}<br>`);
}
} else {
chat.html(`${val} ${message}<br>`);
}
chat.scrollTop(chat[0].scrollHeight);
}
writeMessage(`Whispering, whisper test, mumble test, <b style='color:red'>belch test</b>, 😫`, `<b style='color:green'>Rusty</b>`, 'reply', false, direct = true);
<form id='main' name='main'>
<fieldset class='chatbox' contenteditable='false'>
<legend>Status: </legend>
</fieldset>
<fieldset class='chatbox' contenteditable>
</fieldset>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Related
guys I need to add a class for div inside of a javascript function. I wanna put a box every agency_name, ADRESS_TEXT and phone How can I do this
function jsFilt(value) {
document.getElementById("myDiv").innerHTML = "";
value.AGENCY.forEach(agency => {
$("#myDiv").append(
//HERE "<div class ="xxx" style='border-style:ridge' ><strong>Agency Name :</strong> " + agency.agency_name + "<br>" +
"<strong>Adress : </strong> " + agency.ADRESS_TEXT + "<br> "+
"<strong>Phone :</strong> " + agency.phone + "<br></div>"
);
});
}
CSS
.xxx{
width: 220px;
padding: 10px;
border: 5px solid gray;
margin: 0px;
}
As others said there is two ways: .addClass('classname1 classname2') and .attr('class','classname1 classname2') but addClass is better
in your case will be like:
function jsFilt(value) {
console.log('running jsFilt');
//document.getElementById("myDiv").innerHTML = "";
$('#myDiv').html(''); // this is jquery way of doing it
console.log('myDiv is now empty');
value.AGENCY.forEach(agency => {
console.log('inside loop');
//first we create that div and give it class and style
const $div = $('<div></div>').addClass('xxx').attr('style','border-style:ridge;');
// here we set innerHTML
$div.html(`
<strong>Agency Name :</strong> ` + agency.agency_name + `<br>
<strong>Adress : </strong> ` + agency.ADRESS_TEXT + `<br>
<strong>Phone :</strong> ` + agency.phone + `<br>
`);
console.log('here is the div we created:',$div);
// here we append it to the container (#myDiv)
$("#myDiv").append($div);
console.log('this is how myDiv looks like now', $("#myDiv"));
});
}
make sure you call the function of course jsFilt(someValue)
I put some console.log('bla bla') in my codes if you open browser console you can see some messages being printed out and it helps you track issue. after everything worked you can remove console.log()s
So this may work or may have some syntax errors. Let me know if you could get it to work
You can addClass to the div after the append like:
function jsFilt(value) {
document.getElementById("myDiv").innerHTML = "";
value.AGENCY.forEach(agency => {
$("#myDiv").append(
"<strong>Adress : </strong> " + agency.ADRESS_TEXT + "<br> "+
"<strong>Phone :</strong> " + agency.phone + "<br></div>"
).addClass("CLASSNAME1 CLASSNAME2");
});
}
I Have 3 input text in a form, that i would like to joini like this after pressing a button:
TextA-TextB TextC.
I also would like that will be positioniting on th first free line of the text area.
if for eaxmple ther is this situation:
2018-12345 25.00,
i would like that inserting the datas in the 3 text, will become like this:
2018-12345 25.00
TextA-TextB TextC
I imagine that i need javascript and calling the function with event onclick on the button, but i am not into javascript, because of that i am asking for your kind help.
Thanks for the fast answer.
I tried to combine a couple of codes that i found online, but i always get error 404 when I try it on fiddle:
<script>
function fillMessage() {
var annoTA1 = document.getElementById('annoTA') + " ";
var numTess1 = document.getElementById('numTess') + " ";
var impVer1 = document.getElementById('impVer1') + " ";
msg.value = annoTA1.value + numTess1.value + impVer1.value;
var targ = event.target || event.srcElement;
document.getElementById("message").value += targ.textContent || targ.innerText;
var Message= "";
function addText(text) {
Message+= text
}
document.getElementById("message").value = Message;
} </script>
and for the onclick event I used:
<button onclick="fillMessage()">Aggiungi Nuova Tessera</button>
the original fiddle is this:
http://jsfiddle.net/qmrt7z0w/
and plus I added
var Message= "";
function addText(text) {
Message+= text to test there before.
I solved with this script:
<script>
$('#btn').on('click', function (){
var insertText = $('#annoTA').val() + " ";
insertText += $('#numTess').val() + " ";
insertText += $('#impVer').val() + " ";
if(document.getElementById("annoTAG").value == ' ')
{
$('#annoTAG').val( $('#annoTAG').val() + insertText);
}
else
{
$('#annoTAG').val( $('#annoTAG').val() + '\n' + insertText);
}
});
</script>
And for the button i had to use:
<input type="button" value="Aggiungi Nuova Tessera" id="btn" />
Otherwise is not working...
Everything works good now, just that when I am inserting. The first row, it starts with a space. I tried to adding the backspace like this:
if(document.getElementById("annoTAG").value == ' ')
{
$('#annoTAG').val( $('#annoTAG').val() + '\b '+ insertText);
}
But did not works. Any suggestions?
Thanks
My previous problem has been fixed, now I need to ask how to keep a textarea from resetting its input after a form is submitted. Here is the jsFiddle: http://jsfiddle.net/rz4pnumy/
Should I change the form in the HTML?
<form id="form1" method="GET">
(the form does not go into a php file or anything else, i'm using it to submit the textarea input and use the variables I made using jQuery to make a paragraph on the same page)
or something in the JS?
$(document).ready( function () {
$('#form1').on('submit', function (event) {
// If the form validation returns false, block the form from submitting by
// preventing the event's default behaviour from executing.
if (!validate()) {
event.preventDefault();
}
if(validate()) {
var adjective1 = $('#adjective1').val();
var adjective2 = $('#adjective2').val();
var pluralnoun = $('#plural-noun').val();
var verb1 = $('#verb1').val();
var edibleobject = $('#edible-object').val();
var monster1 = $('#monster1').val();
var adjective3 = $('#adjective3').val();
var monster2 = $('#monster2').val();
var verb2 = $('#verb2').val();
$('body').append(
'<div id="para">' +
'<p>Rain was still lashing the windows, which were now ' + adjective1 +', but inside all looked bright and cheerful. ' +
'The firelight glowed over the countless ' + adjective2 + '' + pluralnoun + ' where people sat ' + verb1 + ', talking, ' +
'doing homework or, in the case of Fred and George Weasley, trying to find out what would happen if you fed a ' + edibleobject +' to a ' + monster1 + '.' +
'Fred had "rescued" the ' + adjective3 + ', fire-dwelling ' + monster2 + ' from a Care of Magical Creatures class and it was now ' + verb2 + ' gently ' +
'on a table surrounded by a knot of curious people. </p>' +
'</div>'
);
}
});
function validate() {
var success = true;
$('.input').each(function(i, item) {
if ($(item).val() === "")
{
console.log("Missing textarea input");
success = false;
$(item).attr("style","border:1px solid red;");
//note it will overwrite your element style in all Input class
}
else
{
$(item).removeAttr('style')
// to remove border
}
});
return success;
}
});
The contents get emptied after pressing submit and I only see the completed paragraph for a split second.
You need to prevent the default event handler from executing whether validate passes or not, so you need to remove the if statement around the event.preventDefault() call. The preventDefault is the function that is keeping the from from submitting and re-loading your page.
Also, your Fiddle was not set to jQuery (it was set to no-library) so that may have also been causing you issues during your testing.
Edited for example of what I'm talking about:
$('#form1').on('submit', function (event) {
// block the form from submitting by
// preventing the event's default behaviour from executing.
event.preventDefault();
if(validate()) {
var adjective1 = $('#adjective1').val();
var adjective2 = $('#adjective2').val();
var pluralnoun = $('#plural-noun').val();
... etc ...
I would use php and set a variable to the GET value of the textarea and set the value of the textarea to that variable
I need the values of the name, address, size, and topping fields to appear in a text box. Without problems the name and address appears correctly. However I can't seen to get the size function to work. It is a radio button, and thus I need only one size to appear. I haven't even tried an if else for the checkbox yet. Here is my code
<html>
<head>
<script>
function pizza() {
document.pizzaboy.comments.value = "Name:" + " " + pizzaboy.name.value + "\n" + "Address:" + " " + pizzaboy.address.value + "\n" + document.getElementById("small").value + document.getElementById("medium").value + document.getElementById("large").value + "\n" + pizzaboy.toppings.value;
{
var rslt = "";
if (document.pizzaboy.size[0].checked) {
rslt = rslt + "Size=Small\n";
} else if (document.pizzaboy.size[1].checked) {
rslt = rslt + "Size=Medium\n";
} else rslt = rslt + "Size=Large\n";
return rslt;
}
}
</head>
The second Javascript bracket might be throwing you an error, keeping your code from running correctly.
In this post, several (more general) ways to get values of radio buttons are explained:
Checking Value of Radio Button Group via JavaScript?
The first answer is using jQuery, but the following answers will help you i think.
You should try this. Answer here if you need further assistance.
I'm attempting to split a string I'm passing into
$("#groupUL").append("<li>" + "<h2>About Item:</h2> " + response.data[i].message + "<br /> " + "<h2>Posted By:</h2> <a href='#' onclick='splitName('" + response.data[i].from.name + "');'>" + response.data[i].from.name + "</a>" + "<br />");
Seems to be passing me the error
SyntaxError: syntax error
splitName(
Not sure how that's wrong...Here is the splitname function if that helps
function splitName(txt){
var myString = txt;
var mySplitResult = myString.split(" ");
console.log("The first element is " + mySplitResult[0]);
console.log("<br /> The second element is " + mySplitResult[1]);
console.log("<br /> The third element is " + mySplitResult[2]);
};
It's too hard to get it right when you put quotes in quotes in quotes and you try to escape it right. You got it wrong.
A solution is to make it in small parts :
var action = "splitName('" + response.data[i].from.name + "');";
$("#groupUL").append("<li>" + "<h2>About ... onclick=\""+action+"\">...");
But the best solution would be to follow best practice, that is not inline the javascript but use jQuery's binding function :
$("#groupUL").append("... <a id=myid ...");
$("#myid").click(function(){ splitName(response.data[i].from.name) });
I think the only problem with your code is with your readability issue. So I would suggest please improve it. Lets have a look at it. My code example # JSbin.
Here is the code :- (which i think is better)
var response = {
data : {
message: 'Cleaning code',
from: {
name: 'Clean Code works'
}
}
};
var li = $('<li>'); //Create empty li (Not Appending to DOM now due to performance issues)
$('<h2>').html('About Item:' + response.data.message + '<br />').appendTo(li);
$('<h2>').html('Posted By:').appendTo(li);
$('<a>').attr('href', '#')
.html(response.data.from.name)
.appendTo(li)
.click(function() {
splitName(response.data.from.name);
});
$('<br>').appendTo(li);
// Append li to ul (Final operation to DOM)
li.appendTo('#groupUL');
function splitName(txt){
var myString = txt;
var mySplitResult = myString.split(" ");
console.log("The first element is " + mySplitResult[0]);
console.log("The second element is " + mySplitResult[1]);
console.log("The third element is " + mySplitResult[2]);
}