Hello,
I am making a simple text changer website where I want the user to be able to select what options to use. Right now I have two options; myConvertOption which capitalizes every odd letter in a word and I have myScrambleOption which randomly mixes up each word a bit.
Right now whenever you click on Caps (checkbox_1) it already executes the function where I only want it to execute whenever the user clicks on the "Convert" button + it also puts spaces in between each letter now.
The Scramble button (checkbox_2) doesn't do anything for some reason, except for console logging the change.
JSfiddle: https://jsfiddle.net/MysteriousDuck/hLjytr2p/1/
Any help and suggestions will be greatly appreciated!
P.S I am new to Javascript.
Checkbox event listeners:
checkbox_1.addEventListener('change', function () {
console.log("checkbox_1 changed");
if (this.checked) {
myConvertFunction();
} else {
//Do nothing
}
})
checkbox_2.addEventListener('change', function () {
console.log("checkbox_2 changed");
if (this.checked) {
myScrambleFunction(text);
} else {
//Do nothing
}
})
Checkbox HTML:
<div class="checkbox">
<input type="checkbox" id="checkbox_1" >
<label for="checkbox_1">Caps</label>
</div>
<div class="checkbox">
<input type="checkbox" id="checkbox_2" >
<label for="checkbox_2">Scramble</label>
</div>
this works properly..
You just had to add the event on the button and then test which check box was checked, and other little things
<!doctype html>
<html>
<head>
</head>
<body>
<div class="container">
<h1> Text Changer </h1>
<h2> CAPS + randomize letters text changer</h2>
<div class="checkbox">
<input type="checkbox" id="checkbox_1">
<label for="checkbox_1">Caps</label>
</div>
<div class="checkbox">
<input type="checkbox" id="checkbox_2">
<label for="checkbox_2">Scramble</label>
</div>
<textarea type="text" autofocus="true" placeholder="input text" id="inputText" value="Input Value" spellcheck="false" style="width: 300px;"></textarea>
<button class="button button1" id="convertText">Convert</button>
<textarea type="text" placeholder="converted text" id="convertedText" value="Clear" readonly="true" spellcheck="false" style="width: 300px;"></textarea>
<button class="button button1" id="copyText">Copy</button>
</div>
<script>
var text = document.getElementById("inputText").value;
var convertText = document.getElementById("convertText");
var checkbox_2 = document.getElementById("checkbox_2");
var checkbox_1 = document.getElementById("checkbox_1");
//Capitalize every odd letter
function myConvertFunction() {
var x = document.getElementById("inputText").value;
var string = "";
for (let i = 0; i < x.length; i++) {
if (i % 2 == 0) {
string = string + x[i].toUpperCase();
} else {
string = string + x[i];;
}
}
return string;
}
//Scramble words
function myScrambleFunction(text) {
let words = text.split(" ");
words = words.map(word => {
if (word.length >= 3) {
return word.split('').sort(() => 0.7 - Math.random()).join('');
}
return word;
});
return words.join(' ');
}
document.getElementById("copyText").addEventListener("click", myCopyFunction);
//Copy textarea output
function myCopyFunction() {
var copyText = document.getElementById("convertedText");
copyText.select();
document.execCommand("copy");
alert("Copied the text: " + copyText.value);
eraseText();
}
//Delete textarea output
function eraseText() {
document.getElementById("convertedText").value = "";
document.getElementById("inputText").value = "";
document.getElementById("inputText").focus();
}
//don't add the event to the radio buttons (previously checkboxes), add it to the convert button, and in its function test which radio button has been checked
convertText.addEventListener('click', function() {
if (checkbox_1.checked && checkbox_2.checked) {
console.log("doing both options");
document.getElementById("convertedText").value = myScrambleFunction(myConvertFunction());
} else if (checkbox_2.checked) {
console.log("proceeding scrumble");
document.getElementById("convertedText").value = myScrambleFunction(text);
} else if (checkbox_1.checked) {
console.log("proceeding cap");
document.getElementById("convertedText").value = myConvertFunction();
}
})
</script>
</body>
</html>
You're never updating var text.
You need to update it before using it if you want the value to be something other than an empty string.
checkbox_2.addEventListener('change', function () {
console.log("checkbox_2 changed");
if (this.checked) {
text = document.getElementById("inputText").value;
myScrambleFunction(text);
} else {
//Do nothing
}
Related
How do I enable input2 if enable 1 has input within it (basically re-enabling it), I'm still a beginner and have no idea to do this.
<form id="form1">
<input type="text" id="text1" onkeyup="valid()">
<input type="text" id="text2" disabled="disabled">
<script language="javascript">
function valid() {
var firstTag = document.getElementById("text1").length;
var min = 1;
if (firstTag > min)
//if the text entered is longer than 1 alert to screen
{
//enable the text2 tag
}
}
//once input from text1 is entered launch this function
</script>
</form>
if i understand your question correctly, you want to enable the second input as long as the first input have value in it?
then use dom to change the disabled state of that input
if(firstTag > min)
//if the text entered is longer than 1 alert to screen
{
//enable the text2 tag
document.getElementById("text2").disabled = false;
}
Please try this code :
var text1 = document.getElementById("text1");
text1.onchange = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("text2").disabled = false;
} else {
document.getElementById("text2").disabled = true;
}
}
<input type="text" id="text1">
<input type="text" id="text2" disabled="disabled">
I think you should use .value to get the value. And, then test its .length. That is firstTag should be:
var firstTag = document.getElementById("text1").value.length;
And, the complete function should be:
function valid() {
var min = 1;
var firstTag = document.getElementById("text1");
var secondTag = document.getElementById("text2");
if (firstTag.length > min) {
secondTag.disabled = false
} else {
secondTag.disabled = true
}
}
Let me know if that works.
You can use the .disabled property of the second element. It is a boolean property (true/false).
Also note that you need to use .value to retrieve the text of an input element.
Demo:
function valid() {
var text = document.getElementById("text1").value;
var minLength = 1;
document.getElementById("text2").disabled = text.length < minLength;
}
valid(); // run it at least once on start
<input type="text" id="text1" onkeyup="valid()">
<input type="text" id="text2">
I would just change #Korat code event to keyup like this:
<div>
<input type="text" id="in1" onkeyup="enablesecond()";/>
<input type="text" id="in2" disabled="true"/>
</div>
<script>
var text1 = document.getElementById("in1");
text1.onkeyup = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("in2").disabled = false;
} else {
document.getElementById("in2").disabled = true;
}
}
</script>
I tried to create my own so that I could automate this for more than just two inputs although the output is always set to null, is it that I cannot give text2's id from text1?
<div id="content">
<form id="form1">
<input type="text" id="text1" onkeyup="valid(this.id,text2)">
<input type="text" id="text2" disabled="disabled">
<script language ="javascript">
function valid(firstID,secondID){
var firstTag = document.getElementById(firstID).value.length;
var min = 0;
if(firstTag > min)
//if the text entered is longer than 1 alert to screen
{
document.getElementById(secondID).disabled = false;
}
if(firstTag == 0){
document.getElementById(secondID).disabled = true;
}
}
//once input from text1 is entered launch this function
</script>
</form>
First, you have to correct your code "document.getElementById("text1").length" to "document.getElementById("text1").value.length".
Second, there are two ways you can remove disabled property.
1) Jquery - $('#text2').prop('disabled', false);
2) Javascript - document.getElementById("text2").disabled = false;
Below is the example using javascript,
function valid() {
var firstTag = document.getElementById("text1").value.length;
var min = 1;
if (firstTag > min) {
document.getElementById("text2").disabled = false;
}
else
{
document.getElementById("text2").disabled = true;
}
}
<input type="text" id="text1" onkeyup="valid()">
<input type="text" id="text2" disabled="disabled">
If I understand you correctly, what you are asking is how to remove the disabled attribute (enable) from the second input when more than 1 character has been entered into the first input field.
You can to use the oninput event. This will call your function every time a new character is added to the first input field. Then you just need to set the second input field's disabled attribute to false.
Here is a working example.
Run this example at Repl.it
<!DOCTYPE html>
<html>
<body>
<!-- Call enableInput2 on input event -->
<input id="input1" oninput="enableInput2()">
<input id="input2" disabled>
<script>
function enableInput2() {
// get the text from the input1 field
var input1 = document.getElementById("input1").value;
if (input1.length > 1) {
// enable input2 by setting disabled attribute to 'false'
document.getElementById("input2").disabled = false;
} else {
// disable input2 once there is 1 or less characters in input1
document.getElementById("input2").disabled = true;
}
}
</script>
</body>
</html>
NOTE: It is better practice to use addEventListener instead of putting event handlers (e.g. onclick, oninput, etc.) directly into HTML.
I am trying to display an onclick alert if the box is filled in with the world "hello", while a different alert should pop up in "hello" is not typed.
Not sure what I am doing wrong here:
The HTML:
<form>
<input id="box" placeholder="type hello" onchange="sayHello()" style="display: block;" />
<input type="button" onclick="sayHelloTwo()" value="Click me" />
<p id="hidden" style="display: none;">
HELLO
</p>
</form>
The JavaScript:
function sayHello() {
var answer = "hello";
if (answer) {
alert("Click for Hello!");
} else {
alert("you need to type hello!");
return false;
}
}
function sayHelloTwo() {
document.getElementById("hidden").style.display = "block";
document.getElementById("hidden").style.color = "#909090";
document.getElementById("hidden").style.fontSize = "40px";
}
You need to check the actual value that the user entered in the box, and then compare it to the value you want (the value inside your answer variable).
There are several ways to do so, one of the is using
document.getElementById('box').value
(Where box is the id of your element).
Here is a working example:
function sayHello() {
var answer = "hello";
var text = document.getElementById('box').value;
if (text == answer) {
alert("Click for Hello!");
} else {
alert("you need to type hello!");
return false;
}
}
function sayHelloTwo() {
document.getElementById("hidden").style.display = "block";
document.getElementById("hidden").style.color = "#909090";
document.getElementById("hidden").style.fontSize = "40px";
}
<form>
<input id="box" placeholder="type hello" onchange="sayHello()" style="display: block;" />
<input type="button" onclick="sayHelloTwo()" value="Click me" />
<p id="hidden" style="display: none;">
HELLO
</p>
</form>
To elaborate on Dekels answer some more, the click event also has an event property attached to it that you can use to get the value, like this.
function sayHello(e) {
if (e.currentTarget.value == "hello") {
alert("Click for Hello!");
} else {
alert("you need to type hello!");
return false;
}
}
You have error in checking condition for answer
function sayHello() {
var answer = "hello";
if (answer == "hello") {
alert("Click for Hello!");
} else {
alert("you need to type hello!");
return false;
}
}
You can pass the element value directly as a parameter this.value in your html.
Notice that to make the code case insensitive you must convert the value to lowercase and than check the if statement value.toLowerCase() !== 'hello'
Code:
function sayHello(value) {
if (value.toLowerCase() !== 'hello') {
alert('You need to type hello!');
return false;
}
alert('Click for Hello!');
}
function sayHelloTwo() {
var hidden = document.getElementById('hidden')
hidden.style.display = 'block';
hidden.style.color = '#909090';
hidden.style.fontSize = '40px';
}
<form>
<input id="box" placeholder="type hello" onchange="sayHello(this.value)" style="display: block;" />
<input type="button" onclick="sayHelloTwo()" value="Click me" />
<p id="hidden" style="display: none;">
HELLO
</p>
</form>
I found the below code online to add bullet points to a textarea, and it works quite well for a single textarea.
Script
var CRLF = 10;
var BULLET = String.fromCharCode(45);
function Init() {
var textareas = document.querySelectorAll('textarea');
[].forEach.call(textareas, function(element) {
element.addEventListener("input", OnInput, false);
});
}
function OnInput(event) {
char = event.target.value.substr(-1).charCodeAt(0);
nowLen = txt.value.length;
if (nowLen > prevLen.value) {
if (char == CRLF) txt.value = txt.value + BULLET + " ";
if (nowLen == 1) txt.value = BULLET + " " + txt.value;
}
prevLen.value = nowLen;
}
HTML
<body onload="Init ();">
<h4>Automatic bullets in a text box</h4>
<textarea id="txt" oninput="OnInput(this, 'prevLen');" rows="15" cols="40"></textarea>
<input type="hidden" id="prevLen" value="0"/>
</body>
However, I can't figure out how to create a similar function such that I can use it on multiple textareas.
I would like something where I can pass through the id of the hidden input, so I can specify that way which input to add the bullet points to, but can't get a working solution.
Suggestions/solutions welcome.
Get a list of all textareas and add the event listener
var textareas = document.querySelectorAll('textarea');
[].forEach.call(textareas, function(element) {
element.addEventListener("click", OnInput, false);
});
You can use any valid CSS3 selector to get the desired textareas.
As per your edit:
You can group the elements together so you can access them as a group. Now you can use the input in any way you like.
<div class="some_wrapper">
<textarea id="txt" oninput="OnInput(this, 'prevLen');" rows="15" cols="40"></textarea>
<input type="hidden" id="prevLen" value="0"/>
</div>
var wrappers = document.querySelectorAll('some_wrapper');
[].forEach.call(wrappers, function(wrapper) {
var textarea = wrapper.querySelector("textarea"),
input = wrapper.querySelector("input");
//process "input" to get the desired "id", "class",.....
textarea.addEventListener("click", function(e) {
OnInput(e, input)
}, false);
});
Solution to my query/issue:
Script/app.js:
var CRLF = 10;
var BULLET = String.fromCharCode(45);
function Init() {
var wrappers = document.querySelectorAll('panel-body');
[].forEach.call(wrappers, function(wrapper) {
var textarea = wrapper.querySelector("textarea"),
input = wrapper.querySelector("input");
textarea.addEventListener("input", OnInput(), false);
});
}
function OnInput(ta,inp) {
char = ta.value.substr(-1).charCodeAt(0);
nowLen = ta.value.length;
if (nowLen > inp.value) {
if (char == CRLF) ta.value = ta.value + BULLET + " ";
if (nowLen == 1) ta.value = BULLET + " " + ta.value;
}
inp.value = nowLen;
}
HTML
<body onload="Init ();">
<div class="panel-body">
<h4>Automatic bullets in a text box</h4>
<textarea id="ta1" oninput="OnInput(ta1, pv1);" rows="15" cols="40"></textarea>
<input type="hidden" id="pv1" value="0"/>
<h4>Automatic bullets in a text box</h4>
<textarea id="ta2" oninput="OnInput(ta2,pv2);" rows="15" cols="40"></textarea>
<input type="hidden" id="pv2" value="0"/>
</div>
</body>
The above solution solves the issue of adding bullets to multiple textareas.
I have 2 text Boxes and one button! When I click on button it should write 1 in the chosen text box but my code is not working.
my code:
function one() {
var number = "1";
if (document.getElementById("txt1").focused) {
document.getElementById("txt1").value = number;
}
else if (document.getElementById("txt2").focused) {
document.getElementById("txt2").value = number;
}
else {
}
You can do some thing like this:
<input type="text" onfocus="onFocus(this)" id="itext1"></input>
<input type="text" onfocus="onFocus(this)" id="itext2"></input>
<button onclick="setValue()">ClickMe</button>
<script>
var selectedDOM = undefined;
function setValue() {
if (selectedDOM) { //selecteddom is present set text to it
selectedDOM.value = 1;
}
}
function onFocus(e) {
selectedDOM = e;//register the last dom selected inside the variable.
}
</script>
Full working code here
You can use onfocus property to perform this instead.
HTML
<input type="text" onfocus="myFocusFunction(this)">
<input type="text" onfocus="myPlaceholderFunction(this)">
Javascript
function myFocusFunction(x) {
x.value = "1";
}
function myPlaceholderFunction(x) {
x.placeholder = "1";
}
Above are two approaches to set value in text box when focused. You can apply any of them prior will add a value and later will add a placeholder instead.
Working Demo : JSFiddle
You can do like this
<div>
<input type="text" id="txt1">
<input type="text" id="txt2">
<button type ="button" id='button'>Click Me </button>
</div>
JavaScript
(function(){
var number ='1';
var _thisId=null;
var _button = document.getElementById('button');
_button.addEventListener('mouseover',function(){
_thisId = document.activeElement.id;
},false)
_button.addEventListener('click',function(){
if(_thisId =='txt1'){
document.getElementById("txt2").value = "";
document.getElementById("txt1").value = number;
}
else if(_thisId =='txt2'){
document.getElementById("txt1").value = "";
document.getElementById("txt2").value = number;
}
})
}())
jsfiddle
I creating a HTML generator, I've used checkbox in the form.
In the resulting code, I'm getting the unchecked boxes as ''.
I have the current code setup at http://jsfiddle.net/Rqe6K/ for your review.
How can the final result be achieved so that only the checked box values are part of the text?
<button onclick="toggle('answer','1','','3','')">Click</button> from this the blank space of the respective checkboxes should be removed.
<form id="band" action="#">
<label>Option 1: <input type="text" id="a1o1"><input type="checkbox" id="a1" class="can"></label><br>
<label>Option 2: <input type="text" id="a1o2"><input type="checkbox" id="a2" class="can"></label><br>
<label>Option 3: <input type="text" id="a1o3"> <input type="checkbox" id="a3" class="can"></label><br>
<label>Option 4: <input type="text" id="a1o4"><input type="checkbox" id="a4" class="can"></label><br>
<input type="submit"></input>
</form>
<p>Copy this:</p>
<textarea rows="20" cols="80" id="code"></textarea>
<script type="text/javascript">
window.onload = function() {
document.getElementById('band').onsubmit = function() {
box1 = '';
box2 = '';
box3 = '';
box4 = '';
if (document.getElementById('a1').checked) { box1 = '1'; }
if (document.getElementById('a2').checked) { box2 = '2'; }
if (document.getElementById('a3').checked) { box3 = '3'; }
if (document.getElementById('a4').checked) { box4 = '4'; }
var text="<button onclick=\"toggle(\'answer\',\'"+box1+"'\,\'"+box2+"'\,\'"+box3+"'\,\'"+box4+"'\)\">Click</button>";
document.getElementById('code').value=text;
return false;
}
}
</script>
If you put an ID called a1o1 but then try to find it using a1, it is normal that the browser never find the control.
UPDATE
Not very cool, but works...
http://jsfiddle.net/A6f9r/
UPDATE2
http://jsfiddle.net/v7rfN/
First of all declare the variables instead of making it global.
i.e. var box1='';
Use this logic-
var text="<button onclick=\"toggle(\'answer\',\'";
if(box1!='')
{
text+=box1+"'\,\'";
}
if(box2!='')
{
text+=box2+"'\,\'";
}
if(box3!='')
{
text+=box3+"'\,\'";
}
if(box4!='')
{
text+=box4+"'\)\'";
}
text = text.substring(0, text.length - 2);
text+=")\">Click</button>";
See fiddle-http://jsfiddle.net/Rqe6K/2/
If you can use jQuery I warmly suggest it, since its syntax is concise:
$("#sendAnswer").click(function(){
var answers = $("input[name='answer[]']").map(function(){if(this.checked){return this.id;}}).get();
var text = "<button onclick=\"toggle(\'answer\'," + serializeInputValues(answers) + ")\">Click</button>";
$('#code').val(text);
return false;
})
function serializeInputValues(fields){
var sStr = "";
jQuery.each(fields, function(i, field){
sStr += "'" + field + "', ";
});
return sStr.slice(0, -2);
}
Try this fiddle.
EDIT: With this approach, your answer can grows and your code still remain the same, with your approach you have to add an if for each new checkbox driving you to a potential combinatorial explosion.