Unhide hidden words that have been removed from text box - javascript

I would like to allow users to select given words from a word bank and place those into a text box, where they will be removed (hidden) from the word bank. If the user makes a mistake and wants the word back, they can delete it from the text box which will place it back in the word bank.
How can this be done? (Please forgive the horrific ms paint image)
HTML:
Create sentence:
<input type="text" id="textBox" value="" />
<br/>
<button onclick="submitMe()" id="testButton" >Submit Response </button>
<br/>
<div class="wordBank_Headings">Word Bank:
<span class="wordBank_Words"></span>
</div>
JavaScript:
You will see here a portion that says /*THIS IS THE PORTION I AM HAVING TROUBLE WITH*/. I am trying to get all words from text box... if word is hidden and does not exist in text box... add it back to the Word Bank.
$(document).ready(function() {
playerResponse();
$(".bank-word").click(function (event) {
//append each newly selected word to $('#textBox').val()
$('#textBox').val($('#textBox').val() + " " + $(this).attr('word'));
//hide word from word bank
$(this).hide();
/*THIS IS THE PORTION I AM HAVING TROUBLE WITH*/
//Get all words from text box
//if word is hidden and does not exist in text box... add it back
$.each($('#textBox').val().split(/\s+/), function(index, word) {
console.log( index + ": " + word);
$('li.bank-word').find(':hidden').each(function(index) {
log("index : " + index + ", " + $(this).text());
$(this).show(); //reveal word in word bank again after we find that it is hidden AND has been deleted from text box
});
});
});
});
var words = {
"task1" :
{
'Ni' : 'you',
'Wo' : 'I',
'Hao' : 'good',
'Shi' : 'am'
}
}
function bank() {
$(".wordBank_Words").empty();
for (obj in words) {
for (key in words[obj]) {
$(".wordBank_Words").append("<li class='bank-word' word='" + key + "' ><b>" + key + "</b>: " + words[obj][key] + "</li>");
}
}
}
function submitMe() {
//will eventually verify input from textbox
var value = document.getElementById('test').value;
alert(value);
}
EDIT:
var array = [];
var i = 0;
$.each($('#textBox').val().split(/\s+/), function(index, word) {
array.push(word);
log("ARRAY: " + array[i] + array.length);
i++;
console.log( index + ": " + word);
for (obj in words) {
for (key in words[obj]) {
//if word doesn't exist in text box, and doesn't exist in word bank, add it
if (!isInArray(key, array) && is in wordbank...) {
key.show(); //pseudo code
}
}
}
});
function isInArray(value, array) {
return array.indexOf(value) > -1;
}

Related

Javascript in HTML: How to insert a user input into the middle of a string automatically?

ProgLang: Javascript in HTML
Issue: I'm getting a user input via a comment box (their name) and want to have it inserted mid strings throughout the rest of the code. For example: 'Are you okay, first name, I was worried!'
I tried to use ${firstname}, but it didn't print the rest of the string in the resulting comment box.
Enter Your First Name
<br><input type="text" id=firstname name="firstname" onblur="addNameToCommentBox(this)"><br><br>
.
Opening Sentence <br>
<input type="checkbox" onclick="addToCommentBox(this);" name="grade" value="statement1. statement1. " + ${firstname}.`+ "statement1. statement1.">Statement1. indentifier user read on page<br>
Second Sentence <br>
<input type="checkbox" onclick="addToCommentBox(this);" name="grade" value="statement2. statement2. ">Statement2. indentifier user read on page<br>
<br>
...
Resulting Block<br>
<textarea id="comment" rows="10" cols="80"></textarea><br>
</form>
<script>
function addNameToCommentBox(nameElement) {
var comment = $("#comment");
comment.val(comment.val() + " " + nameElement.value); }
function addToCommentBox(checkboxElement) {
var comment = $("#comment");
if (checkboxElement.checked === true) {
comment.val(comment.val() + " " + checkboxElement.value);
} else {
var currentComment = comment.val();
currentComment = currentComment.replace(checkboxElement.value, "");
comment.val(currentComment);
Could you please advise me?
You can set your template like "statement1.statement1 {0} statement1. statement1."
And then write a function to get message by passing arguments.
function getComment(template, args){
return args.reduce((acc, element) => {
console.log(element);
acc = acc.replace(/{\d}/, element);
return acc;
}, template);}
Codepen link: https://codepen.io/nithinthampi/pen/gOYJopP
You have forgot to use $ before the parameters. Try this
<script>
function addNameToCommentBox(nameElement) {
var comment = $("#comment");
comment.val(comment.val() + " " + $(nameElement).value); }
function addToCommentBox(checkboxElement) {
var comment = $("#comment");
if (checkboxElement.checked === true) {
comment.val(comment.val() + " " + $(checkboxElement).value);
} else {
var currentComment = comment.val();
currentComment = currentComment.replace( $(checkboxElement).value), "");
comment.val(currentComment);

Alternative to TextArea with more control over text?

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>

Add/Remove value to input on click

i have this code that i use, and on click i put email in field, but what i want to accomplish is that on next click on same field it removes email if one already exist in input.
Here is my code:
<p class="email">mail1#gmail.com</p>
<p class="email">something#gmail.com</p>
<p class="email">third#gmail.com</p>
<input type="text" id="contact-email" value="" class="form-control" style="width:500px" />
And js:
var $contact = $('#contact-email');
$('.email').on('click', function () {
if ($contact.val()) {
$contact.val($contact.val() +'; '+ $(this).text());
} else {
$contact.val($(this).text());
}
});
and fiddle https://jsfiddle.net/2dffwew5/2/
I would store selected email addresses to an array. Then push or splice the clicked email.
var $contact = $('#contact-email');
var emails = [];
$('.email').on('click', function () {
var index = emails.indexOf($(this).text());
if (index > -1) {
emails.splice(index, 1);
} else {
emails.push($(this).text());
}
$contact.val(emails.join(";"));
});
https://jsfiddle.net/jdgiotta/ze7zebzq/
I would suggest that you add a check to see if the current text contains the selected email address. If it does, then remove it. Otherwise add it.
You will also need to cater for leading/trailing dividers, which can easily be done with a couple of conditional checks.
Something like this:
var $contact = $('#contact-email');
$('.email').on('click', function () {
var text = $(this).text(); // Get the value to insert/remove.
var current = $contact.val(); // Get the current data.
// Check if the value already exists with leading seperator, if so remove it.
if (current.indexOf('; ' + text) > -1) {
$contact.val(current.replace('; ' + text, ''));
}
// Check if the value already exists with trainling seperator, if so remove it.
else if (current.indexOf(text + '; ') > -1) {
$contact.val(current.replace(text + '; ', ''));
}
// Check if the value already exists with no seperator (on it's own), if so remove it.
else if (current.indexOf(text) > -1) {
$contact.val(current.replace(text, ''));
}
// Otheriwse, it doesn't exist so add it.
else {
if (current) {
$contact.val(current + '; ' + text);
} else {
$contact.val(text);
}
}
});
Here is a working example

javascript - autocomplete hightlight text issue

I have a search engine that display a list of results when you search something.
The problem is that when I slect one of those results, in the input will apear this text : "<span style='font-weight:bold; color:" and not the word wich is for search.
For example if I want to search the word "football", in the search input will appear this text :"<span style='font-weight:bold; color: and not the word "football".
Also in the url the var t appears as a <span> code and not the word "football"
My code is this :
$("#search-field").data('ui-autocomplete')._renderItem = function(ul, item) {
var re = new RegExp("^" + this.term) ;
var t = item.label.replace(re, "<span style='font-weight:bold; color:#000;'>" +
this.term +
"</span>");
return $('<li></li>')
.data("item.autocomplete", item)
.append('' + t + '')
.appendTo(ul);
};

Delete the last append

I want to delete the last append when i click the back button. but when Im choosing appending again,the last append still there.
this is my codes on appending. its working:
$(req.responseText).find('ItemName').each(function () {
ItemNameArr[ItName] = $(this).text();
ItName++;
})
$(req.responseText).find('ItemQty').each(function () {
ItemQtyArr[ItQty] = $(this).text();
ItQty++;
})
$(req.responseText).find('ItemUnit').each(function () {
ItemUnitArr[ItUn] = $(this).text();
ItUn++;
})
for (var a = 0; a < ItemNameArr.length; a++) {
//$contentDt = $('<p><h6> ' + ItemQtyArr[a] + " " + ItemUnitArr[a] + " " + ItemNameArr[a] + '</h6></p>');
$('#Ingredients').append('<p><h6> ' + ItemQtyArr[a] + " " + ItemUnitArr[a] + " " + ItemNameArr[a] + '</h6></p>')
$('#Ingredients').fieldcontain('refresh')
}
My codes in back button when its click:
$("#btnBack").on('click',function(){
$('#Ingredients').empty()
$('#Ingredients').fieldcontain('refresh')
});
My codes in html when it was append
<div data-role="fieldcontain" id="Ingredients"> <!--Ingridients-->
</div>
});
You can do it using below code.
$('#Ingredients p:last').remove();
Use this Code
$('#Ingredients p:last').remove();
Explanation
# referees for the id selector.
$('#Ingredients p) finds the p tag in the element with id Ingredients.
$('#Ingredients p:last') selects last p tag in the element with id Ingredients.
.remove() function removes it from the page.
Problem is in your back button code (click event)
it will be -
$("html").on('click','#btnBack',function(){
// your code
// for remove last p element within #Ingredients
$('#Ingredients p:last').remove();
});

Categories

Resources