i'm trying to make a "To do list" using JavaScript and it doesn't work.I tried different things but it won't work.Please help. Thanks!
document.getElementById("button").onclick = function() {
var text = document.getElementById("text").value;
var li = "<li>" + text + "</li>";
document.getElementById("list").appendChild(li);
}
<input type="text" id="text"><br><br>
<input type="button" id="button" value="Write">
<ul id="list"></ul>
Open the developer tools in your browser. Look at the console.
Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
at HTMLInputElement.document.getElementById.onclick
You are passing a string to appendChild, but the value it expects is an node such as an element.
document.getElementById("button").onclick = function() {
var text = document.getElementById("text").value;
var li = document.createElement("li");
li.appendChild(document.createTextNode(text));
document.getElementById("list").appendChild(li);
}
<input type="text" id="text"><br><br>
<input type="button" id="button" value="Write">
<ul id="list"></ul>
You can do that by using innerHTML as well, as shown below :
document.getElementById("button").onclick = function() {
var text = document.getElementById("text").value;
document.getElementById("list").innerHTML+="<li>"+text+"</li>";
}
<input type="text" id="text"><br><br>
<input type="button" id="button" value="Write">
<ul id="list"></ul>
Like Quentin said but you don't need to create node, you can directly append string with function insertAdjacentHTML
document.getElementById("button").onclick = function() {
var text = document.getElementById("text").value;
var li = "<li>" + text + "</li>";
document.getElementById("list").insertAdjacentHTML("beforeend", li);
}
<input type="text" id="text"><br><br>
<input type="button" id="button" value="Write">
<ul id="list"></ul>
<input type="text" id="text"><input type="button" id="button" value="Write">
document.getElementById("button").onclick = function() {
var node = document.createElement("li");
var textnode = document.createTextNode(document.getElementById("text").value);
node.appendChild(textnode);
document.getElementById("list").appendChild(node);
}
you can do this way
Related
There is a list of rules. The rules specify how to change the word entered. The screenshot shows an example of how the program should work. The result should be a string "aBct". I don't understand how to do this.
function pushRules(list){
var rules = "";
var w1 = document.getElementById('inputw1').value;
var w2 = document.getElementById('inputw2').value;
var w = w1+'-->'+w2;
var li = document.createElement("li");
var rule = document.createTextNode(w);
li.appendChild(rule);
}
function applyRule() {
var str = document.getElementById('inputString').value;
var numRule = document.getElementById('inputNumRules').value;
for(var i=0; i<str.length; i++){
// ...
}
}
<div class="addRules">
<h3>Add Rules</h3>
<form>
<label>w1:</label><input id="inputw1" type="text"><label> --> w2:</label><input id="inputw2" type="text">
<input type="button" value="Add" onclick="pushRules()">
</form>
<h3>Rules:</h3>
<div class="container_rules">
<ui id="list"></ui>
</div>
</div>
<h3>Input string</h3>
<input type="text" id="inputString">
<form>
<p>Apply the selected rule to the symbol at number:</p><input type="text" id="inputNumRules" value="0">
<input type="button" value="Apply rule" onclick="applyRule()">
</form>
<h3>Result</h3>
Working solution.
Just insert rules and then write the number of rule you want to apply starting from 0
var changeStringFromRules = [];
var changeStringToRules = [];
function pushRules(list){
var rules = "";
var w1 = document.getElementById('inputw1').value;
changeStringFromRules.push(w1);
var w2 = document.getElementById('inputw2').value;
changeStringToRules.push(w2);
var w = w1+'-->'+w2;
var li = document.createElement("li");
var rule = document.createTextNode(w);
li.appendChild(rule);
document.getElementById("list").appendChild(li);
}
function applyRule() {
var str = document.getElementById('inputString').value;
var numRule = parseInt(document.getElementById('inputNumRules').value);
if(str.indexOf(changeStringFromRules[numRule])!== -1){
str = str.replace(changeStringFromRules[numRule], changeStringToRules[numRule]);
}
document.getElementById("result").innerHTML = str;
}
<div class="addRules">
<h3>Add Rules</h3>
<form>
<label>w1:</label><input id="inputw1" type="text"><label> --> w2:</label><input id="inputw2" type="text">
<input type="button" value="Add" onclick="pushRules()">
</form>
<h3>Rules:</h3>
<div class="container_rules">
<ui id="list"></ui>
</div>
</div>
<h3>Input string</h3>
<input type="text" id="inputString">
<form>
<p>Apply the selected rule to the symbol at number:</p><input type="text" id="inputNumRules" value="0">
<input type="button" value="Apply rule" onclick="applyRule()">
</form>
<h3>Result</h3>
<p id="result"></p>
If I understood the question correctly, You just have to replace few characters in the input string with other characters.
You can use replace() method.
So all you have to do is,
"aBcah".replace(/ah/g,'t');
This means, replace all occurrences of ah with t in the string aBcah.
I have used a regex here and /g means to remove all(global flag), without it, it will only remove the first occurrence.
var a = "aBcah".replace(/ah/g,'t');
console.log(a);
I'm doing a task sheet. I dynamically add items to the list along with the delete button, but the button is not displayed. Why?
I can certainly write the code differently, but why does this code not work?
$(function() {
$("#button").click(function() {
var text = $("#text").val();
if(text != "")
{
var del = $("<input type='button' value='X'></input>").text();
//var item = $("<li></li>").text(text + del);
var item = $("<li></li>").text(text + del); // DONT WORK! WHY?
$("ul").append(item);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
Введите текст:
<input id="text" type="text"></input>
<input id="button" type="submit"></input>
</div>
<div class="ul">
<ul>
</ul>
</div>
With this code I want to achieve this result. But I can not. Who will help explain where I'm wrong?
<li>Some Text <input type='button' value='X'></input></li>
In your code $("<input type='button' value='X'></input>").text() returns undefined.
Try this:
$(function() {
$("#button").click(function() {
var text = $("#text").val();
if(text != "")
{
var delHTML = "<input type='button' value='X'></input>";
var item = $("<li></li>").html(text + delHTML);
$("ul").append(item);
}
});
});
Your issue stemmed from not appending the delete button to the list item reference. As it's written I can add a list item to the ul but the button's delete button element was never attached to the list item.
Second, I removed .text() from var del = $("<input type='button' value='X'></input>").text();.
Here's my full solution.
$(function() {
$("#button").click(function() {
var text = $("#text").val();
if(text != "")
{
// Creating elements
var deleteBtn = $("<input type='button' value='X'></input>");
var item = $("<li></li>").text(text);
// Appending elements
item.append(deleteBtn);
$("ul").append(item);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
Введите текст:
<input id="text" type="text"></input>
<input id="button" type="submit"></input>
</div>
<div class="ul">
<ul>
</ul>
</div>
I want to make a JavaScript function, which, after pressing a button, takes the list of checkbox elements with their content, checks all the checkboxes, creates a div element with these checkboxes and writes the result to the HTML form.
Here is my code:
function confirmDrivers() {
$('#selectedList').find('.chk').prop("checked", true);
var list = document.getElementById('selectedList').getElementsByTagName("li");
var myForm = document.getElementById('formInput');
var text = "<strong>Selected Drivers: </strong> <br><br>";
var myDiv = document.createElement("div");
myDiv.setAttribute("id","selectedInputDrivers");
myDiv.style.overflowY = "auto";
myDiv.style.maxHeight = "100px";
myDiv.style.maxWidth = "250px";
for (i = list.length - 1; i >= 0; i--) {
myDiv.innerHTML = list[i].innerHTML+'<br>'+myDiv.innerHTML;
}
$("formInput").find('.chk').prop("checked", true);
myForm.innerHTML = myDiv.outerHTML + myForm.innerHTML;
myForm.innerHTML = text + myForm.innerHTML;
}
Here is the HTML Div element with the list of checkbox elements. They also appear dynamically. Initially, Div is empty.
<div id = "selectedList" class = "col" style=" max-height:200px; max-width:500px;display: inline-block; background:#A8D9F1; overflow-y:auto">
<strong style="margin-right:10px">Selected List of Drivers</strong>
<input type="button" style="margin-right:10px" value="Remove All" name="removeAllDr" onclick="removeAllDrivers()" />
<input type="button" id="confirmD" value="Confirm" name="confirm" onclick="confirmDrivers()" />
<br><br>
</div>
And this is the HTML form, where I want my result to appear:
<form id="formInput">
</form>
The problem here is that it checks all the checkboxes in my list, but in the resulting HTML form they appear unchecked again. What is wrong with it? Thank you
Besides replacing prop() to attr() as Rik Lewis correctly recommended you can alternately put the line
$("formInput").find('.chk').prop("checked", true);
at the bottom of the function and add the # character in front the selector id like this:
function confirmDrivers() {
$('#selectedList').find('.chk').prop("checked", true);
var list = document.getElementById('selectedList').getElementsByTagName("li");
var myForm = document.getElementById('formInput');
var text = "<strong>Selected Drivers: </strong> <br><br>";
var myDiv = document.createElement("div");
myDiv.setAttribute("id","selectedInputDrivers");
myDiv.style.overflowY = "auto";
myDiv.style.maxHeight = "100px";
myDiv.style.maxWidth = "250px";
for (i = list.length - 1; i >= 0; i--) {
myDiv.innerHTML = list[i].innerHTML+'<br>'+myDiv.innerHTML;
}
myForm.innerHTML = myDiv.outerHTML + myForm.innerHTML;
myForm.innerHTML = text + myForm.innerHTML;
$("#formInput").find('.chk').prop("checked", true);
}
function confirmDrivers() {
$('#selectedList').find('.chk').prop("checked", true);
var list = document.getElementById('selectedList').getElementsByTagName("li");
var myForm = document.getElementById('formInput');
var text = "<strong>Selected Drivers: </strong> <br><br>";
var myDiv = document.createElement("div");
myDiv.setAttribute("id", "selectedInputDrivers");
myDiv.style.overflowY = "auto";
myDiv.style.maxHeight = "100px";
myDiv.style.maxWidth = "250px";
for (i = list.length - 1; i >= 0; i--) {
myDiv.innerHTML = list[i].innerHTML + '<br>' + myDiv.innerHTML;
}
myForm.innerHTML = myDiv.outerHTML + myForm.innerHTML;
myForm.innerHTML = text + myForm.innerHTML;
$("#formInput").find('.chk').prop("checked", true);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="selectedList" class="col" style=" max-height:200px; max-width:500px;display: inline-block; background:#A8D9F1; overflow-y:auto">
<strong style="margin-right:10px">Selected List of Drivers</strong>
<input type="button" style="margin-right:10px" value="Remove All" name="removeAllDr" onclick="removeAllDrivers()" />
<input type="button" id="confirmD" value="Confirm" name="confirm" onclick="confirmDrivers()" />
<br>
<br>
<ul>
<li>
<input type="checkbox" class="chk" value="test" />
</li>
<li>
<input type="checkbox" class="chk" value="test" />
</li>
<ul>
</div>
<form id="formInput">
</form>
<div id="cblist">
<input type="checkbox" value="first checkbox" id="cb1" /> <label for="cb1">first checkbox</label>
</div>
<input type="text" id="txtName" />
<input type="button" value="ok" id="btnSave" />
<script type="text/javascript">
$(document).ready(function() {
$('#btnSave').click(function() {
addCheckbox($('#txtName').val());
});
});
function addCheckbox(name) {
var container = $('#cblist');
var inputs = container.find('input');
var id = inputs.length+1;
var html = '<input type="checkbox" id="cb'+id+'" value="'+name+'" /> <label for="cb'+id+'">'+name+'</label>';
container.append($(html));
}
</script>
I currently have the following code which adds a new input box everytime the user clicks a button. Is there a way to create a button to remove the last generated input box?
var data = '<label>Temperature (K):</label><input type="number" name="temp"/>'
function addNew() {
var newContent = document.createElement('div');
newContent.innerHTML = data;
document.getElementById('target').appendChild(newContent);
}
<div id="target"></div>
<input id="add" type="button" value="Add New" onclick="addNew()" />
Push your inputs into an array:
inputs=[];
inputs.push(newContent);
//put this in your addNew function
Now you can get the last element out of that array and remove it
function remove(){
if(inputs.length>0){
elem=inputs.pop();
elem.parentNode.removeChild(elem);
}
}
Add:
<input id="remove" type="button" value="Remove last element" onclick="removeLastElem()" />
And:
function removeLastElem() {
document.getElementById('target').lastChild.remove()
}
EXAMPLE :)
Here is sample of your java-script to remove added div
First you need to create button to remove newly added row
and onclick you need to remove its parent element(last added div).
var data='<label>Temperature (K):</label><input type="number" name="temp"/> <input type="button" value="Remove" onclick="removeDiv(this)" />';
function addNew() {
var newContent = document.createElement('div');
newContent.innerHTML = data;
document.getElementById('target').appendChild(newContent);
}
function removeDiv(args){
args.parentNode.remove()
}
Sample JSBIN
Simple select last child and remove it
function removeLast(){
document.getElementById("target").lastChild.remove();
}
Here is jsfiddle
https://jsfiddle.net/aqev0pu4/
Put all the content you add to the form in a wrapping node:
var data = '<span><label>Temperature (K):</label><input type="number" name="temp"/></span>'
You can remove the last child of your "target" node:
function removeLast() {
document.getElementById("target").lastChild.remove();
}
Just keep a list of added elements :
var data = '<label>Temperature (K):</label><input type="number" name="temp"/>'
var addedList = [];
function addNew() {
var newContent = document.createElement('div');
newContent.innerHTML = data;
addedList.push(document.getElementById('target').appendChild(newContent));
}
function removeLast() {
if (addedList.length) {
document.getElementById('target').removeChild(addedList.pop());
}
}
<div id="target"></div>
<input id="add" type="button" value="Add New" onclick="addNew()" />
<input id="remove" type="button" value="Remove last added" onclick="removeLast()" />
If you just want the last element and not a list :
var data = '<label>Temperature (K):</label><input type="number" name="temp"/>'
var addedEl = null;
function addNew() {
var newContent = document.createElement('div');
newContent.innerHTML = data;
addedEl = document.getElementById('target').appendChild(newContent);
}
function removeLast() {
if (null !== addedEl) {
document.getElementById('target').removeChild(addedEl);
addedEl = null;
}
}
<div id="target"></div>
<input id="add" type="button" value="Add New" onclick="addNew()" />
<input id="remove" type="button" value="Remove last added" onclick="removeLast()" />
Keep track of last inserted input tag with a counter as sub-string of its id and remove the last one by reading the id using counter.
var inputCounter = 1;
function addNew() {
var data = '<label>Temperature (K):</label><input type="number" id="counter' + inputCounter + '" name="temp"/>';
inputCounter++;
var newContent = document.createElement('div');
newContent.innerHTML = data;
document.getElementById('target').appendChild(newContent);
}
function removeLast() {
if (inputCounter > 1) {
inputCounter--;
var last = document.getElementById("counter" + inputCounter).parentElement;
document.getElementById('target').removeChild(last);
} else {
alert("Add new inputs. No last inserted input found.")
}
}
<div id="target"></div>
<input id="add" type="button" value="Add New" onclick="addNew()" />
<input id="remove" type="button" value="Remove last added" onclick="removeLast()" />
I have an <input> tag with some HTML as the value. I want to remove any <span>s that have the class of "emphasis", but still retain the content in the <span>. I also don't want any other <span>s removed.
Example Below:
This:
<input type="hidden" name="answer" id="answer" value="<span class="emphasis"><div class="fraction_display"><span class="numer_display">21</span><span class="bar_display">/</span><span style="border-top-color: green;" class="denom_display">23</span></div></span>"
should end up as:
<input type="hidden" name="answer" id="answer" value="<div class="fraction_display"><span class="numer_display">21</span><span class="bar_display">/</span><span style="border-top-color: green;" class="denom_display">23</span></div>"`
I've tried using jQuery with this fiddle (https://jsfiddle.net/0xgx04pq/4/)...
function remove_emphasis_class (){
var content = $('#answer').val(answer);
var content_after = content.filter('span.emphasis').contents().unwrap();
$('#answer').val(content_after);
alert(content_after);
}
.emphasis {
background: orange;
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" value="2 + 5 = <span class='emphasis'>7</span>" name="answer" id="answer">
<br><br>
<button onclick="remove_emphasis_class();">Remove Class</button>
...but it's not working. content_after ends up coming back as "[object Object]" Any ideas?
Basic idea
//using string instead of reading value of the input aka var str = $(".foo").val();
var str = "2 + 5 = <span class='emphasis'>7</span>";
//convert the string to html
var temp = $("<div>").html(str);
//find the span and unwrap it
temp.find(".emphasis").contents().unwrap();
//get the html string without the span
var updated = temp.html();
//display it
console.log(updated);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
other option is to just read .text() instead of .html() and it will strip all html.
One approach in which multiple span elements with emphasis class might exist in the input value, can be like this;
var tempDir = document.createElement("div"),
inp = document.getElementById("answer"),
els2del,
content = "";
tempDir.innerHTML = inp.value;
els2del = tempDir.querySelectorAll("span[class = 'emphasis']");
for (var i = 0; i < els2del.length; i++){
content += els2del[i].innerHTML;
}
inp.value = content;
console.log(inp.value);
<input type="hidden" name="answer" id="answer" value="<span class='emphasis'><div class='fraction_display'><span class='numer_display'>21</span><span class='bar_display'>/</span><span style='border-top-color: green;' class='denom_display'>23</span></div></span>">
Try it:
function remove_emphasis_class (){
var answer = document.querySelector('#answer').value;
var div = document.createElement("div");
div.innerHTML = answer;
var selector = div.querySelector('.emphasis');
var newContent = selector.innerHTML;
div.querySelector('.emphasis').outerHTML = newContent;
console.log(div.innerHTML);
}