I have 2 input fields in a html file, text1 and text2. Then I copy a long string and paste it into text1. I want the string splited automatically into text1 and text2. So there must be a delimiter e.g TAB (ASCII 9) in the string. I have been trying many times but no lucky. In my experiment, there is a button calling javascript function as follows :
<script>
function Chr(AsciiNum)
{
return String.fromCharCode(AsciiNum)
}
function test()
{
c = "ABC"+Chr(9)+"DEF";
document.getElementById("text1").value=c;
}
</script>
<input type="button" value="Paste it" onClick="test()">
What I want is text1 filled with ABC and text2 filled with "DEF"
Thanks you for your helps .....
Splitting is simple:
function test(pastedText) {
var parts = pastedText.split(Chr(9));
document.getElementById("text1").value = parts[0];
document.getElementById("text2").value =
(parts[1] === undefined ? "" : parts[1]);
}
The tricky part, actually is the pasting, check the full code below.
See a online DEMO for code here.
Text1: <input type="text" id="text1"><br />
Text2: <input type="text" id="text2"><br />
<br />
<div>Sample string (copy the red text and paste it on Text1):</div>
<div style="color:red">ABC DEF</div>
<script>
function Chr(AsciiNum) {
return String.fromCharCode(AsciiNum)
}
function test(pastedText) {
var parts = pastedText.split(Chr(9));
document.getElementById("text1").value = parts[0];
document.getElementById("text2").value = (parts[1] === undefined ?
"" : parts[1]);
}
/** HANDLING PASTE EVENT
* Credits to: http://stackoverflow.com/a/6035265/1850609 */
function handlePaste(e) {
var pastedText = undefined;
if (window.clipboardData && window.clipboardData.getData) { // IE
pastedText = window.clipboardData.getData('Text');
} else if (e.clipboardData && e.clipboardData.getData) {
pastedText = e.clipboardData.getData('text/plain');
}
test(pastedText); // Process and handle text...
return false; // Prevent the default handler from running.
};
document.getElementById("text1").onpaste = handlePaste;
</script>
I also suggest you rename the test() function into something more meaningful to you.
Why dont you just do like that:
c = "ABC "+Chr(9);
document.getElementById("text1").value=c;
document.getElementById("text2").value= "DEF";
This should be inside test()
Hope this helps.
Related
I want to detect a specific word or multiple words within the user's entered text and reply accordingly. I plan to add more words to detect but for now I've been using this.
My result is finalKey.contains is not a function.
<html>
<div>
<p1 id="iOut">🧰</p1>
</div>
<div>
<input id="uIn" value=""></input>
</div>
<button onclick="regis()">SUBMIT</button>
<script>
var key = document.getElementById("uIn").value;
var finalKey = key.toUpperCase();
function regis() {
if (finalKey.contains("Hi" || "H")) {
document.getElementById("iOut").innerHTML = "HEY";
} else if (finalKey.contains("Bye" || "Goodbye")) {
document.getElementById("iOut").innerHTML = "Okay";
} else {
document.getElementById("iOut").innerHTML = "🧰 Try again";
}
}
</script>
</html>
There is no such thing as contains. It is .includes or indexOf != -1
Your gathering of values needs to be inside the function too
Also you cannot test two values in one statement unless you turn it around and use an array:
["Hi","H"].indexOf(finalKey) !=-1
or
["HI","H"].filter(text => finalKey.startsWith(text)).length > 0
if you want finalkey to start with either - use .includes if you want to test the complete input
Lastly you uppercased the text so compare uppercase text
function regis() {
var key = document.getElementById("uIn").value;
var finalKey = key.toUpperCase();
if (["HI","H"].filter(text => finalKey.includes(text)).length > 0) {
document.getElementById("iOut").innerHTML = "HEY";
} else
if (["BYE","GOODBYE"].filter(text => finalKey.includes(text)).length > 0) {
document.getElementById("iOut").innerHTML = "Okay";
} else // GOOD has to be AFTER GOODBYE to not catch it
if (["GOOD","GREAT"].filter(text => finalKey.includes(text)).length > 0) {
document.getElementById("iOut").innerHTML = "That's Good";
} else {
document.getElementById("iOut").innerHTML = "🧰 Try again";
}
}
<div>
<p1 id="iOut">🧰</p1>
</div>
<div>
<input id="uIn" value="" />
</div>
<button type="button" onclick="regis()">SUBMIT</button>
Using regular expression and word boundaries
Note I wrapped in a form, now you can just hit enter too
const wordList = [
{ list: ["HI", "H"], answer: "HEY" },
{ list: ["BYE", "GOODBYE"], answer: "Okay" },
{ list: ["GOOD", "GREAT"], answer: "That's good" }
];
const defaultText = "🧰 Try again";
document.getElementById("inputForm").addEventListener("submit", e => {
e.preventDefault()
const input = document.getElementById("uIn").value.trim().toUpperCase();
let result = wordList
.filter(({ list, answer }) => list
.filter(word => new RegExp("\\b" + word + "\\b").test(input))
.length > 0);
console.log(result)
document.getElementById("iOut").innerHTML = result.length > 0 ? result[0].answer : defaultText;
})
<div>
<p1 id="iOut">🧰</p1>
</div>
<form id="inputForm">
<div>
<input id="uIn" value="" />
</div>
<button>SUBMIT</button>
</form>
You will want to use .includes() and not .contains().
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
I'd recommend getting comfortable with Chrome's Developer Tools. For example, pull up a browser and enter "xyz". You will see various methods available, and contains() is not on the list.
Also, as #mplungjan pointed out, there are other problems here.
"Hi" || "H" evaluates to "Hi". So "HI" is entirely ignored here.
You could write finalKey.includes("Hi") || finalKey.includes("H")) instead, but this would get cumbersome as you add other conditions.
A better approach would be to use functional programming along these lines:
const wordsToTest = ['FOO', 'BAR'];
if (wordsToTest.find(word => finalKey.includes(word))) {
I was made aware that i made a fundemental mistake in my previous answer, so i came up with another solution. With this approach you will not have to make multiple if/else statements, however simply add new object to the array, i hope it is pretty self explanatory when looking at it :)
<html>
<div>
<p1 id="iOut">🧰</p1>
</div>
<div>
<input id="uIn" value=""></input>
</div>
<button onclick="regis()">SUBMIT</button>
<script>
function regis() {
let key = document.getElementById("uIn").value;
let finalKey = key.toUpperCase();
let match = false;
// Words to test for
autoComplete = [
{ // Hey
response: "hey",
input: [
'HI',
'H',
]
},
{ // Bye
response: "Bye",
input: [
'BYE',
'GOODBYE',
]
}
]
for (potentialMatch of autoComplete){
for (input of potentialMatch.input){
if (input === finalKey){
document.getElementById("iOut").innerHTML = potentialMatch.response;
match = true;
}
}
}
if (match === false)
document.getElementById("iOut").innerHTML = "🧰 Try again";
}
</script>
</html>
I have a requirement, in which, when a user pastes a list of values from excel into jquery selectize, it should recognize each line as a value instead of identifing the entire list as one value.
say for example, when I paste the below list containing 2 values, selectize should identify 'bill gates' as one value and 'steve jobs' as another,but
by default, it identifies the entire list as one value('bill gates steve jobs').
List:
bill gates
steve jobs
I have shared a demo for your reference, let me know if there is a way to implement it. Thanks.
If you can edit your excel files to include ',' after each enter. Be it at new line or same line, it should add the values in a separate tag.
Try pasting:
bill gates,
steve jobs
bill gates,steve jobs
In your jsfiddle and it should work.
To fix this issue-- I cached all the pasted text and then modified it, before programmatically pasting it on the Selectize control. You can find the demo here.
HTML code:
<div class="demo">
<div class="control-group">
<label for="input-tags">Tags:</label>
<input type="text" id="input-tags" class="demo-default" value="awesome,neat">
</div>
</div>
Javascript code:
var pastedText = undefined;
['paste'].forEach(function (event) {
document.addEventListener(event, function (e) {
var str = undefined;
if (window.clipboardData && window.clipboardData.getData("Text"))
str = window.clipboardData.getData("Text");
else
if (e.clipboardData && e.clipboardData.getData('text'))
str = e.clipboardData.getData('text');
pastedText = str;
});
});
var onItemAddEventHandler = function (value, $item) {
var tempStr = undefined;
if (pastedText !== undefined) {
// Replace all newline chars to | (pipe).
tempStr = pastedText.replace(/(?:\r\n|\r|\n)/g, '|');
tempStr = tempStr.replace(/,/g, '|');
if (tempStr.length>0)
this.$control_input.val(tempStr);
pastedText = undefined;
this.removeOption(value);
$item.remove();
return;
}
if (value.indexOf("|") === -1)
return;
var tempItem = value;
value = value.replace(/,/g, '|');
value = value.split("|");
for (var i = 0; i < value.length; i++) {
if(value[i].trim()!="")
this.createItem(value[i].trim());
}
this.removeOption(tempItem);
$item.remove();
return;
}
$('#input-tags').selectize({
persist: false,
createOnBlur: true,
create: true,
onItemAdd: function (value, $item) {
onItemAddEventHandler.call(this, value, $item);
}
});
I am trying to create a simple web application. Like in Facebook chat when I enter "(Y)" it turns into the thumbs up icon. Similarly I am trying to do something like that with the following code. But it is not working for me. I am not expert with JavaScript. I need some help that what's wrong with the code?
And I made the code in a way that if i enter "y" it will return LIKE. I want to know how to show an icon after "y" input.
<html>
<head>
<title>Emogic</title>
</head>
<body>
<input type="text" id="input">
<input onclick="appear()" type="submit">
<p id="output"></p>
<script>
function appear(){
var value = document.getElementByid("input").value
var result = document.getElementById("output").innerHTML
if(value == "y"){
result = "LIKE"
}
else if(value == ""){
alert("You must enter a valid character.");
}
else{
alert("Character not recognised.");
}
}
</script>
</body>
</html>
There are a few issues/typo in your code :
it's document.getElementById(), with a capital I in Id.
result will be a string, containing the innerHTML of your element, but not a pointer to this innerHTML : when you then set result to an other value, it won't change the element's innerHTML as you expected. So you need to create a pointer to the element, and then set its innerHTML from the pointer.
The quick fix of your code would then be :
function appear() {
var value = document.getElementById("input").value;
var output = document.getElementById("output");
if (value == "y") {
output.innerHTML = "LIKE";
} else if (value == "") {
alert("You must enter a valid character.");
} else {
alert("Character not recognised.");
}
}
<input type="text" id="input" value="y">
<input onclick="appear()" type="submit">
<p id="output"></p>
But you'll find out that your user will have to enter exactly "y" and only "y" for it to work.
I think you should use instead String.replace() method with a regular expression to get all occurences of a pattern, i.e, for "(Y)" it could be
function appear() {
var value = document.getElementById("input").value;
var output = document.getElementById("output");
// The Regular Expression we're after
var reg = /\(Y\)/g;
// your replacement string
var replacement = 'LIKE';
// if we found one or more times the pattern
if (value.match(reg).length > 0) {
output.innerHTML = value.replace(reg, replacement);
} else if (value == "") {
alert("You must enter a valid character.");
} else {
alert("Character not recognised.");
}
}
<input type="text" id="input" value="I (Y) it (Y) that">
<input onclick="appear()" type="submit">
<p id="output"></p>
I'm making a quiz with a text input. This is what I have so far:
<html>
<head>
<script type="text/javascript">
function check() {
var s1 = document.getElementsByName('s1');
if(s1 == 'ō') {
document.getElementById("as1").innerHTML = 'Correct';
} else {
document.getElementById("as1").innerHTML = 'Incorrect';
}
var s2 = document.getElementsByName('s2');
if(s2 == 's') {
document.getElementById("as2").innerHTML = 'Correct';
} else {
document.getElementById("as2").innerHTML = 'Incorrect';
}
//(...etc...)
var p3 = document.getElementsByName('p3');
if(p3 == 'nt') {
document.getElementById("ap3").innerHTML = 'Correct';
} else {
document.getElementById("ap3").innerHTML = 'Incorrect';
}
}
</script>
</head>
<body>
1st sing<input type="text" name="s1"> <div id="as1"><br>
2nd sing<input type="text" name="s2"> <div id="as2"><br>
<!-- ...etc... -->
3rd pl<input type="text" name="p3"> <div id="ap3"><br>
<button onclick='check()'>Check Answers</button>
</body>
</html>
Every time I check answers it always says Incorrect and only shows the first question. I also need a way to clear the text fields after I check the answers. One of the answers has a macro. Thanks in advance.
The method getElementsByName returns a NodeList, you can't really compare that against a string. If you have only one element with such name, you need to grab the first element from that list using such code instead:
var s1 = document.getElementsByName('s1')[0].value;
To make it more flexible and elegant plus avoid error when you have typo in a name, first add such function:
function SetStatus(sName, sCorrect, sPlaceholder) {
var elements = document.getElementsByName(sName);
if (elements.length == 1) {
var placeholder = document.getElementById(sPlaceholder);
if (placeholder) {
var value = elements[0].value;
placeholder.innerHTML = (value === sCorrect) ? "Correct" : "Incorrect";
} else {
//uncomment below line to show debug info
//alert("placeholder " + sPlaceholder+ " does not exist");
}
} else {
//uncomment below line to show debug info
//alert("element named " + sName + " does not exist or exists more than once");
}
}
Then your code will become:
SetStatus('s1', 'ō', 'as1');
SetStatus('s2', 's', 'as2');
//...
document.getElementsByName('s1') is an array you should use document.getElementsByName('s1')[0] to get certain element(first in this case)
I want to see if it's possible to block the enter key and replace it with a space. I'm also using form validation to only allow letters, numbers and some other specific characters like the dollar sign,minus, and period and so on.
Here is that code, I would like to see if I can combine them into one and be able to check for the validation and replace the key press with a space all in one code/call.
<script type="text/javascript">
function ValidateForm(form)
{
var str
str=document.getElementById('limitedtextarea').value
str=str.replace(/[^A-Za-z0-9.-:/$ ]/g, "");
document.getElementById('limitedtextarea').value=str
//return true;
}
</script>
<FORM action="sms_SendMessage.asp" method=post onsubmit="javascript:return ValidateForm(this)" target=_blank>
Thanks for the help...
In javascript, the line-break character is represented by \n. You could replace them by spaces in your validation function like this :
function ValidateForm(form)
{
var str
str=document.getElementById('limitedtextarea').value
str=str.replace(/[^A-Za-z0-9.-:/$ ]/g, "");
str=str.replace(/\n/g, " ");
document.getElementById('limitedtextarea').value=str
//return true;
}
If you remove the onsubmit and do not have a submit button, typing enter will not submit it.
<body>
<form>
<textarea></textarea>
</form>
<script>
(function(){
var txt = document.getElementsByTagName('TEXTAREA')[0];
txt.onkeypress = function(ev){
ev = ev || window.event;
if ( ev.keyCode === 13 ){
if (window.event) {
window.event.returnValue = false;
}
if (ev && ev.preventDefault) {
ev.preventDefault();
}
txt.value += ' ';
}
};
})();
</script>
</body>