Appendchild() with two inputs, and removing latest post - javascript

I have two input, textarea (name + comment) and Submit button. Onclick should post text from input and textarea. I use appendchild(), but need to call textarea.
1. How should I do it?
2. Button "Delete" remove all post, but I need delete just the last one. So how it is possible?
Thank you for any tips.
There is the code:
<script type="text/javascript">
function append(form) {
if (form.input.value) {
var newItem = document.createElement("div");
newItem.appendChild(document.createTextNode(form.input.value));
document.getElementById("myDiv").appendChild(newItem);
}
}
function restore() {
var oneChild;
var mainObj = document.getElementById("myDiv");
while (mainObj.childNodes.length > 0) {
oneChild = mainObj.lastChild;
mainObj.removeChild(oneChild);
}
}
</script>
<form>Name:
<br>
<input type="text" name="input" />
<br />Comment:
<br>
<textarea type="text" name="textarea"></textarea>
<br />
<input type="button" value="Submit" onclick="append(this.form)" />
<input type="button" value="Delete" onclick="restore()" />
</form>
<div id="myDiv"></div>

Problem is because you are saying while there are posts delete last one.
Put just this code in restore. It will remove last child once.
function restore() {
var oneChild;
var mainObj = document.getElementById("myDiv");
oneChild = mainObj.lastChild;
mainObj.removeChild(oneChild);
}

To solve your append issue:
function append(form) {
if (form.input.value) {
var newItem = document.createElement("div");
newItem.appendChild(document.createTextNode(form.input.value));
//add a line break and the text from textarea
newItem.appendChild(document.createElement("br"));
newItem.appendChild(document.createTextNode(form.textarea.value));
document.getElementById("myDiv").appendChild(newItem);
}
}
If you want to delete the last item only, you have to convert the while loop to an if condition:
function restore() {
var oneChild;
var mainObj = document.getElementById("myDiv");
if (mainObj.childNodes.length > 0) {
oneChild = mainObj.lastChild;
mainObj.removeChild(oneChild);
}
}

Related

How to connect JS functions to checkbox

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
}

How to set value with input text to get tag and set condition on text in jquery

How i can set value to jquery inseted set html code
in this question i set value on body
link
how i can set html code with input text and work like link
i write this code
<input type="text" style="width: 400px;height:400px;" class="in" /><br />
<input type="button" value="submit" onclick="myFunction()" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function myFunction() {
var text = $("input:text").val();
console.log(text);//its ok but i don't how to use text in arr
var arr = $('ol li').map(function () {
var $li = $(this);
return {
value: $li.find('.Value').text(),
name: $li.find('.Name').text()
}
}).get();
console.log(arr);
}
</script>
</body>
</html>
Do you want set Text box value by jquery?
$('.in').val('your custom value or text');
First. For input multiline you need to use <textarea>
Then split string with
("Yourtext").split("Your Seperator",limit_arraysize);
//example
alert(("Howdy! I'm Flowey the flower").split(" ",3));
//That mean you split with " " (1 blank space)
OUTPUT:
[
"Howdy!"
,"I'm"
,"Flowey"
]
Some example below
function myFunction() {
var arr = [];
var text = $("textarea").val();
var submit = text.split("\n"); // USE TO split multiline
for (var i = 0; i < submit.length; i++) {
var temp = submit[i].split(",", 2);
arr[i] = {
value: temp[0],
name: temp[1]
};
}
console.log(arr);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea type="text" style="width: 400px;height:200px;" class="in">
25,ok
80,good
90,no</textarea>
<!--use TEXTAREA instead INPUT for multiline-->
<br>
<input type="button" value="submit" onclick="myFunction()" />

Why aren't the user inputs being put into the empty array?

I'm trying to write a program so that once the user clicks the 'Add!' button, the string that they typed will be added to an initially empty array in an object, and then that updated array will be displayed back on the HTML page. However, when I checked what the value of the items array was when I typed something in, it still appeared to be null. I'm fairly certain that the addItem function is fine, is the problem in the updateList function?
HTML CODE:
<!DOCTYPE html>
<html>
<head>
<title>Homework 5</title>
<!--<link rel="stylesheet" type="text/css" href="index.css">-->
<script src="toDoList.js"></script>
</head>
<body>
<h1>Homework 5: JS Objects & HTML DOM</h1>
<div id="input">
<input id="userInput" type="text" placeholder="Type a word">
<button id="submit">Add</button>
</div>
<div id="output"></div>
<h1>Design</h1>
<h1>Challenges</h1>
</body>
</html>
JAVASCRIPT CODE:
var button = document.getElementById("submit");
var toDoList = {
items: [],
add: addItem,
update: updateList
};
function addItem(string) {
toDoList.items.push(string);
}
function updateList() {
var output = document.getElementById("output");
output.innerHTML = toDoList.items;
}
function getInput() {
var input = document.getElementById("userInput").value;
toDoList.add(input);
toDoList.update();
//clearing the text field for next use
document.getElementById("userInput").innerHTML = "";
}
button.addEventListener('click', getInput());
The second argument provided to addEventListener needs to be a function. If you put a function invocation there, that function is executed immediately, with its return value assigned as the handler. But if the return value isn't a function, the event listener doesn't work.
In your case, you just want getInput to be run when the button is clicked - getInput is not a higher-order function, so just pass the function itself, rather than invoking it:
button.addEventListener('click', getInput);
Like this
var button = document.getElementById("submit");
var toDoList = {
items: [],
add: addItem,
update: updateList
};
function addItem(string) {
toDoList.items.push(string);
}
function updateList() {
var output = document.getElementById("output");
output.innerHTML = toDoList.items;
}
function getInput() {
var input = document.getElementById("userInput").value;
toDoList.add(input);
toDoList.update();
//clearing the text field for next use
document.getElementById("userInput").innerHTML = "";
}
button.addEventListener('click', getInput);
<h1>Homework 5: JS Objects & HTML DOM</h1>
<div id="input">
<input id="userInput" type="text" placeholder="Type a word">
<button id="submit">Add</button>
</div>
<div id="output"></div>
<h1>Design</h1>
<h1>Challenges</h1>
You should not invoke or execute the function in addEventListener. Invoking function causes the function to execute immediately not when the event (click) happens. So remove parenthesis after the function name.
Change button.addEventListener('click', getInput());
To
button.addEventListener('click', getInput);
var button = document.getElementById("submit");
var toDoList = {
items: [],
add: addItem,
update: updateList
};
function addItem(string) {
toDoList.items.push(string);
}
function updateList() {
var output = document.getElementById("output");
output.innerHTML = toDoList.items;
}
function getInput() {
var input = document.getElementById("userInput").value;
toDoList.add(input);
toDoList.update();
//clearing the text field for next use
document.getElementById("userInput").innerHTML = "";
}
button.addEventListener('click', getInput);
<h1>Homework 5: JS Objects & HTML DOM</h1>
<div id="input">
<input id="userInput" type="text" placeholder="Type a word">
<button id="submit">Add</button>
</div>
<div id="output"></div>
<h1>Design</h1>
<h1>Challenges</h1>
I think, you have to loop through your array. to get the content:
var x = ['apple','banana','orange'];
var output = "";
for (i=0;i<x.length;i++) {
output += x[i];
}
alert(output); //--> outputs applebananaorange
alert(x.items); //--> undefined (whats your case)

How do I change the class of a forms parent if they enter it wrong?

I'm using a at the moment in order to add a search feature to my site. I want them to enter a number that starts with 765611 and then has 11 numbers after that; if they type in a correct number, it will run the below script:
var a = document.getElementById('search');
a.addEventListener('submit',function(e) {
e.preventDefault();
var b = document.getElementById('searchbar').value;
window.location.href = 'thecopperkings.co.uk'+b;
});
If they enter a wrong number (i.e. one that does not start with 765611 and have 11 numbers proceeding it) the background of the div will flash red for two seconds (I assume the way this would be done is by adding a temporary class value which has a red background) with a transition as well, and the above code wouldn't run.
I'm pretty terrible (and new) to JS but looking at other peoples code and my basic knowledge, I assume it would have to be something along the lines of this:
var search = document.getElementByID('search');
a.addEventListener('submit',function(e) {
if document.getElementByID('searchbar').value = "765611[0-9]{11}$" {
e.preventDefault();
var b = document.getElementById('searchbar').value;
window.location.href = 'thecopperkings.co.uk'+b;
}
else {
**SET THE FORM'S CLASS TO "RED"?**
}
What is the best and most efficient way of doing this?
var a = document.getElementById('search');
a.addEventListener('submit',function(e) {
e.preventDefault();
var b = document.getElementById('searchbar').value;
window.location.href = 'thecopperkings.co.uk'+b;
});
<div>
<form class="search" id="search" method="get" action="html/player.html">
<input type="text" placeholder="What is your SteamID?" id="searchbar" name="id" maxlength="17">
<input type="submit" value="Search">
</form>
</div>
Please find the below answer.
working example can be found here jsFiddle
Add class red as .red { background-color:red !important;}
var a = document.getElementById('search');
function appendClass(elementId, classToAppend){
var oldClass = document.getElementById(elementId).getAttribute("class");
if (oldClass.indexOf(classToAppend) == -1)
{
document.getElementById(elementId).setAttribute("class", oldClass+ " "+classToAppend);
}
}
function removeClass(elementId, classToRemove){
var oldClass = document.getElementById(elementId).getAttribute("class");
if (oldClass.indexOf(classToRemove) !== -1)
{ document.getElementById(elementId).setAttribute("class",oldClass.replace(classToRemove,''));
}
}
a.addEventListener('submit',function(e) {
e.preventDefault();
var b = document.getElementById('searchbar').value;
//regular expression to match your criteria and test the sample value
if(/^765611[0-9]{11}$/.test(b)) {
alert('success -> '+ b );
window.location.href = 'thecopperkings.co.uk'+b;
} else {
//append the class red for searchid which is in form element
appendClass('search','red');
//remove the red class after 2sec(2000milliseconds)
window.setTimeout(function(){removeClass('search','red');},2000);
}
});
<div>
<form class="search" id="search" method="get" action="html/player.html">
<input type="text" placeholder="What is your SteamID?" id="searchbar" name="id" maxlength="17">
<input type="submit" value="Search">
</form>
</div>
var patt = new RegExp("765611[0-9]{11}$");
var searchbar = document.getElementByID('searchbar');
var searchForm = document.getElementByID('search');
if( patt.test(searchbar.value) ){
searchForm.classlist.remove('error');
// do your magic
} else{
searchForm.classlist.add('error');
// And maybe an alert or notice for the user
}
Also, check out the html5 input attribute pattern=""

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

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

Categories