I am trying to take a user input value that is entered through an html input box, and have it as a value within my function (the negKeyword function in my code to be more specific). The problem that I think is happening is this input value is stored as a variable, so when the code is first stored in memory it is stored as "", since the user has not inputed anything yet. How do I get it so when the user inputs something it replaces blank or "" with what ever the user inputs?
What I basically want to happen next is the user will click a button, it will then compare what the user inputs to what the "negKeyword" function outputs and give a result on whether they match or not (this action is demonstrated in my booleanKeyword function in my code).
Here is my code.
var input = document.getElementById("input").value;
var arr = ['no', 'not', 'checked'];
var text = ''; //JS output variable.
var keyword = 'leak'; //Individual keyword.
function negKeyword() {
for (i = 0; i < arr.length; i++) {
if (text == input) { break; }
text = arr[i] + ' ' + keyword;
}
return text;
}
function booleanKeyword() {
if (input == negKeyword()) {
document.getElementById("result").style.color="green";
document.getElementById("result").innerHTML="Match";
} else {
document.getElementById("result").style.color="red";
document.getElementById("result").innerHTML="No Match";
}
}
document.getElementById("result2").innerHTML=keyword;
<label for="Full Negative Keyword">Negative Keyword</label> <input id="input" type="text" />
<div id="message">Result: <span id="result"></span></div>
<div id="message">Keyword: <span id="result2"></span></div>
<button id="test" onclick="booleanKeyword()">Click to Test</button>
You can retrieve the input's value again, by getting it and assigning to the same variable (but inside the function that is called after the button click).
var input = document.getElementById("input").value;
var arr = ['no', 'not', 'checked'];
var text = ''; //JS output variable.
var keyword = 'leak'; //Individual keyword.
function negKeyword() {
input = document.getElementById("input").value;
for (i = 0; i < arr.length; i++) {
if (text == input) { break; }
text = arr[i] + ' ' + keyword;
}
return text;
}
function booleanKeyword() {
input = document.getElementById("input").value;//The variable is reassigned, only after the click
if (input == negKeyword()) {
document.getElementById("result").style.color="green";
document.getElementById("result").innerHTML="Match";
} else {
document.getElementById("result").style.color="red";
document.getElementById("result").innerHTML="No Match";
}
}
document.getElementById("result2").innerHTML=keyword;
Edit: added the same code to negKeyword() function as it requires the input too.
It is not working because your variable input is always "". You have to assign new value to it each time the button is clicked. I just moved your code for input in BooleanKeyword() function. Now everything is working fine.
Everytime when something like this is not working, just try to log/alert values.
For example you could just alert(input + ' ' + negKeyword()); on top of booleanKeyword() function and you would see problem by yourself.
var input;
var arr = ['no', 'not', 'checked'];
var text = ''; //JS output variable.
var keyword = 'leak'; //Individual keyword.
function negKeyword() {
for (i = 0; i < arr.length; i++) {
if (text == input) { break; }
text = arr[i] + ' ' + keyword;
}
return text;
}
function booleanKeyword() {
input = document.getElementById("input").value;
if (input == negKeyword()) {
document.getElementById("result").style.color="green";
document.getElementById("result").innerHTML="Match";
} else {
document.getElementById("result").style.color="red";
document.getElementById("result").innerHTML="No Match";
}
}
document.getElementById("result2").innerHTML=keyword;
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<label for="Full Negative Keyword">Negative Keyword</label> <input id="input" type="text" />
<div id="message">Result: <span id="result"></span></div>
<div id="message">Keyword: <span id="result2"></span></div>
<button id="test" onclick="booleanKeyword()">Click to Test</button>
</html>
Related
I am trying to clear the value of an input depending if it finds or not an id, if it finds an existing id, js updates the value of an input, but if it doesn't it keeps the last one found but I need to have the value clear, can someone tell me what is wrong:
function driverdata(valueid)
{
var numero_id = valueid;
//console.log(valueid)
var idselect = document.getElementById('driver'+id_number).value;
document.getElementById("idinsearch"+ id_number).value = idselect;
//console.log(idselect);
var placa = document.getElementById("searchable"+idselect).value;
console.log(placa);
if (placa != null) {
document.getElementById("placa"+ id_number).value = placa;
} else {
document.getElementById("placa"+ id_number).value = "";
}
}
In the method driverdata you don't define variable id_number so it's undefined when you try get element by id
So if id_number is equal to the parameter of the method you can directly use it
moreover to clear value you are right it's elem.value = ""
withour yout html i can propose you the following one => your script run
function driverdata(numberId)
{
var idselect = document.getElementById('driver'+numberId).value;
document.getElementById("idinsearch"+ numberId).value = idselect;
var placa = document.getElementById("searchable"+idselect).value;
if (placa != null) {
document.getElementById("placa"+ numberId).value = placa;
} else {
document.getElementById("placa"+ numberId).value = "";
}
}
<div onclick="driverdata(1)">
click me<br/>
driver<input id="driver1" value="1"/><br/>
idinsearch<input id="idinsearch1"/><br/>
<div id="searchable1">
input that will be clear <input id="placa1" value="test"/>
</div>
</div>
I have a simple form: https://jsfiddle.net/skootsa/8j0ycvsp/6/
<div class='field'>
<input placeholder='Nickname' type='text'>
</div>
<div class='field'>
<input placeholder='Age' type='text'>
</div>
How would I get a button that copied the contents of each input box + the "placeholder" attribute (or class name)? So that the clipboard results looked like this:
Nickname: Johnnyboy
Age: 22
You need to:
create an invisible element to copy the data
get the data from your form and set it to the previous element
select it
call document.execCommand('copy') to copy the selected text to the
clipboard
I have updated your fiddle, check it out https://jsfiddle.net/8j0ycvsp/9/
In case you want the code
function copyToClipboard() {
/*get inputs from form */
var inputs = document.querySelectorAll("#the-form input[type=text]");
/*do a copy of placeholder and contents*/
var clipboardText = ''
for (var i = 0, input; input = inputs[i++];) {
clipboardText += input.placeholder+': '+(input.value ? input.value : '' )+'\n';
}
/*create hidden textarea with the content and select it*/
var clipboard = document.createElement("textarea");
clipboard.style.height = 0;
clipboard.style.width = 0;
clipboard.value = clipboardText;
document.body.appendChild(clipboard);
clipboard.select();
console.log(clipboard.value);
/*do a copy fren*/
try {
if(document.execCommand('copy'))
console.log('Much succes, wow!');
else
console.log('Very fail, wow!');
} catch (err) {
console.log('Heckin concern, unable to copy');
}
}
So give it a try
var input = document.querySelectorAll('.field input');
document.getElementById('submit').addEventListener('click', function () {
var innerHTMLText = "";
for (var i = 0; i < input.length; i++) {
innerHTMLText += input[i].placeholder + ':' + input[i].value + ' ';
}
console.log(innerHTMLText);
document.getElementsByClassName('bix')[0].innerHTML = innerHTMLText;
});
I have a problem with my Script. I want to do the following steps in this order:
1. Save the text in the input field.
2. Delete all text in the input field.
3. Reload the same text that was deleted before in the input field.
The problem with my script is that the ug()- function writes undefined in my textbox instead of the string that should be stored in var exput. The alert(exput) however shows me the correct content.
Help would be very much appreciated. And I'm sure there is better ways to do that, I'm quite new to this stuff.
HTML
<textarea id="a" style="width: 320px; height: 200px;"></textarea>
<input type="checkbox" id="remember" onclick="merker();deleter();ug()" />
Javascript
function merker() {
var merkzeug = document.getElementById('a').value;
ug(merkzeug);
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug(exput) {
alert(exput);
document.getElementById('a').value = exput;
};
Your code is calling merker(); deleter(); ug(); in the onclick event, but ug() is already called by merker(). You should be doing this instead:
function merker() {
var merkzeug = document.getElementById('a').value;
deleter();
ug(merkzeug);
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug(exput) {
alert(exput);
document.getElementById('a').value = exput;
};
<textarea id="a" style="width: 320px; height: 200px;"></textarea>
<input type="checkbox" id="remember" onclick="merker();" />
I changed Your Javascript:
function merker() {
merkzeug = document.getElementById('a').value;//global variable without var
ug();//why You use it here? I think only for test. So delete it after.
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug() {
alert(merkzeug);
document.getElementById('a').value =merkzeug;
};
Problems with your code:
method ug was used with argument and without argument ( i changed to without )
to restore deleted value it must be saved to some variable, i saved to global merkzeug variable - this is not good practice but sufficient in this case
next i used merkzeug to restore value in textarea in ug() function
i do not know why You using ug() two times? maybe delete one of them is good thing to do.
In plunker - https://plnkr.co/edit/fc6iJBL80KcNSpaBd0s9?p=info
problem is: you pass undefined variable in the last ug function:
you do: merker(value) -> ug(value); delete(); ug(/*nothing*/);
or you set your merkzeung variable global or it will never be re-inserted in your imput:
var merkzeug = null;
function merker() {
merkzeug = document.getElementById('a').value;
ug(merkzeug);
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug(exput) {
if (typeof exput === 'undefined') exput = merkzeung;
alert(exput);
document.getElementById('a').value = exput;
};
I want to pass an array from one external .js file to another.
Each of these files works fine by themselves, but I am having a problem passing the array from pickClass.js to displayStudent.js, and getting the names and "remaining" value to display in the html file. I know it has something to do with how the arrays are declared, but I can't seem to get it to work properly.
The first file declares the array choice:
(masterStudentList.js):
var class1 = ['Brown, Abe','Drifter, Charlie','Freed, Eve'];
var class2 = ['Vole, Ug','Xylo, William','Zyzzyx, Yakob'];
The second picks which array to use based on the radio buttons (pickClass.js):
var classPicked = array(1);
function randomize(){
return (Math.round(Math.random())-0.5); }
function radioResult(){
var chooseClass = document.getElementsByName("chooseClass");
for (i = 0; i < chooseClass.length; i++){currentButton = chooseClass[i];
if (currentButton.checked){
var selectedButton = currentButton.value;
} // end if
} // end for
var output = document.getElementById("output");
var response = "You chose ";
response += selectedButton + "\n";
output.innerHTML = response;
chosenClass = new Array();
if (selectedButton == "class1")
{chosenClass = class1;}
else
{chosenClass = class2;}
var text = "";
var nametext = "";
var i;
for (i = 0; i < chosenClass.length; i++) {
text += chosenClass[i]+ ' / ';
}
var showText = "";
l = chosenClass.length;
classPicked = Array(l);
for (var i = 0; i < l; ++i) {
classPicked[i] = chosenClass[i].split(', ').reverse().join(' ');
showText += classPicked[i]+ '<br>';
}
//return = classPicked;
document.getElementById("classList").innerHTML = classPicked;
} // end function
This works properly.
I then want to pass "classPicked" to another .js file (displayStudent.js) which will randomize the student list, loop and display the students for a few seconds, and then end with one student name.
basket = classPicked; //This is where the array should be passed
function randOrd(){
return (Math.round(Math.random())-0.5); }
function showBasket(){
mixedBasket = basket.sort( randOrd ); //randomize the array
var i = 0; // the index of the current item to show
document.getElementById("remaining").innerHTML = basket.length;
fruitDisplay = setInterval(function() {
document.getElementById('showStud')
.innerHTML = mixedBasket[i++]; // get the item and increment
if (i == mixedBasket.length) i = 0; // reset to first element if you've reached the end
}, 100); //speed to display items
var endFruitDisplay = setTimeout(function()
{ clearInterval(fruitDisplay);
var index = mixedBasket.indexOf(document.getElementById('showStud').innerHTML);
mixedBasket.splice(index,1);
}, 3500); //stop display after x milliseconds
}
Here is the html (master.html). It's just rough -- I'll be working on the layout later:
<html>
<head>
<script src="masterStudentList.js" type="text/javascript"></script>
<script src="pickClass.js" type="text/javascript"></script>
<script src="displayStudent.js" type="text/javascript"></script>
</head>
<body>
<h2>Choose Class</h2>
<form action = "">
<fieldset>
<input type = "radio"
name = "chooseClass"
id = "radSpoon"
value = "class1"
checked = "checked" />
<label for = "radSpoon">Class 1</label>
<input type = "radio"
name = "chooseClass"
id = "radFlower"
value = "class2" />
<label for = "radFlower">Class 2</label>
<button type = "button"
onclick = "radioResult()"> Choose Class
</button>
<div id = "output">
</fieldset>
</form>
</div>
<center>
<h1> <span id="chooseStud"></span><p></h1>
<script> var fruitSound = new Audio();
fruitSound.src = "boardfill.mp3";
function showFruitwithSound()
{
fruitSound.play(); // Play button sound now
showBasket()
}
</script>
Remaining: <span id = "remaining" ></span>
<p>
<button onclick="showFruitwithSound()">Choose Student</button>
</center>
pickedClassList = <p id = classList> </p>
</body>
</html>
You shouldn't use global variable like this (I encourage you to read more on this theme) and I'm not sure I understand what you're trying to do... but the solution of your issue should be to move the basket = classPicked; line into your showBasket method :
basket = classPicked; //This is where the array should be passed
function randOrd(){
return (Math.round(Math.random())-0.5);
}
function showBasket(){
// whatever
}
should be :
function randOrd(){
return (Math.round(Math.random())-0.5);
}
function showBasket(){
basket = classPicked; //This is where the array should be passed
// whatever
}
This way, each time you call showBasket, this method will use the last value of classPicked.
Otherwise, basket will always keep the reference on the first value of classPicked.
Why ? because each time you assign a new Array to the basket variable (classPicked = Array(l);) instead of changing directly it's content by :
emptying it : while (classPicked.length > 0) { classPicked.pop(); }
and then adding new data : classPicked.concat(chosenClass)
You can't pass things to files; you could call a function defined in displayStudent.js, pass it classPicked, and have it assign it to basket.
I noticed this at the end of your second chunk of code ...
} // end function
This could indicate the classPicked is declared inside a function (I don't see one on the code). Because it is inside function scope, your set of code that is trying to use it cannot.
Push the declaraction of classPicked outside of the function.
var classPicked = Array(1);
function thisusesclasspicked() {
...
Also, please start indenting your code properly, it will become much easier to maintain and read.
UPDATE FROM COMMENTS:
I see the declaration now ...
classPicked = Array(l);
for (var i = 0; i < l; ++i) {
classPicked[i] = chosenClass[i].split(', ').reverse().join(' ');
showText += classPicked[i]+ '<br>';
}
... however, you are re-assigning the array with an element of one just before you attempt to make modifications to it ... You are emptying it there: classPicked = Array(l);
I would like to ask somebody how i can determine what key was pressed in a textarea....
need to write a little javascript code.. a user type in a textarea and i need to write it in a while he writing so the keydown, keypress event handle this functionality, also need to change the text color if a user typed a "watched" word (or the word what he wrote contains the "watched" word/words ) in the textarea.. any idea how i can handle it ??
till now did the text is appear in the <div>, but with this i have a problem.. can't check if the text is in the "watched"... the document.getElementById('IDOFTHETEXTAREATAG'); on keypress is not really works because i got back the whole text inside of the textarea.....
So how i can do it ? any ideas ??? "(Pref. in Mozilla FireFox)
Well, if you were using jQuery, you could do this given that the id of your textarea was 'ta':
$('#ta').keypress(function (evt) {
var $myTextArea = $(this); // encapsulates the textarea in the jQuery object
var fullText = $myTextArea.val(); // here is the full text of the textarea
if (/* do your matching on the full text here */) {
$myTextArea.css('color', 'red'); // changes the textarea font color to red
}
};
I suggest you use the 'onkeyup' event.
$( element ).keyup( function( evt ) {
var keyPressed = evt.keyCode;
//...
});
I have this made like this (plain JS, no JQuery):
function keyDown(e) {
var evt=(e)?e:(window.event)?window.event:null;
if(evt){
if (window.event.srcElement.tagName != 'TEXTAREA') {
var key=(evt.charCode)?evt.charCode: ((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0));
}
}
}
document.onkeydown=keyDown;
This script is in head tag. I am catching this in all textarea tags. Modify it for your purpose.
2 textareas.
In the first textarea I need to write the words or chars what you want to "watch" in the typing text.
In the second textarea I need to type text, so when I type text, under the textarea need to write what is in the textarea (real time) and highlight the whole word if contains the watched words or chars.
For example:
watched: text locker p
text: lockerroom (need to highlite the whole word because it contains the locker word) or apple (contains the p)
who I can do if a word not start with watched word/char to highlite the whole word?
JavaScript:
var text;
var value;
var myArray;
var found = new Boolean(false);
function getWatchedWords()
{
myArray = new Array();
text = document.getElementById('watched');
value = text.value;
myArray = value.split(" ");
for (var i = 0;i < myArray.length; i++)
{
document.getElementById('writewatched').innerHTML += myArray[i] + "<newline>";
}
}
function checkTypeing()
{
var text2 = document.getElementById('typeing');
var value2 = text2.value;
var last = new Array();
last = value2.split(" ");
if (last[last.length-1] == "")
{
if(found)
{
document.getElementById('writetyped').innerHTML += "</span>";
document.getElementById('writetyped').innerHTML += " ";
}
else
document.getElementById('writetyped').innerHTML += " ";
}
else
check(last[last.length-1]);
}
function check(string)
{
for (var i = 0; i < myArray.length; i++)
{
var occur = string.match(myArray[i]);
if(occur != null && occur.length > 0)
{
if (!found)
{
found = true;
document.getElementById('writetyped').innerHTML += "<span style='color: blue;'>";
}
else
{
found = true;
}
}
else
{
}
}
if(found)
{
document.getElementById('writetyped').innerHTML += string;
}
else
{
document.getElementById('writetyped').innerHTML += string;
}
}
HTML:
<html>
<head>
<title>TextEditor</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script src='script.js' type='text/javascript'></script>
</head>
<body>
<div>
<p>Watched words:</p>
<textarea id="watched" onblur=getWatchedWords();>
</textarea>
</div>
<div id="writewatched">
</div>
<div>
<p>Text:</p>
<textarea id="typeing" onkeyup=checkTypeing();>
</textarea>
</div>
<div id="writetyped">
</div>
</body>
</html>