In the text field inputAddLabel some character is entered. When you click the Add tag button, the eventpushLabel ()is triggered. However, not every symbol should be added, but only one that is contained in listAlphabet. That is, a check must be carried out on the belonging of the added label to the alphabet.
function pushAlphabet() {
var alph = document.getElementById("inputAddAlphabet").value;
if(alph.length == 1){
var li = document.createElement("li");
li.textContent = alph + " ";
document.getElementById("listAlphabet").appendChild(li);
} else { alert('error');}
}
function pushLabel() {
var label = document.getElementById("inputAddLabel").value;
console.log("label", label);
var li = document.createElement("li");
li.textContent = label + " ";
document.getElementById("listLabels").appendChild(li);
}
<div class="alphabet">
<form>
<input id="inputAddAlphabet" type="text">
<input type="button" value="add symbol" onclick="pushAlphabet()">
</form>
<ul id="listAlphabet"></ul>
</div>
<div class="labels">
<form>
<input type="text" id="inputAddLabel">
<input type="button" value="add label" onclick="pushLabel()">
</form>
<ul id="listLabels"></ul>
</div>
Keep track of the pushed symbols (alphabet) and use them to filter the label:
var allowedLabels = [];
function pushAlphabet() {
var alph = document.getElementById("inputAddAlphabet").value;
allowedLabels.push(alph);
var li = document.createElement("li");
li.textContent = alph + " ";
document.getElementById("listAlphabet").appendChild(li);
document.getElementById("inputAddAlphabet").value = "";
}
function pushLabel() {
var label = document.getElementById("inputAddLabel").value;
console.log("label", label);
if (allowedLabels.indexOf(label) >= 0) {
var li = document.createElement("li");
li.textContent = label + " ";
document.getElementById("listLabels").appendChild(li);
document.getElementById("inputAddLabel").value = "";
} else { alert('error');}
}
<div class="alphabet">
<form>
<input id="inputAddAlphabet" type="text">
<input type="button" value="add symbol" onclick="pushAlphabet()">
</form>
<ul id="listAlphabet"></ul>
</div>
<div class="labels">
<form>
<input type="text" id="inputAddLabel">
<input type="button" value="add label" onclick="pushLabel()">
</form>
<ul id="listLabels"></ul>
</div>
Related
I'm building a small ChatHub application based on the Microsoft-Tutorial for SignalR and JavaScript.
In short: hub-messages are put in a created-on-demand (li)
For styling purposes I'm looking to add a classname to these (li), differentiating them into categories "sender" and "receiver"
Background:
Each Side of the ChatConnection has a different view. I'm still building on the logic of the texting, so this is far from flawless.
My dbo for friendstable is UserFriends, depending on which side of the friendship you are, you get a different (but mirrored) chatwindow.
Cshtml-snippet:
#foreach (var item in Model.UserFriends)
{
#if (item.FriendChatName == #User.Identity.Name)
{
<div>
<button class="open-button" onclick="openChatForm()">#item.UserChatName</button>
<div class="chat-popup" id="myChatForm" style="display:none">
<form action="/action_page.php" class="form-container">
<button type="button" class="btn cancel" onclick="closeChatForm()">#item.UserChatName</button>
<input type="hidden" id="receiverInput" value="#item.UserChatName"/>
<ul id="messagesList" class="chatmessage receiver" ></ul>
<input type="hidden" id="userInput" class="receiverInput" value="#item.FriendChatName" />
<textarea placeholder="Type message.." required style="height:32px;" id="messageInput"></textarea>
<button type="submit" asp-route-user="#User.Identity.Name" asp-route-sender="#User.Identity.Name" asp-route-receiver="#item.UserChatName" class="btn" id="sendButton">Send</button>
</form>
</div>
</div>
}
#if (item.UserChatName == #User.Identity.Name)
{
<div>
<button class="open-button" onclick="openChatForm()">#item.FriendChatName</button>
<div class="chat-popup" id="myChatForm" style="display:none">
<form action="/action_page.php" class="form-container">
<button type="button" class="btn cancel" onclick="closeChatForm()">#item.FriendChatName</button>
<input type="hidden" id="receiverInput" value="#item.FriendChatName" />
<ul id="messagesList" class="chatmessage sender" ></ul>
<input type="hidden" id="userInput" value="#item.UserChatName" />
<textarea placeholder="Type message.." required style="height:32px;" id="messageInput"></textarea>
<button type="submit" asp-area="" asp-route-user="#User.Identity.Name" asp-route-sender="#User.Identity.Name" asp-route-receiver="#item.FriendChatName" class="btn" id="sendButton">Send</button>
</form>
</div>
</div>
}
}
the ChatHub Class:
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
and the chat.js script-snippet:
var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
connection.on("ReceiveMessage", function (user, message) {
var msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
var encodedMsg = user + ": " + msg;
var li = document.createElement("li");
li.textContent = encodedMsg;
document.getElementById("messagesList").appendChild(li);
});
connection.start().catch(function (err) {
return console.error(err.toString());
});
document.getElementById("sendButton").addEventListener("click", function (event) {
var user = document.getElementById("userInput").value;
var message = document.getElementById("messageInput").value;
connection.invoke("SendMessage", user, message).catch(function (err) {
return console.error(err.toString());
});
event.preventDefault();
});
I'm trying to get this kind of thing:
if (user == reciever ) {
li.className = "receiver";
}
if (user == sender) {
li.className = "sender";
}
With the help of this snippet
var sender = document.getElementById("senderInput").value;
var receiver = document.getElementById("receiverInput").value;
But when all smoothed out i get nothing but a runtime error
this is the view in two browser windows
Anybody can help me with the building of the If in the chat.Js or has other structural notes on how i would go about styling sendermessenges and receivermessages differently, would be much appreciated!
I'm back to post my solution for this problem:
#foreach (var item in Model.User.Friends)
{
<li>
<button class="open-button" onclick="openChatForm(event, '#item.Id##ChatForm')" type="button" style="max-width:200px;">#item.UserName</button>
<div class="chat-popup" id="#item.Id##ChatForm" style="display:none; width:300px; margin-left:900px;">
<div>
<form action="/action_page.php" class="form-container" style="position:absolute">
<button class="btn cancel" onclick="closeChatForm(event, '#item.Id##ChatForm')" type="button">#item.FirstName</button>
<input type="hidden" id="receiverInput" value="#item.UserName" />
<ul id="messagesList" class="chatmessage" style="max-height:600px;"></ul>
<input type="hidden" id="senderInput" value="#User.Identity.Name" />
<textarea placeholder="Type message.." required style="height:32px;" id="messageInput"></textarea>
<button type="submit" class="btn" id="sendButton">Send</button>
</form>
</div>
</div>
<script>
</script>
</li>
}
this is the chat.js
connection.on("ReceiveMessage", function (user, message) {
var msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
var encodedMsg = user + ": " + msg;
var li = document.createElement("li");
li.className += user;
var senderForSenderForm = document.getElementById("senderInput").value;
var senderForReceiverForm = document.getElementById("receiverInput").value;
var receiverForSenderForm = document.getElementById("receiverInput").value;
var receiverForReceiverForm = document.getElementById("senderInput").value;
if (senderForSenderForm === li.className ) {
li.className += " toRight";
}
if (receiverForSenderForm === li.className) {
li.className += " toLeft";
}
if (senderForReceiverForm === li.className ) {
li.className += " toRight";
}
if (receiverForReceiverForm === li.className) {
li.className += " toLeft";
}
li.textContent = encodedMsg;
document.getElementById("messagesList").appendChild(li);
});
connection.start().catch(function (err) {
return console.error(err.toString());
});
document.getElementById("sendButton").addEventListener("click", function (event) {
var user = document.getElementById("senderInput").value;
var message = document.getElementById("messageInput").value;
connection.invoke("SendMessage", user, message).catch(function (err) {
return console.error(err.toString());
});
event.preventDefault();
});
ChatHub is still the same..
In short i refactored the chatwindow to one scope,
generated (li)'s for messages and adding a class to it to finally base the styling off this className.
Styling for all friends is Okay, Chatting atm is just possible with one friend, will update when fixed!
When I want to check my text type variable and display every char of it then it return numbers of value. And second problem when I give the variable to replace then it's undefined. Why is that, do you think?
<script>
function checkSpace(x) {
// alert(x.value.toString());
for (var charS in x.value.toString()) {
alert(charS);
}
return x.value.replace(" ", "");
}
var wykonawca = document.getElementById("informations").artist;
var tytul = document.getElementById("informations").title;
var addd = document.getElementById("tabelkaa");
var minus = document.getElementById("minus");
var plus = document.getElementById("plus");
var row = document.getElementById("effect");
plus.onclick = function (e) {
var replacedText1 = checkSpace(wykonawca);
var replacedText2 = checkSpace(tytul);
addd.innerHTML = "Artist: " + replacedText1 + "Title: " + replacedText2;
}
</script>
<body>
<div id="informationss">
<form id="informations">
<p>Wykonawca <input type ="text" name="artist"required> </p>
<p> Tytul <input type ="text" name="title" required> </p>
</form> <br/>
<input type="submit" value="-" id="minus">
<input type="submit" value="+" id="plus"> <br/>
<div id="effect"> </div>
</div>
<div id ="tabelka">
<table id="tabelkaa" border="5"></table>
</div>
</body>
charS is the index. x.value[charS] is the letter at the charS position.
Also replace(/ /g, "") will replace all spaces.
function checkSpace(x) {
// alert(x.value.toString());
for (var charS in x.value) {
alert(x.value[charS]);
}
return x.value.replace(/ /g, "");
}
var wykonawca = document.getElementById("informations").artist;
var tytul = document.getElementById("informations").title;
var addd = document.getElementById("tabelkaa");
var minus = document.getElementById("minus");
var plus = document.getElementById("plus");
var row = document.getElementById("effect");
plus.onclick = function (e) {
var replacedText1 = checkSpace(wykonawca);
var replacedText2 = checkSpace(tytul);
addd.innerHTML = "Artist: " + replacedText1 + " Title: " + replacedText2;
}
<body>
<div id="informationss">
<form id="informations">
<p>Wykonawca <input type ="text" name="artist"required> </p>
<p> Tytul <input type ="text" name="title" required> </p>
</form>
<br/>
<input type="submit" value="-" id="minus">
<input type="submit" value="+" id="plus"> <br/>
<div id="effect"></div>
</div>
<div id ="tabelka">
<table id="tabelkaa" border="5">
</table>
</div>
</body>
First of all, for..in iterates through object keys or array indexes. If you want to iterate through values, use for..of
Second, if you want to remove all spaces from string, use x.value.replace(/ /g, "") instead of x.value.replace(" ", "") wich will replace only the first space.
<body>
<div id="informationss">
<form id="informations">
<p>Wykonawca <input type ="text" name="artist"required> </p>
<p> Tytul <input type ="text" name="title" required> </p>
</form>
<br/>
<input type="submit" value="-" id="minus">
<input type="submit" value="+" id="plus"> <br/>
<div id="effect"></div>
</div>
<div id ="tabelka">
<table id="tabelkaa" border="5">
</table>
</div>
</body>
<script>
function checkSpace(x) {
// alert(x.value.toString());
for (var charS of x.value.toString()) {
alert(charS);
}
return x.value.replace(/ /g, "");
}
var wykonawca = document.getElementById("informations").artist;
var tytul = document.getElementById("informations").title;
var addd = document.getElementById("tabelkaa");
var minus = document.getElementById("minus");
var plus = document.getElementById("plus");
var row = document.getElementById("effect");
plus.onclick = function (e) {
var replacedText1 = checkSpace(wykonawca);
var replacedText2 = checkSpace(tytul);
addd.innerHTML = "Artist: " + replacedText1 + " Title: " + replacedText2;
}
</script>
I have a situation where user may insert the Total Quantity and also the Total Pass and Total Fail. I have created a function where when the number of Total Pass inserted, the loop (of entering the pass score) will run according to the iterations inputted.
However, I do not want to have the loop to display the line Enter The Score : in the JavaScript function. Therefore, I want the function to call a div from the HTML itself.
For example, I want the <div id="outputPass"><p>Enter the score : <input type="text" /></p></div> to be called in the loop function which I have created in the document.getElementById('btnPass').onclick = function().
I have inserted some comments in the code section.
document.getElementById('btnPass').onclick = function() {
var totalIterations = parseInt(document.getElementById('inputPass').value);
var output = document.getElementById('outputPass');
var quantity = document.getElementById('quantity').value;
output.innerHTML = '';
if (quantity < totalIterations) {
alert("Invalid Input, Pass Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
} else {
for (var i = 1; i <= totalIterations; i++) {
var item = document.createElement('div');
//Call <div> from HTML
item.innerHTML = "";
output.appendChild(item);
}
}
};
document.getElementById('btnFail').onclick = function() {
var totalIterations = parseInt(document.getElementById('inputFail').value);
var output = document.getElementById('outputFail');
var quantity = document.getElementById('quantity').value;
output.innerHTML = '';
if (quantity < totalIterations) {
alert("Invalid Input, Fail Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
} else {
for (var i = 1; i <= totalIterations; i++) {
var item = document.createElement('div');
//Call <div> from HTML
item.innerHTML = "";
output.appendChild(item);
}
}
};
function togglePass() {
var x = document.getElementById("passDiv");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
function toggleFail() {
var y = document.getElementById("failDiv");
if (y.style.display === "block") {
y.style.display = "none";
} else {
y.style.display = "block";
}
}
.display {
display: none;
}
<form method="post" name="form">
<p>Enter the quantity : <input type="text" id="quantity" name="quantity" /></p><br />
<input type="button" value="Pass" onclick="togglePass()">
<input type="button" value="Fail" onclick="toggleFail()">
<div id="passDiv" class="display">
<p>Enter Total Pass : <input type="text" id="inputPass" name="inputPass" /> <input type="button" value="Key In Score" id="btnPass" onclick="return validate();"></p><br />
<!--This Div-->
<div id="outputPass">
<p>Enter the score : <input type="text" /></p>
</div>
<br />
<input type="button" value="DONE">
</div>
<br />
<div id="failDiv" class="display">
<p>Enter Total Fail : <input type="text" id="inputFail" /> <input type="button" value="Key In Score" id="btnFail"></p><br />
<!--This Div-->
<div id="outputFail">
<p>Enter the score : <input type="text" /></p>
</div>
<br />
<input type="button" value="DONE">
</div>
</form>
You can make the following changes to achieve what you are looking for:
Initially we're giving an id of pscore/fscore (for pass and fail respectively) to the <p></p> tags and hiding them.
<p id="fscore" style="display:none">Enter the score : <input type="text" /></p>
We're accessing them in the javascript code in the form of variables pscore and fscore respectively. (Make sure they are declared globally outside)
var pscore = document.getElementById('pscore');
var fscore = document.getElementById('fscore');
Then in the iterations we can just make a clone of the pscore/fscore , give a class of pscore/fscore to the <p></p> tags and remove the id of pscore/score (to avoid duplicate IDs), changing the display to block and append it to the output container by using the following:
var cln = pscore.cloneNode(true);
cln.style.display="block";
cln.className ="pscore";
cln.removeAttribute("id");
item.appendChild(cln);
var cln = fscore.cloneNode(true);
cln.style.display="block";
cln.removeAttribute("id");
cln.className ="fscore";
item.appendChild(cln);
var pscore = document.getElementById('pscore');
var fscore = document.getElementById('fscore');
document.getElementById('btnPass').onclick = function() {
var totalIterations = parseInt(document.getElementById('inputPass').value);
var output = document.getElementById('outputPass');
var quantity = document.getElementById('quantity').value;
output.innerHTML = '';
if (quantity < totalIterations) {
alert("Invalid Input, Pass Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
} else {
for (var i = 1; i <= totalIterations; i++) {
var item = document.createElement('div');
//Call <div> from HTML
var cln = pscore.cloneNode(true);
cln.style.display = "block";
cln.className = "pscore";
cln.removeAttribute("id");
item.appendChild(cln);
output.appendChild(item);
}
}
};
document.getElementById('btnFail').onclick = function() {
var totalIterations = parseInt(document.getElementById('inputFail').value);
var output = document.getElementById('outputFail');
var quantity = document.getElementById('quantity').value;
output.innerHTML = '';
if (quantity < totalIterations) {
alert("Invalid Input, Fail Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
} else {
for (var i = 1; i <= totalIterations; i++) {
var item = document.createElement('div');
//Call <div> from HTML
var cln = fscore.cloneNode(true);
cln.style.display = "block";
cln.className = "fscore";
cln.removeAttribute("id");
item.appendChild(cln);
output.appendChild(item);
}
}
};
function togglePass() {
var x = document.getElementById("passDiv");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
function toggleFail() {
var y = document.getElementById("failDiv");
if (y.style.display === "block") {
y.style.display = "none";
} else {
y.style.display = "block";
}
}
.display {
display: none;
}
<form method="post" name="form">
<p>Enter the quantity : <input type="text" id="quantity" name="quantity" /></p><br />
<input type="button" value="Pass" onclick="togglePass()">
<input type="button" value="Fail" onclick="toggleFail()">
<div id="passDiv" class="display">
<p>Enter Total Pass : <input type="text" id="inputPass" name="inputPass" /> <input type="button" value="Key In Score" id="btnPass"></p><br />
<!--This Div-->
<div id="outputPass">
<p id="pscore" style="display:none">Enter the score : <input type="text" /></p>
</div>
<br />
<input type="button" value="DONE">
</div>
<br />
<div id="failDiv" class="display">
<p>Enter Total Fail : <input type="text" id="inputFail" /> <input type="button" value="Key In Score" id="btnFail"></p><br />
<!--This Div-->
<div id="outputFail">
<p id="fscore" style="display:none">Enter the score : <input type="text" /></p>
</div>
<br />
<input type="button" value="DONE">
</div>
</form>
I want to make ordered list in my little script, but I have no idea how to start it. Can you give me some advice? I think it would be more usefull than just code. The question is: how to display it on website as ordered list?
Here is my javascript and HTML:
var numnames = 0;
var names = new Array();
function SortNames() {
thename = document.theform.newname.value;
names[numnames] = thename;
names[numnames] = thename.toUpperCase();
numnames++;
names.sort();
document.theform.sorted.value=names.join("\n");
}
<h1>Sorting list</h1>
<p>Instert text</p>
<form name="theform">
<p>Text:</p>
<input type="text" name="newname" size="20">
<input type="button" name="addname" value="add" onclick="SortNames();">
<h2>Sorted txt</h2>
<textarea cols="80" rows="20" name="sorted">
text
</textarea>
</form>
You mean like this?
var numnames = 0;
var names = new Array();
function SortNames() {
thename = document.theform.newname.value;
names[numnames] = thename;
names[numnames] = thename.toUpperCase();
numnames++;
names.sort();
var ol = document.getElementById('out');
ol.innerHTML = '';
names.forEach(function(name) {
var li = document.createElement('li');
li.innerHTML = name;
ol.appendChild(li);
});
}
<h1>Sorting list</h1>
<p>Instert text</p>
<form name="theform">
<p>Text:</p>
<input type="text" name="newname" size="20">
<input type="button" name="addname" value="dodaj" onclick="SortNames();">
<h2>Sorted txt</h2>
<ol id='out'></ol>
</form>
Try this (I also simplified your code):
var names = new Array(); // you should use var names = [];
function SortNames() {
names.push(document.theform.newname.value);
names.sort();
var list = document.getElementById('list');
list.innerHTML = '<li>' + names.join('</li><li>') + '</li>';
}
<h1>Sorting list</h1>
<p>Instert text</p>
<form name="theform">
<p>Text:</p>
<input type="text" name="newname" size="20">
<input type="button" name="addname" value="dodaj" onclick="SortNames();">
<h2>Sorted txt</h2>
<ol id="list"></ol>
</form>
You can do very similar to what you've already done, but rather than write the element to a textarea write them to an ol element.
var numnames = 0;
var names = new Array();
function SortNames() {
thename = document.theform.newname.value;
names[numnames] = thename; // NOTE: this line is obsolete
names[numnames] = thename.toUpperCase();
numnames++;
names.sort();
var ol = document.getElementById("list");
ol.innerHTML = names.map(function(n){
return "<li>" + n + "</li>"
}).join("") ;
}
<h1>Sorting list</h1>
<p>Instert text</p>
<form name="theform">
<p>Text:</p>
<input type="text" name="newname" size="20">
<input type="button" name="addname" value="dodaj" onclick="SortNames();">
<h2>Sorted txt</h2>
<ol id="list"></ol>
</form>
If you wanted to keep this in a textarea just manually create the numbers
var numnames = 0;
var names = new Array();
function SortNames() {
thename = document.theform.newname.value;
names[numnames] = thename;
names[numnames] = thename.toUpperCase();
numnames++;
names.sort();
document.theform.sorted.value=names.map(function(n,i){
return (i + 1) + '. ' + n;
}).join('\n')
}
<h1>Sorting list</h1>
<p>Instert text</p>
<form name="theform">
<p>Text:</p>
<input type="text" name="newname" size="20">
<input type="button" name="addname" value="add" onclick="SortNames();">
<h2>Sorted txt</h2>
<textarea cols="80" rows="20" name="sorted">
text
</textarea>
</form>
Check this w3school it about how to build list by html
Another one thing you should check is how to work with DOM elements, simply like
document.getElementById("main").innerHtml = "<ol><li></li></ol>"
check this out js DOM
var names = new Array();
var ol = document.getElementById("sorted");
function SortNames() {
var input = document.theform.newname; // get the input
thename = input.value; // store its value
input.value = ""; // clear it's value
names.push(thename.toUpperCase()); // push it into the array in uppercase
names.sort(); // sort the array
ol.innerHTML = "";
names.forEach(function(name){
var li = document.createElement("li");
li.textContent = name;
ol.appendChild(li);
});
}
<h1>Sorting list</h1>
<p>Instert text</p>
<form name="theform">
<p>Text:</p>
<input type="text" name="newname" size="20">
<input type="button" name="addname" value="dodaj" onclick="SortNames();">
<h2>Sorted txt</h2>
<ol id="sorted"></ol>
</form>
Instead of recreating the HTML list each time, just insert the element right into the list.
var form = document.forms['theform'];
var list = document.getElementById('name-list');
var names = new Array();
function sortNames(button) {
var name = form['newname'].value.toUpperCase();
if (names.indexOf(name) > -1) {
alert('Name already present!');
return;
}
// Add the new name and sort the list.
names.push(name);
names.sort();
// Create new list item.
var listItem = document.createElement('LI');
listItem.appendChild(document.createTextNode(name));
// Insert the new list item into the list.
var newIndex = names.indexOf(name);
list.insertBefore(listItem, list.childNodes[newIndex]);
}
<h1>Sorting list</h1>
<p>Instert text with auto-sorting.</p>
<form name="theform">
<p>
Text:
<input type="text" name="newname" size="20">
<input type="button" name="addname" value="Add" onclick="sortNames(this)">
</p>
<h2>Sorted txt</h2>
<ol id="name-list"></ol>
</form>
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>