Concatenating to user input - javascript

An example would be if I type !greet it would output "Hello username".
The end goal is to integrate this into a discord bot.
An example of what I have tried:
function doGreeting() {
var input = document.getElementById('userInput')
alert(input);
}
if (msg.content === prefix + 'greet') {
msg.channel.sendMessage('Hello ' + doGreeting())
};

I don't know about your input field id or class but I am giving you example below so it may help you.
<input type="text" id="my_id" >
<span id="msg"></span>
<script>
var input_val = document.getElementById("my_id");
if(input_val .indexOf("!greet") !=-1){ // if there is !greet word
var split_str = input_val .split(" ");
document.getElementById('msg').innerHTML = "Hello "+split_str [1];
}
</script>

Related

How to format input in html using javascript

How to format input text on html, sample input: Hi hello
I like to display the input like this
'Hi','hello',
When I hit enter, single quote with a comma will automatically display.
Any suggestion? Thank you.
The text is then formatted and returned to the input field. You only need an eventlistener, a function that converts the text.
const input = document.getElementById('watch');
input.addEventListener('keypress', function (e) {
e.preventDefault();
if (e.key === 'Enter') {
input.value = input.value.split(' ').map(s => `'${s}'`).toString() + ',';
}
return false;
});
<form>
<input type="text" value="Hi World" id="watch">
</form>
You can use split and join
const str = "Hi hello";
let output = '';
if(str)
output = `'${str.split(" ").join("','")}',`;
console.log(str);
const string = 'a b c'
console.log(string.split(' ').map(str => `'${str}'`).toString() + ',')

My validation and the push() is not working

The user has to type the information in a text box and then click on the button to add the names. If the format is correct the name will appear below the text box. If the format is incorrect a message will be generated that reads "Incorrect Format".
The users inputs will create a list of names that will appear underneath the text box.
function validate(name){
var str = [];
var name = document.getElementById("letters");
var check = /^[A-Za-z]+$/;
if(name.value.match(check)){
str.push(document.getElementById("letters"));
document.write("Name: " + name);
}
else{
document.write("Incorrect Format");
}
}
validate();
I think this is what you're trying to achieve:
function validate() {
console.clear();
var check = /^[A-Za-z]+$/;
var inputVal = document.getElementById('letters').value;
if (inputVal.match(check)) {
console.log("Name: " + inputVal);
document.getElementById('container').innerHTML += inputVal + "<br/>";
} else {
console.log("Incorrect Format");
}
}
document.getElementById('btnValidate').addEventListener('click', validate);
<input type="text" id="letters" />
<input type="button" id="btnValidate" value="Validate" />
<div id="container"></div>

Prettify JSON object alert

I have a JSON object and when i alert it i get this:
and i want to get this:
function getNameById(id){
return usersArray.find(item => item.id === id).name;
}
var usersArray = [
{"id":"135","name":"Jenny"},
{"id":"162","name":"Kelly"}
];
$("#submit").click(function (e) {
var errors = {};
$(".validation").each(function(){
var worker_id = $(this).attr('id').replace(/[^\d]/g, '');
var w_name = getNameById(worker_id);
if(!errors[w_name]) errors[w_name] = [];
if ( $(this).val() == "" ) {
errors[w_name].push( $(this).attr('id').replace(/[^a-zA-Z]/g, '') + " must be filled!");
//errors[w_name].push("second number must be smaller than first");
}
if ( $(this).attr('id') == "second-"+worker_id && ($(this).val() > $('#first-'+worker_id+'').val())) {
errors[w_name].push("second number must be smaller than first");
}
});
alert(JSON.stringify(errors, null, 2));
e.preventDefault();
e.stopPropagation();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
First<input id="first-135" class="validation" name="first" type="text" value="5"><br>
Second<input id="second-135" class="validation" name="second" type="text" value="8"><br>
Signature<input id="signature-135" class="validation" name="signature" type="text"><br>
<input id="submit" type="submit" value="Submit">
</form>
How can i achieve that?
Transform your object to a string like this
let obj = {
"Jenny" : [
"Second number must be smaller than first",
"Signature must be filled !"
]
};
let str = "";
Object.keys(obj).forEach(k => {
str += k + ":\n";
str += obj[k].join(",\n");
});
console.log(str);
Extract the data from the JSON data that you have in errors instead of running JSON.stringify directly. You should be able to get the data like this: errors["Jenny"] to get a list of the errors. Then combine them into a string according to your liking.
I honestly don't think your question has absolutely anything to do with JSON. The only reason why some JSON even shows up is because you're generating it for the alert():
alert(JSON.stringify(errors, null, 2));
// ^^^^^^^^^^^^^^ This generates JSON
If you want to concatenate some array items you can use a combination of the concatenation operator (+) and Array.join():
alert(w_name + ":\n" + errors[w_name].join(",\n"));
Tweak format to your liking.
var w_name = "Jenny";
var errors = {};
errors[w_name] = [];
errors[w_name].push("Second number must be smaller than first");
errors[w_name].push("Signature must be filled!");
alert(w_name + ":\n" + errors[w_name].join(",\n"));

Text Box Search / Javascript Function Arrays **not corresponding**

I want the user to "Search" some "Authors" and if they select the one in the database they are sent to a corresponding HTML. Otherwise "No Author Found" displays...
For some reason I cannot wrangle it properly - pls help!
//Search by Author
function searchAuth() {
var search_string = document.getElementById('search_string').value;
var arrayelement = ["John","Stan","Henry","Paul","Samuel"];
for (i=0;i<arrayelement.length;i++) {
if (input == arrayelement.John) {
var itemLink = document.getElementById('demo').innerHTML =
"<a href='https://www.google.ca/?gws_rd=ssl'>Your link</a>";
} else if (input == arrayelement.Stan) {
var itemLink = document.getElementById('demo').innerHTML =
"<a href='https://www.google.ca/?gws_rd=ssl'>Your link</a>";
}else {
var itemLink = document.getElementById('demo').innerHTML =
"Author not found."
}
}
<!--Author-->
<h3>Search By Author</h3>
<form name="searchTest" onsubmit="return(searchAuth());" action="#">
<input type="text" id="search_string" />
<input type="submit"/>
<p id="demo"></p>
Perhaps you are trying to do things like these..
P.S this is just a demo, for you to start :)
EDIT: added few explanation on some stuffs you might get confuse with. :)
//events once textbox gets out focus
//the events varies on which or where do you want to add the event. it can be on click of a search button or submit button just like in your example.
document.getElementById('search-text-box-id').addEventListener("focusout", function() {
//searchString gets the textbox value.
var searchString = document.getElementById('search-text-box-id').value;
var searchList = ["John","Stan","Henry","Paul","Samuel"];
//Loop searchList
for (i=0; i < searchList.length; i++) {
//i which usually means the index or the key of the array's object(s).
var searchItem = "";
//searchList[i] loops its object by getting the index resulting to John, Stan and so on and so forth.
if (searchString == searchList[i]) {
searchItem = searchList[i];
document.getElementById('search-result-container').innerHTML = searchItem + " link";
//stop looping as the loop found a match.
return;
}
else {
searchItem = "Author not found.";
document.getElementById('search-result-container').innerHTML = searchItem;
}
}
});
<label for="search-text-box"></label>
<input type="text" id="search-text-box-id" name="search-text-box" />
<p id="search-result-container"></p>

Check if TextArea/TextBox contains a certain String

Given textarea is a textarea element with id 'textareabox', how can I check if it contains a string within it?
var textarea = document.getElementById('textareabox');
var word = something;
if (!textarea.contains(word))
{
textarea.value += word;
}
You can use .value, as:
var textarea = document.getElementById('textareabox');
var word = 'something';
var textValue=textarea.value; //-> don't use .innerHTML since there is no HTML in a textarea element
if (textValue.indexOf(word)!=-1)
{
alert('found')
}
You could do something like this:
var textarea = document.getElementById('textareabox').value;
if (texarea.match(word) != null) {
// do some stuff
}
A better regex than what I did but I don't know regex all that well (forgive me regex ignorance).
body {
background-color: red;
}
<html>
<h1>#mywebsite</h1>
<body>1+1=2?(yes <strong>or</strong> no)</body>
<input type="text" id="text" placeholder="text here"></input>
<button type="button" id="u" onclick="run()">submit</button>
<script type="text/javascript">
var a = 1;
function run() {
if (document.getElementById("text").value.includes("yes")) {
alert("correct!");
/*if the textbox includes "yes" it will say you got it right; basically whatever the input your user puts into the textbox it will test if the users sentence contains "yes" it alerts "correct!" into html if its wrong well it alerts "Try again!" the thing is, no matter what, if yes is in the sentance it will still say its correct.*/
/*if the snippet will not work use a different website to put code on */
document.body.innerHTML += "<li>attempt #" + a + ": correct";
a++
}
else {
alert("try again!")
document.body.innerHTML += "<li>attempt #" + a + ": try again";
a++
}
}
</script>

Categories