how to cross out the text when clicking checkBox javascript - 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>

Related

how to get an array post values

In my script, I have input fields which are added dynamically. I have to get all input values using php but the problem in that $_POST['poids'] give me just the first value of input array, so just the first element of the array poids. This is my code:
$(function() {
var max_fields = 10;
var $wrapper = $(".container1");
var add_button = $(".add_form_field");
$(add_button).click(function(e) {
e.preventDefault();
const vals = $("> .item input[name^=poids]", $wrapper).map(function() {
return +this.value
}).get()
const val = vals.length === 0 ? 0 : vals.reduce((a, b) => a + b);
if ($("> .item", $wrapper).length < max_fields && val < 100) {
const $form_colis = $(".item").first().clone();
$form_colis.find("input").val("");
$wrapper.append($form_colis); //add input box
} else {
var err_msg = 'limit riched';
//alert(err_msg);
window.alert(err_msg);
}
});
$wrapper.on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
})
});
<div class="container1" style="min-height:200px">
<button class="add_form_field">Add New Field ✚</button>
<form method="post" action="postForm.php">
<div class="item">
<input type="text" placeholder="Poids" name="poids[]">
<input type="text" placeholder="Longueur" name="longueurs[]">
<input type="text" placeholder="Largeur" name="largeurs[]">
<input type="text" placeholder="Hauteur" name="hauteurs[]">
Delete
</div>
<button type="submit" name="" class="btn btn-danger btn-responsive "> Send </button></center>
</a>
</form>
</div>
to get post (postForm.php):
$poids = $_POST['poids'];
foreach($poids as $poid) {
echo " -->" .$poid;
}
I hope that you undestand what I mean.
Thank you in advance
The problem is that you're appending the div with the new input fields to $wrapper, but that's outside the form. You need to put it inside the form.
Change
$wrapper.append($form_colis); //add input box
to
$('.item', $wrapper).last().after($form_colis); //add input box
I'm no PHP expert, but by just browsing the code provided, it seems you're just searching for inputs with a name value of poids.
const vals = $("> .item input[name^=poids]",$wrapper).map(function() { return +this.value }).get()
Then when you create a bew input, you do not append poids to the input name.
const $form_colis = $(".item").first().clone();
$form_colis.find("input").val("");
$wrapper.append($form_colis);
Therefore, you will only find one with your method, and that's this one:
<input type="text" placeholder="Poids" name="poids[]">
So to solve this, inside the $form_colis method, add poids to it I do believe.

how to remove textfield using dom

I have a form that permits to user to add textfield whenever he click on a button
I want to add link below every added textfield that allow to remove it
here is the script
<script>
function myFunction() {
let wrapper = document.getElementById("dynamic-question");
var input = document.createElement("input");
var del = document.createElement("button");
var div = document.createElement("div");
del.className = "del"
del.innerText = "X"
div.appendChild(input)
div.appendChild(del)
div.appendChild(document.createElement("br"));
div.appendChild(document.createElement("br"));
wrapper.appendChild(div)
}
document.getElementById("dynamic-question").addEventListener("click",function(e) {
if (e.target.className=="del") {
e.target.closest("div").remove()
}
})
</script>
and here the html code
<form id="myForm" method="POST" action="./gett">
<label for="question"> Question </label> <br>
<input class="champ" type="textarea" name="question" id="question" value=""><br><br>
<label for="ans"> Answers </label> <br>
<input type="text" name="ans1" id="ans1" value=""><br><br>
<input type="text" name="ans2" id="ans2" value=""><br><br>
<div id="dynamic-question"></div>
<button type="button" onclick="myFunction()">Add proposition</button> <br><br>
<input type="submit" value="submit">
</form>
type=button on the add
e.preventDefault() on the button to delete OR make type=button too
Use a container for the input, the BRs and the delete to get rid of them all in one go
Then call remove
function myFunction() {
let wrapper = document.getElementById("dynamic-question");
var input = document.createElement("input");
var del = document.createElement("button");
var div = document.createElement("div");
del.className = "del";
del.innerText = "X";
del.type="button";
div.appendChild(input);
div.appendChild(del);
div.appendChild(document.createElement("br"));
div.appendChild(document.createElement("br"));
wrapper.appendChild(div);
}
document.getElementById("dynamic-question").addEventListener("click",function(e) {
if (e.target.className=="del") {
e.preventDefault();
e.target.closest("div").remove();
}
})
<button type="button" onclick="myFunction()">Add</button>
<div id="dynamic-question"></div>
Individually like this - all nearest siblings needs to be removed including the BRs
function myFunction() {
let wrapper = document.getElementById("dynamic-question");
var input = document.createElement("input");
var del = document.createElement("button");
del.className = "del";
del.type="buttpn"
del.innerText = "X";
wrapper.appendChild(input);
wrapper.appendChild(del);
wrapper.appendChild(document.createElement("br"));
wrapper.appendChild(document.createElement("br"));
}
document.getElementById("dynamic-question").addEventListener("click",function(e) {
if (e.target.className=="del") {
e.preventDefault();
e.target.previousElementSibling.remove(); // remove field
e.target.nextElementSibling.remove(); // remove br
e.target.nextElementSibling.remove(); // remove br
e.target.remove();
}
})
<button type="button" onclick="myFunction()">Add</button>
<div id="dynamic-question"></div>
You can try creating link like button, you can attach a function to that button to remove like the following way:
function myFunction() {
let wrapper = document.getElementById("dynamic-question");
var form = document.getElementById("myForm");
var input = document.createElement("input");
var btn = document.createElement("button");
btn.textContent = "Remove";
btn.addEventListener('click', remove);
wrapper.appendChild(input);
wrapper.appendChild(btn);
wrapper.appendChild(document.createElement("br"));
wrapper.appendChild(document.createElement("br"));
}
function remove(){
this.previousSibling.remove(); //Remove the input
this.nextSibling.remove(); //Remove the first br
this.nextSibling.remove(); //Remove the second br
this.remove(); //Remove the button
}
button:not(:first-child) {
background:none!important;
color:inherit;
border:none;
padding:0!important;
font: inherit;
border-bottom:1px solid #444;
cursor: pointer;
}
<button type="button" onclick="myFunction()">Create</button>
<div id="dynamic-question"></div>
You can remove an element from the DOM like so:
To remove a specified element without having to specify its parent node:
function removeEl(id) {
let node = document.getElementById(id);
if (node.parentNode) {
node.parentNode.removeChild(node);
}
}
MDN Docs
So, in your case, you may want to add an ID when you are creating the textfield, so you are able to find it again and then remove it:
<script>
function myFunction() {
let wrapper = document.getElementById("dynamic-question");
var form = document.getElementById("myForm");
var input = document.createElement("input");
// Add id here
input.id = "[id_here]"
wrapper.appendChild(input)
wrapper.appendChild(document.createElement("br"));
wrapper.appendChild(document.createElement("br"));
}
</script>
Then you can call the function above like so:
removeEl("[id_here]")
Try this:
For each element you dynamically add, create a div and add a remove link with some class, then add a listener that when user clicks on the remove link, it removes the element, and the parent element (the div that the link and the input are inside).
//annonymous function
var btnAddField = document.getElementById("btnAddField");
var wrapper = document.getElementById("wrapper");
btnAddField.onclick = function() {
var div = document.createElement('div');
var input = document.createElement("input");
var removeLink = document.createElement("a");
removeLink.innerHTML = 'Remove input';
removeLink.className = "btn-remove";
div.append(input);
div.append(removeLink)
wrapper.append(div);
};
document.addEventListener('click',function(e){
if(e.target && e.target.className == 'btn-remove'){
e.target.parentNode.remove();
}
});
<div id="wrapper">
<button id="btnAddField">
Add input field
</button>
</div>

How to Disable input text on form?

I want to disable and enable input text if action add input text enable And if action edit input text disable
thanks
You can achieve this using the jQuery function prop() :
Javscript
var value = $('input').val();
if (value == null) {
$("input").prop('disabled', false);
} else {
$("input").prop('disabled', true);
}
Here is a demo: JsFiddle
Since you have not provided any snippet, I tried to replicate it witll following codes.
HTML
<input type = "text" id ="demoI">
<input type = "button" value = "Add" id = "_add">
<input type = "button" value = "Edit" id = "_edit">
JS
window.onload=function(){
var _getInput=document.getElementById("demoI");
var _getAdd = document.getElementById("_add");
var _getEdit = document.getElementById("_edit");
_getAdd.addEventListener('click',function(event){
_getInput.disabled = true;
})
_getEdit.addEventListener('click',function(event){
_getInput.disabled = false;
})
}
Check this jsFiddle
You can do this in your view.
if( $this->uri->segment(3) == 'add' ) {
<input type="text" name="myfield" disabled />
} else {
<input type="text" name="myfield" />
}
Try this code:
you can do this with java script only, there is no need to use jQuery
window.onload = function(){
var fname = document.getElementById("fname").value;
if(fname == '')
{
document.getElementById("fname").disabled = false;
}
else
{
document.getElementById("fname").disabled = true;
}
}
First Name: <input type="text" name="fname" id="fname" >

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);
}

Add and remove item in li on div without refresh page

I'm new in javascript and i need some help.
I have div tag inside a form tag who has his own submit button. Inside this div tag i have a combox with some names, and two button, one to add an item in a list (li) e other to remove it.
My problem is when i choose a name and press the add button, i call javascript function that do it, but also it refresh my html page. I don't want that.
How can i do it?
Without the form tag it works just fine.
Best regards
Here is the code:
<#s.form action="confuserpermission" theme="simple">
<#s.hidden name="saveuserpermission" value="true"/>
<div style="float: left; margin-top: 0.8em;">
<h5 style="color: #1E1E1E;">Login Utilizador:</h5>
<div class="input">
<#s.textfield name="confUserBean.name" label="Nome" cssClass="input"/>
</div>
<div style="display: inline">
<h5 style="color: #1E1E1E; display: inline">Escolhe e Adiciona uma Entidade</h5>
<select id="entityList">
<option value="default">-----Select-----</option>
<#s.iterator value="listaEntidades">
<option value="<#s.property />"><#s.property /></option>
</#s.iterator>
</select>
<button class="submit" onclick="adicionaEntidade()">Adicionar</button> <button class="submit" onclick="removaEntidade()">Remover</button>
<ul id="myList"></ul>
</div>
<script>
function isInArray(value, array) {
return array.indexOf(value) > -1 ? true : false;
}
function checkIfEntityIsAlreadyInList(entidade) {
var texts = [], lis = document.getElementById("myList").childNodes;
for (var i = 0, im = lis.length; im > i; i++) {
texts.push(lis[i].firstChild.nodeValue);
}
return isInArray(entidade, texts);
}
function adicionaEntidade()
{
var e = document.getElementById("entityList");
var entidade = e.options[e.selectedIndex].value;
if (entidade !== "default" && !checkIfEntityIsAlreadyInList(entidade)) {
var node = document.createElement("LI");
var textnode = document.createTextNode(entidade);
var fileTypeNode = document.createElement("UL");
var optionArray = ["PSX", "PS2", "XLS"];
for (var option in optionArray) {
if (optionArray.hasOwnProperty(option)) {
var pair = optionArray[option];
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.name = pair;
checkbox.value = pair;
fileTypeNode.appendChild(checkbox);
var label = document.createElement('label');
label.htmlFor = pair;
label.appendChild(document.createTextNode(pair));
fileTypeNode.appendChild(label);
//fileTypeNode.appendChild(document.createElement("br"));
}
}
node.appendChild(textnode);
node.appendChild(fileTypeNode);
document.getElementById("myList").appendChild(node);
}
}
function removaEntidade()
{
var e = document.getElementById("entityList");
var entidade = e.options[e.selectedIndex].value;
if (entidade !== "default" && checkIfEntityIsAlreadyInList(entidade)) {
var lis = document.getElementById("myList").childNodes;
var indexOfChildToRemove = -1;
for (var i = 0, im = lis.length; im > i; i++) {
if(lis[i].firstChild.nodeValue === entidade){
indexOfChildToRemove = i;
break;
}
}
if(indexOfChildToRemove>-1){
document.getElementById("myList").childNodes[indexOfChildToRemove].remove(indexOfChildToRemove);
}
}
}
</script>
<div class="submit">
<#s.submit theme="xhtml" value="Guardar"/>
</div>
Replace
<button class="submit" onclick="adicionaEntidade()">Adicionar</button> <button class="submit" onclick="removaEntidade()">Remover</button>
By
<button class="submit" onclick="adicionaEntidade()">Adicionar</button> <button class="submit" onclick="removaEntidade(); return false">Remover</button>
The thing is that this button submits the form, and so reloads the page. Making a return false into onclick function prevent form from being submitted.
You can modify the button with input type="button" as follows which will not submit the form:
<input type="button" class="submit" onclick="adicionaEntidade()" value="Adicionar"/>
<input type="button" class="submit" onclick="removaEntidade()" value="Remover"/>

Categories

Resources