Cannot get rid of page reload in html/javascript form - javascript

I am trying to set up a form in which buttons fill input fields and in which those input fields can again be emptied by other "delete" buttons.
This works quite well, but I cannot get rid of one problem in a special action sequence:
If I press buttons "one" and "three", the corresponding input forms are filled properly, this is what I want.
Now if after that I press the "Delete A" button, one of two unwanted things happen:
If the command event.preventDefault() exists in line 15, then (only) the first input field gets cleared correctly and the buttons are restored. But when I then again press button "one", the complete form gets cleared and the word "three" vanishes from form 2.
If the command event.preventDefault() is deleted from line 15, then as soon as I press "Delete A", the complete form gets cleared and also the word "three" vanishes from form 2.
I do not want to clear the complete form to be reloaded at any stage.
EDIT: The problem is not a question of returning false values from functions to prevent form submission as discussed in JavaScript code to stop form submission . in fact all my fucntions are returning falsevalues.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
</head>
<script>
function evt_r(){
var task = document.getElementById("task_"+arguments[0]);
var tasklabel = arguments[0];
var texts = Array.from(arguments).slice(1)
var length = task.getElementsByTagName("button").length - 1;
event.preventDefault()
// remove existing buttons
for (let i =0; i < length; i++){
task.removeChild(task.getElementsByTagName("button")[0]);
}
// recreate all buttons from scratch
for (let i =texts.length-1; i >=0 ; i--){
btn = document.createElement("button");
btn.innerHTML = texts[i];
btn.onclick= "evt_"+String(tasklabel)+"_"+String(i)+"()";
btn.id="id_btn_"+String(tasklabel)+"_"+String(i);
task.insertBefore(btn, task.firstChild);
task.children[0].style.marginRight ="5px";
}
document.getElementById("id_task_"+String(tasklabel)).value="";
return false;
}
function evt_0_0(){
var elem = document.getElementById("id_btn_0_0");
event.preventDefault()
elem.parentNode.removeChild(elem);
document.getElementById("id_task_0").value=document.getElementById("id_task_0").value +"one "
return false;
}
function evt_0_1(){
var elem = document.getElementById("id_btn_0_1");
event.preventDefault()
elem.parentNode.removeChild(elem);
document.getElementById("id_task_0").value=document.getElementById("id_task_0").value +"two "
return false;
}
function evt_1_0(){
var elem = document.getElementById("id_btn_1_0");
event.preventDefault()
elem.parentNode.removeChild(elem);
document.getElementById("id_task_1").value=document.getElementById("id_task_1").value +"three "
return false;
}
function evt_1_1(){
var elem = document.getElementById("id_btn_1_1");
event.preventDefault()
elem.parentNode.removeChild(elem);
document.getElementById("id_task_1").value=document.getElementById("id_task_1").value +"four "
return false;
}
</script>
<body>
<ol>
<li style="margin-bottom:8px"><form id = "task_0" >
<button id="id_btn_0_0" onclick="evt_0_0()">one</button>
<button id="id_btn_0_1" onclick="evt_0_1()">two</button>
<button id="id_btn_0_r" onclick='evt_r("0", "one", "two")' style="margin-left:50px">Delete A</button>
<br>
<input id="id_task_0" style="margin-top:10px" ></input>
</form>
<li style="margin-bottom:8px"><form id = "task_1" >
<button id="id_btn_1_0" onclick="evt_1_0()">three</button>
<button id="id_btn_1_1" onclick="evt_1_1()">four</button>
<button id="id_btn_1_r" onclick='evt_r("1", "three", "four")' style="margin-left:50px">Delete B</button>
<br>
<input id="id_task_1" style="margin-top:10px" ></input>
</form>
</body>
</html>

The issue with your btn.onclick initialization in evt_r(). You are assigning it a string. Since your new buttons are in a form and not calling event.preventDefault() in this case, the page is refreshing. Try doing doing btn.onclick=new Function("evt_"+String(tasklabel)+"_"+String(i)+"()"); instead. So your html becomes:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
</head>
<script>
function evt_r(){
var task = document.getElementById("task_"+arguments[0]);
var tasklabel = arguments[0];
var texts = Array.from(arguments).slice(1)
var length = task.getElementsByTagName("button").length - 1;
event.preventDefault();
// remove existing buttons
for (let i =0; i < length; i++){
task.removeChild(task.getElementsByTagName("button")[0]);
}
// recreate all buttons from scratch
for (let i =texts.length-1; i >=0 ; i--){
btn = document.createElement("button");
btn.innerHTML = texts[i];
btn.onclick=new Function("evt_"+String(tasklabel)+"_"+String(i)+"()");
btn.id="id_btn_"+String(tasklabel)+"_"+String(i);
task.insertBefore(btn, task.firstChild);
task.children[0].style.marginRight ="5px";
}
document.getElementById("id_task_"+String(tasklabel)).value="";
return false;
}
function evt_0_0(){
var elem = document.getElementById("id_btn_0_0");
event.preventDefault()
elem.parentNode.removeChild(elem);
document.getElementById("id_task_0").value=document.getElementById("id_task_0").value +"one "
return false;
}
function evt_0_1(){
var elem = document.getElementById("id_btn_0_1");
event.preventDefault()
elem.parentNode.removeChild(elem);
document.getElementById("id_task_0").value=document.getElementById("id_task_0").value +"two "
return false;
}
function evt_1_0(){
var elem = document.getElementById("id_btn_1_0");
event.preventDefault()
elem.parentNode.removeChild(elem);
document.getElementById("id_task_1").value=document.getElementById("id_task_1").value +"three "
return false;
}
function evt_1_1(){
var elem = document.getElementById("id_btn_1_1");
event.preventDefault()
elem.parentNode.removeChild(elem);
document.getElementById("id_task_1").value=document.getElementById("id_task_1").value +"four "
return false;
}
</script>
<body>
<ol>
<li style="margin-bottom:8px"><form id = "task_0" >
<button id="id_btn_0_0" onclick="evt_0_0()">one</button>
<button id="id_btn_0_1" onclick="evt_0_1()">two</button>
<button id="id_btn_0_r" onclick='evt_r("0", "one", "two")' style="margin-left:50px">Delete A</button>
<br>
<input id="id_task_0" style="margin-top:10px" ></input>
</form>
<li style="margin-bottom:8px"><form id = "task_1" >
<button id="id_btn_1_0" onclick="evt_1_0()">three</button>
<button id="id_btn_1_1" onclick="evt_1_1()">four</button>
<button id="id_btn_1_r" onclick='evt_r("1", "three", "four")' style="margin-left:50px">Delete B</button>
<br>
<input id="id_task_1" style="margin-top:10px" ></input>
</form>
</body>
</html>

Related

Event listener not displaying line-through when ticking checkbox of list item

I’ve created a function named checkedItems. I want the function to cross an item out each time the check box attached to it is ticked. However, nothing happens when I do so. If someone could point out where I’ve gone wrong in my code and fix it, that would be great.
var elUlList = document.getElementById("ulList");
var btn = document.getElementById("btn");
const elInput = document.getElementById("input");
const footer = document.querySelector("footer");
const message = document.getElementById("message");
const elCounter = document.getElementById("counter");
function createListItems() {
var elements = document.getElementsByTagName('li');
console.log(elements)
var inputValue = elInput.value;
var newLi = document.createElement("li");
var input = document.createElement("input")
input.type = "checkbox"
var newText = document.createTextNode(inputValue);
newLi.appendChild(input);
newLi.appendChild(newText);
elUlList.appendChild(newLi)
}
btn.addEventListener("click", createListItems, false);
elInput.addEventListener("keyup", function(e) {
if (e.keyCode === 13) {
e.preventDefault();
btn.click()
}
})
elInput.addEventListener("mouseover", emptyField, false)
function emptyField() {
this.value = "";
}
elUlList.addEventListener("change", checkedItems, false)
function checkedItems() {
var checkboxes = document.querySelectorAll("input[type=checkbox]")
var checkboxesArray = Array.from(checkboxes);
console.log(checkboxes.length);
if (checkboxes.length > 1) {
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked
? checkboxes[i].classList.toggle("lineThrough")
: null;
}
}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<div id="message" class=""></div>
<ul id="ulList"></ul>
<button id="btn" type="button" name="button">click here to add items</button>
<input id="input" type="text" name="" value="">
<div id="counter" class=""></div>
<footer></footer>
<script src="index.js" type="text/javascript"></script>
</body>
</html>
Converting comments to an answer: you’re applying the lineThrough class to the checkbox, not its parent element, the <li>. The <li> contains the text.
The function referenced in elUlList.addEventListener("change", checkedItems, false) can be shortened:
const checkedItems = ({target}) => {
if(target.matches("input[type=checkbox]")){
target.closest("li").classList.toggle("lineThrough", target.checked);
}
}
target.closest("li") will always find the <li> that contains target (and is the closest parent node in the DOM tree).
toggle accepts a second argument that will set or unset the class "lineThrough" based on the boolean target.checked.
No need to loop, because a change event will only be triggered when you change one specific checkbox, and you want to strike out the text in only this list item, so it’s sufficient to only target that one.
And your conditional operator was wrong: why do you toggle only when the checkbox is checked?
Another thing: checkedItems isn’t a good name for this function, as this name implies that the function returns a list of checked items or something similar, but it doesn’t. strikeOutCheckedItem or toggleCheckedItem is better; there’s also no plural, because this function only deals with one list item at a time.
Finally, make sure you actually have the CSS class defined:
.lineThrough {
text-decoration: line-through;
}
I think this is a better approach
const elUlList = document.getElementById("ulList");
const btn = document.getElementById("btn");
const elInput = document.getElementById("input");
function addItem() {
if (elInput.value !== "") {
const listItem = `<li>
<input type="checkbox">
<span>${elInput.value}</span>
</li>`;
elUlList.insertAdjacentHTML("afterbegin", listItem);
elInput.value = "";
}
}
btn.addEventListener("click", addItem);
elInput.addEventListener("keyup", (e) => {
if (e.key === "Enter") {
addItem();
}
});
function isCompleted() {
const checkboxs = document.querySelectorAll("li input");
const tasks = document.querySelectorAll("li span");
for (let i = 0; i < checkboxs.length; i++) {
if (checkboxs[i].checked) {
tasks[i].classList.toggle("lineThrough");
}
}
}
elUlList.addEventListener("change", isCompleted);
.lineThrough {
text-decoration: line-through;
}
<ul id="ulList"></ul>
<button id="btn" type="button" name="button">
click here to add items
</button>
<input id="input" type="text" />
...

Output paragraph to web page depending on whether a user input answer is true or false

I want to make an application with 3 questions, each with 2 buttons: yes and no. I want to output a different paragraph in response, depending on whether the answer was true or false (not an alert message!). How do I proceed??
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Tegne med Javascript</title>
<script>
function oppstart () {
function hs(){
document.getElementById('utskrift').onclick = "riktig";
}
function hu(){
document.getElementById('utskrift').onclick = "feil";
}
function ss(){
document.getElementById('utskrift1').onclick = "riktig";
}
function su(){
document.getElementById('utskrift1').onclick = "feil";
}
function ts(){
document.getElementById('utskrift2').onclick = "riktig";
}
function tu(){
document.getElementById('utskrift2').onclick = "feil";
}
}
</script>
</head>
<body>
jeg har hode
<p id="utskrift"></p>
<button type="submit" id="hs">Sann</button> <button type="submit"
id="hu">USann</button>
<br>
<br>
<p id="utskrift1"></p>
jeg liker Skyrim <button type="submit" id="ss">Sann</button> <button
type="submit" id="su">USann</button>
<br>
<br>
<p id="utskrift2"></p>
jeg heter Tarzan <button type="submit" id="ts">Sann</button> <button
type="submit" id="tu">USann</button>
</body>
Each question's Yes/No buttons will have a click event callback function that will check the answer given and deliver the correct output.
Don't use submit buttons for this since you aren't actually submitting form data anywhere, regular button types will do.
This can be optimized a bit by combining the 3 functions I'm showing below into a single one, but that will complicate the code beyond beginner level, so you may want to stick with this approach for now.
// Get references to all of the buttons
var q1P = document.getElementById("utskrift1");
var q1Sann = document.getElementById("hs");
var q1Usann = document.getElementById("hu");
var q2P = document.getElementById("utskrift2");
var q2Sann = document.getElementById("ss");
var q2Usann = document.getElementById("su");
var q3P = document.getElementById("utskrift3");
var q3Sann = document.getElementById("ts");
var q3Usann = document.getElementById("tu");
// Set up each set of buttons to invoke a validation function when they are clicked
q1Sann.addEventListener("click", q1Validate);
q1Usann.addEventListener("click", q1Validate);
q2Sann.addEventListener("click", q2Validate);
q2Usann.addEventListener("click", q2Validate);
q3Sann.addEventListener("click", q3Validate);
q3Usann.addEventListener("click", q3Validate);
// Validation functions
function q1Validate (evt) {
var message = "";
// Test which button was clicked and populate the appropriate paragraph accordingly
if(evt.target === q1Sann){
message = "Correct!";
} else {
message = "Incorrect!";
}
// Update the paragraph with the message
q1P.textContent = message;
}
function q2Validate (evt) {
var message = "";
// Test which button was clicked and populate the appropriate paragraph accordingly
if(evt.target === q2Sann){
message = "Correct!";
} else {
message = "Incorrect!";
}
q2P.textContent = message;
}
function q3Validate (evt) {
var message = "";
// Test which button was clicked and populate the appropriate paragraph accordingly
if(evt.target === q3Sann){
message = "Correct!";
} else {
message = "Incorrect!";
}
q3P.textContent = message;
}
p { color: blue; }
<div>
jeg har hode
<button type="button" id="hs">Sann</button>
<button type="button" id="hu">USann</button>
<p id="utskrift1"></p>
</div>
<div>
jeg liker Skyrim
<button type="button" id="ss">Sann</button>
<button type="button" id="su">USann</button>
<p id="utskrift2"></p>
</div>
<div>
jeg heter Tarzan
<button type="button" id="ts">Sann</button>
<button type="button" id="tu">USann</button>
<p id="utskrift3"></p>
</div>

how to cross out the text when clicking checkBox javascript

I'm trying to cross out text next to the checkbox button when the checkbox is clicked by the user. But when I test it, for some reason nothing is happening. I want to check if the box is checked. If it is then I want to to cross that item next to that check box. This function, however does not work. Can someone please explain what I'm doing wrong? thanks.
function myFunction() {
var editButton = document.createElement("button");
//button.delete
var deleteButton = document.createElement("button");
var item = document.getElementById("todoInput").value
var checkBox = document.createElement("input");
checkBox.type = "checkbox";
checkBox.id = "checkbox"
var text = document.createTextNode(item)
var newItem = document.createElement("li")
newItem.className = "addedClass"
newItem.appendChild(text)
if (item === "") {
alert("please fill in the blanks");
} else {
var crap = document.getElementById("todoList")
crap.appendChild(newItem)
var addhere = document.getElementById("todoList")
addhere.appendChild(checkBox);
}
function updateItem() {
if (document.getElementById(checkbox).checked) {
document.getElementById(todoList).style.textDecoration = "line-through"
}
}
}
<form name="myForm" id="todoForm">
<input id="todoInput" name="fname" required>
<button type="button" onclick="myFunction()">OK</button>
</form>
<ol id="todoList"></ol>
first handle event and call the update function and this snippet for you need to add event to checkbox. i hope it should help you thanks.
function myFunction()
{
var item=document.getElementById("todoInput").value
var checkBox = document.createElement("input");
checkBox.type = "checkbox";
checkBox.id="checkbox"
checkBox.onchange=updateItem
var text=document.createTextNode(item)
var newItem=document.createElement("li")
newItem.className="addedClass"
newItem.appendChild(text)
if (item === "")
{
alert("please fill in the blanks");
}
else
{
var crap=document.getElementById("todoList")
crap.appendChild(newItem)
var addhere=document.getElementById("todoList")
addhere.appendChild(checkBox);
}
function updateItem()
{
if (document.getElementById("checkbox").checked)
{
document.getElementById("todoList").style.textDecoration="line-through"
}
}
}
<html>
<form name="myForm" id="todoForm">
<input id="todoInput" name="fname" required >
<button type="button" onclick="myFunction()">OK</button>
</form>
<ol id ="todoList">
</ol>
</html>
you can use other wise HTML5 element for the same purpose.
<strike>not yet available!</strike>
Your code has lot of issues,
Some of the fixes / improvements I have done,
You are missing } or closed inappropriately in your code for myFunction().
Always try to use id for element on which you are going to process. I have added an id on li. (The text node)
function myFunction()
{
var item=document.getElementById("todoInput").value
var checkBox = document.createElement("input");
checkBox.type = "checkbox";
checkBox.id="checkbox"
var text=document.createTextNode(item)
var newItem=document.createElement("li")
newItem.id = "textEl";
newItem.className="addedClass"
newItem.appendChild(text)
if (item === "") {
alert("please fill in the blanks");
}
else{
var crap=document.getElementById("todoList")
crap.appendChild(newItem)
var addhere=document.getElementById("todoList")
addhere.appendChild(checkBox);
document.addEventListener('change', function (e) {
updateItem();
});
}
}
function updateItem()
{
if (document.getElementById("checkbox").checked)
{
document.getElementById("textEl").innerHTML = document.getElementById("textEl").innerHTML.strike();
}
}
<html>
<form name="myForm" id="todoForm">
<input id="todoInput" name="fname" required >
<button type="button" onclick="myFunction()">OK</button>
</form>
<ol id ="todoList">
</ol>
</html>

Get input from textbox and write it below

I need to take the value from an input box and write it below the input box on the click of a button. I thought to use a label but if there is another way I am open to suggestions.
My code so far:
<h1>Test</h1>
<form name="greeting">
Type your name here: <input type = "Text" name="fullname" id="name"> <button onclick="getName()">Create</button><br>
Hello <label id="greet">Hello</label>
</form>
<script lang="javascript">
function getName() {
var inputVal = document.getElementById("name").value;
if (inputVal == "") {
document.getElementById("name").style.backgroundColor = "red";
}
else {
document.write("Hello " + document.getElementById("name"));
}
First of all, you don't want to submit a form, so change button type from "submit" (default) to "button".
Then you should not use document.write almost never, it's used in very specific cases. Use proper DOM manipulation methods like appendChild. I would use convenient insertAdjacentHTML:
function getName() {
var input = document.getElementById("name");
if (input.value == "") {
input.style.backgroundColor = "red";
} else {
input.insertAdjacentHTML('afterend', '<div>' + input.value + '</div>');
}
}
<form name="greeting">Type your name here:
<input type="Text" name="fullname" id="name" />
<button type="button" onclick="getName()">Create</button>
<br>Hello
<label id="greet">Hello</label>
</form>
First you need to stop your form from submitting. Second you should not use document.write, since it will not append the text as wanted after the input field. And last you need to validate the elements value and not the element itself.
<html>
<head>
<script>
//First put the function in the head.
function getName(){
var input = document.getElementById("name");
input.style.backgroundColor = ''; //Reseting the backgroundcolor
if (input.value == ''){ //Add the.value
input.style.backgroundColor = 'red';
}
else{
//document.write('Hello ' + input.value); //This would overwrite the whole document, removing your dom.
//Instead we write it in your greeting field.
var tE = document.getElementById('greet');
tE.innerHTML = input.value;
}
return false //Prevent the form from being submitted.
}
</script>
</head>
<body>
<h1>Test</h1>
<form name = 'greeting'>
Type your name here: <input type = "Text" name="fullname" id="name"> <button onclick="return getName()">Create</button><br>
Hello <label id="greet">Hello</label>
</form>
</body>
</html>
You need to cancel the submit event which makes the form submit, alternatively you could not wrap everything inside a form element and just use normal div that way submit button wont submit.
Demo : https://jsfiddle.net/bypr0z5a/
Note reason i attach event handler in javascript and note onclick attribute on button element is because jsfiddle works weird, on ordinary page your way of calling getName() would have worked.
byId('subBtn').onclick = function (e) {
e.preventDefault();
var i = byId('name'),
inputVal = i.value;
if (inputVal == "") {
i.style.backgroundColor = "red";
} else {
byId('greet').innerText = inputVal;
i.style.backgroundColor = "#fff";
}
}
function byId(x) {
return document.getElementById(x);
}

Javascript disabling input fields

I am looking for a javascript function. which will disable the entered (filled) text field on submit. So when the user logs in back the filled text box has to remain disabled. I have tried a code, but here what happens is on clicking the sumbit the contents in the text field gets deleted.
<html>
<head>
<script>
function enableDisable(){
var disable = true;
var arglen = arguments.length;
var startIndex = 0;
var frm = document.example1;//change appropriate form name
if (arglen>0){
if (typeof arguments[0]=="boolean") {
disable=arguments[0];
if (arglen>1) startIndex=1;
}
for (var i=startIndex;i<arglen;i++){
obj = eval("frm."+arguments[i]);
if (typeof obj=="object"){
if (document.layers) {
if (disable){
obj.onfocus=new Function("this.blur()");
if (obj.type=="text") obj.onchange=new Function("this.value=this.defaultValue");
}
else {
obj.onfocus=new Function("return");
if (obj.type=="text") obj.onchange=new Function("return");
}
}
else obj.disabled=disable;
}
}
}
}
</script>
</head>
<body>
<form name="example1">
Text Field: <input type="text" name="text1">
<br>
<input type="submit" name="control1" onclick="enableDisable(this.submit,'text1','submit','select1')">
</form>
</body>
</html>
please do guide.
Make sure your submit function returns false if you don't want the page to refresh. The code you're looking for is document.getElementById('insertIdOfTextFieldHere').style.readonly = "readonly";

Categories

Resources