Read formatted text from form through javascript - javascript

class Storedata {
constructor(name, desc, price, qty) {
this.name = name;
this.desc = desc;
this.price = price;
this.qty = qty;
}
}
var arr = [];
var btnform = document.getElementById('clicktoadd');
var btnlist = document.getElementById('clicktoshow');
var rem = document.getElementById('main');
var cancelform;
var submit;
function addData() {
var proname = document.getElementById("inpname");
var prodesc = document.getElementById("inpdesc");
var propric = document.getElementById("inpprice");
var proqty = document.getElementById("inpqty");
arr.push(new Storedata(proname.value, prodesc.value, propric.value, proqty.value));
}
function showlist() {
var data = document.createElement('table');
data.setAttribute("id", "data");
data.innerHTML += "<tr><th>Product Name</th><th>Description</th><th>Price</th><th>Quantity</th><th></th></tr>";
for (let i = 0; i < arr.length; i++) {
data.innerHTML += ("<tr><td>" + arr[i].name + "</td><td>" + arr[i].desc + "</td><td>" + arr[i].price + "</td><td>" + arr[i].qty + "</td><td><button id=\"delete" + i + "\">Delete</button></tr>");
};
document.getElementById('listing').appendChild(data);
document.getElementById('showbutton').removeAttribute("hidden", false);
}
function removelist() {
var data = document.getElementById("data");
data.parentNode.removeChild(data);
}
function addformtopage() {
var form = document.createElement('div');
form.setAttribute("id", "remform");
form.innerHTML += "<div id=\"lblname\">Product Name:</div><input id=\"inpname\" type=\"text\"><div id=\"chkname\" hidden=\"true\">Enter a Product Name</div><div id=\"lbldesc\">Description:</div><textarea id=\"inpdesc\" rows=\"10\" cols=\"35\"></textarea><div id=\"chkdesc\" hidden=\"true\">Enter a Product Desciption</div><div id=\"lblprice\">Price in INR:</div><input id=\"inpprice\" type=\"number\"><div id=\"chkprice\" hidden=\"true\">Enter a Product Price</div><div id=\"lblqty\">Quantity:</div><input id=\"inpqty\" type=\"number\"><div id=\"chkqty\" hidden=\"true\">Enter a Product Quantity</div><br><br><button id=\"submitproduct\">Submit</button><button id=\"cancel\">Cancel</button>";
document.getElementById('panel').appendChild(form);
cancelform = document.getElementById('cancel');
submit = document.getElementById('submitproduct');
}
function validateform() {
var proname = document.getElementById("inpname");
var prodesc = document.getElementById("inpdesc");
var propric = document.getElementById("inpprice");
var proqty = document.getElementById("inpqty");
var errname = document.getElementById("chkname");
var errdesc = document.getElementById("chkdesc");
var errpric = document.getElementById("chkprice");
var errqty = document.getElementById("chkqty");
if ((proname.value) && (prodesc.value) && (propric.value) && (proqty.value)) {
errname.setAttribute("hidden", true);
errdesc.setAttribute("hidden", true);
errpric.setAttribute("hidden", true);
errqty.setAttribute("hidden", true);
return true;
}
if (proname.value) {
errname.setAttribute("hidden", true);
}
if (prodesc.value) {
errdesc.setAttribute("hidden", true);
}
if (propric.value) {
errpric.setAttribute("hidden", true);
}
if (proqty.value) {
errqty.setAttribute("hidden", true);
}
if (!proname.value) {
errname.removeAttribute("hidden", false);
}
if (!prodesc.value) {
errdesc.removeAttribute("hidden", false);
}
if (!propric.value) {
errpric.removeAttribute("hidden", false);
}
if (!proqty.value) {
errqty.removeAttribute("hidden", false);
}
return false;
}
function clearform() {
var proname = document.getElementById("inpname");
var prodesc = document.getElementById("inpdesc");
var propric = document.getElementById("inpprice");
var proqty = document.getElementById("inpqty");
proname.value = null;
prodesc.value = null;
propric.value = null;
proqty.value = null;
}
function removeform() {
var elem = document.getElementById("remform");
elem.parentNode.removeChild(elem);
}
function removebuttons() {
rem.setAttribute("hidden", true);
}
function showbuttons() {
rem.removeAttribute("hidden", false);
}
btnform.addEventListener('click', function() {
addformtopage();
removebuttons();
cancelform.addEventListener('click', function() {
showbuttons();
removeform();
});
submit.addEventListener('click', function() {
if (validateform()) {
alert("Values Added");
addData();
clearform();
}
});
});
btnlist.addEventListener('click', function() {
showlist();
removebuttons();
document.getElementById('showbutton').addEventListener('click', function() {
showbuttons();
removelist();
document.getElementById('showbutton').setAttribute("hidden", "true");
});
});
#chkname,
#chkdesc,
#chkprice,
#chkqty {
color: red;
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 70%;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
<!DOCTYPE HTML>
<html>
<head>
<link href="style.css" rel="stylesheet" />
<title>
JS Form
</title>
</head>
<body>
<div id="main">
<p><button id="clicktoadd">Add Product</button> <button id="clicktoshow">Show List</button></p>
</div>
<div id="panel">
</div>
<div id="listing">
</div>
<button id="showbutton" hidden="true">< Back</button>
<script src="script.js"></script>
</body>
</html>
I want to take input in form for description of the item as formatted text. And then output it in the same format as input, but right now I am getting text separated by space where should be there. Please help..
Steps to perform
1. Run this code snippet.
2. Click on 'Add Product' button.
3. Fill the form (For testing give a description of more than one line) and Submit.
4. Click on 'Cancel' button to return.
5. Click on 'Show List' button.
6. Observe Description column.
This is output I am getting separated by spaces
This is form input I am providing

Well, you have two options. Add a <pre> tag:
for (let i = 0; i < arr.length; i++) {
data.innerHTML += ("<tr><td>" + arr[i].name + "</td><td><pre>" + arr[i].desc + "</pre></td><td>" + arr[i].price + "</td><td>" + arr[i].qty + "</td><td><button id=\"delete" + i + "\">Delete</button></tr>");
};
This way it will display the new lines and you keep your string clean.
Or you can replace the new lines with <br> this way:
for (let i = 0; i < arr.length; i++) {
data.innerHTML += ("<tr><td>" + arr[i].name + "</td><td>" + arr[i].desc.replace(/\n/g, "<br>") + "</td><td>" + arr[i].price + "</td><td>" + arr[i].qty + "</td><td><button id=\"delete" + i + "\">Delete</button></tr>");
};
Remember that the new lines are not shown by default in HTML, if you want a new line put a <br>
Test it online
Hope it helps! :)

Add this into your code:
var text = arr[i].desc;
text = text.replace(/\n/g, '<br />');
JSfiddle
See JavaScript: How to add line breaks to an HTML textarea? too.

Related

form not clearing properly after submit and also for hidden input

I'm using a parsley validator and somehow it affects my form. After submission, it won't clear all the inputs; especially hidden inputs. And when I tried to set some input value from javascript it won't show up.
I think it's because of my <form method="post" id="transaction_form">. I've tried to re-evaluate my HTML but still, it won't work properly.
$(document).ready(function () {
$("#cust_num").val(55555);
var exam_num = 12345;
var prod_num = 88998;
var prod_name = "Hello";
var prod_price = 150000;
var transactionTable = $("#transaction_table");
var trxprodcount = 0;
var subTotal = 0;
var endTotal = 0;
function clearinput() {
$("#transaction_form")[0].reset();
$("#transaction_form").parsley().reset();
//$('#get_productdata').attr('disabled', 'disabled');
$("#subtotal").html(0);
$("#endtotal").html(0);
}
clearinput();
function recount() {
subTotal = transactionTable.DataTable().column(3).data().sum();
$("#subtotal").html(subTotal);
endTotal = subTotal - (subTotal * $("#trx_disc").val()) / 100;
$("#endtotal").html(endTotal);
}
transactionTable.DataTable({
ordering: false,
responsive: true,
searching: false,
paging: false,
info: false,
fnRender: function (Obj) {
return "Rp" + Obj.Data[3];
},
drawCallback: function () {
recount();
},
});
$("#trx_disc").on("change", function () {
recount();
});
trxprodcount = trxprodcount + 1;
var exam_num = $("#cust_num").val() + "S" + trxprodcount;
var col_exam_num =
exam_num +
'<input type="hidden" name="hidden_exam_num[]" id="exam_num' +
trxprodcount +
'" class="exam_num" value="' +
exam_num +
'" />';
var col_exam_prod =
prod_num +
'<input type="hidden" name="hidden_exam_prod[]" id="exam_prod' +
trxprodcount +
'" value="' +
prod_num +
'" />';
var del_btn =
'<button type="button" name="del_prodtrx" id="' +
trxprodcount +
'" class="btn btn-danger btn-sm del_prodtrx" >Delete</button>';
transactionTable
.DataTable()
.row.add([col_exam_num, col_exam_prod, prod_name, prod_price, del_btn])
.draw()
.node();
$("#transaction_table").on("click", ".del_prodtrx", function () {
var row = $(this).parents("tr");
if ($(row).hasClass("child")) {
transactionTable.DataTable().row($(row).prev("tr")).remove().draw();
} else {
transactionTable.DataTable().row($(this).parents("tr")).remove().draw();
}
});
$("#transaction_form").on("submit", function (event) {
event.preventDefault();
if ($("#transaction_form").parsley().isValid()) {
var count_data = 0;
$(".exam_num").each(function () {
count_data = count_data + 1;
});
if (count_data > 0) {
clearinput();
} else {
$("#message").html(
'<div class="alert alert-danger">Customer/Product Kosong'
);
}
setTimeout(function () {
$("#message").html("");
}, 3000);
}
});
});
Live Example: https://jsfiddle.net/azissofyanp/9p7j1d6u/30/
And I'm very confused about it.

I cannot add the class "unread" to the append content of a certain data-id

I want to add the "unread" class to an append content with a specific data-id. The following line of code works fine in the browser console. However, when the code is run it does not add the class "unread".
var idMessage = message[message.length-1].id;
$('#visitors').find('h5[data-id=' + idMessage + ']').addClass('unread');
The goal is to add "unread" in the following line of code:
$("#visitors").append('<h5 class="' + state + '" data-id=' + visitors[i].idSession + '>' + visitors[i].visitorOnline + '</h5>');
I will provide you with a code snippet
<div id="conexion-chat">
<button id="btn-conexion-chat" onclick="initWebSocket();">Iniciar chat</button>
</div>
<div id="display-chat" style="display: none;">
<div id="visitors"></div>
<br />
<textarea id="chatRoomField" rows="10" cols="30" readonly></textarea> <br/>
<input id="sendField" value="" type="text">
<button id="sendButton" onclick="send_message();">Enviar</button>
</div>
function initWebSocket(){
$('#conexion-chat').css('display', 'none');
$('#display-chat').css('display', '');
websocket = new WebSocket("ws://localhost:8080/o/echo");
websocket.onopen = function (event) {
websocket.send(json_user());
};
websocket.onclose = function(event) {
localStorage.clear();
console.log("DESCONECTADO");
};
websocket.onmessage = function(event) {
var message = event.data;
processMessage(message);
};
websocket.onerror = function(event) {
console.log("ERROR: " + event.data);
};
}
function visitorSelected(event){
var visitorSelected = $(event.target).data('id');
localStorage.setItem('visitorSelected', visitorSelected);
websocket.send(json_messages(visitorSelected, '${email}', '${read}'));
document.getElementById("chatRoomField").innerHTML = "";
}
function processMessage(message){
if(message == '${disconnected}'){
document.getElementById("chatRoomField").innerHTML += "El patrocinador no se encuentra conectado." + "\n";
}else {
var json_message = JSON.parse(message);
var visitorSelected = localStorage.getItem('visitorSelected');
if(json_message.hasOwnProperty('message') && message.length > 0){
var message = json_message.message;
var text = "";
if('${currentUserRol}' != '${rolPreferences}'){
for(var i=0; i<message.length; i++){
text += message[i].from + ": " + message[i].message + "\n";
document.getElementById("chatRoomField").innerHTML = text;
}
}else{
if(message[message.length-1].id == visitorSelected || message[message.length-1].idTo == visitorSelected){
for(var i=0; i<message.length; i++){
text += message[i].from + ": " + message[i].message + "\n";
document.getElementById("chatRoomField").innerHTML = text;
}
}else{
var idMessage = message[message.length-1].id;
$('#visitors').find('h5[data-id=' + idMessage + ']').addClass('unread');
}
}
}
if(json_message.hasOwnProperty('visitors') && json_message.visitors.length > 0){
var visitors = json_message.visitors;
var state;
$("#visitors h5").remove();
for (var i = 0; i < visitors.length; i++) {
state = (visitors[i].idSession == visitorSelected)? "selected" : "not-selected";
$("#visitors").append('<h5 class="' + state + '" data-id=' + visitors[i].idSession + '>' + visitors[i].visitorOnline + '</h5>');
}
if(visitorSelected == null){
$("#visitors h5:first-child").attr("class", "selected");
visitorSelected = $("#visitors h5:first-child").attr("data-id");
localStorage.setItem('visitorSelected', visitorSelected);
}
}
}
}
$('#visitors').on('click', 'h5.not-selected', visitorSelected);
*Note: The entire code has not been submitted, but a code snippet.
Thanks!
Regards!

I am developing duolingo type sentence practice in javascript. I have implemented it but it needs more improvement

I have used following code to develop sentence grammar practice. When I click button then order should to maintained. I want it when button clicked then it should hide but after click on top button again show up.
Move sentence to left if there is blank. Also show button again if words clicked again.
Should using only buttons for showing at top also at bottom?
<html>
<head>
<title>
</title>
</head>
<body>
<div id="sen">I am learning JavaScript by developing a simple project.</div>
<br>
<div id="dash"></div>
<br>
<div id="container"></div>
<div id="val"></div>
<script>
var sen = document.getElementById("sen").innerHTML;
var senTrim = sen.trim();
var senArr = senTrim.split(/\s+/);
var dashElement = "";
for(i=0;i<senArr.length;i++)
{
//alert(senArr[i]);
dashElement += "<div onclick='funDiv(this.id);' style='display: inline'" + "id = dashid" + i + ">" + '__ ' + '</div>';
}
var dash = document.getElementById("dash");
dash.innerHTML = dashElement;
//var dashID = document.getElementById("dashid0").innerHTML;
//var dash1 = document.getElementById("val");
//dash1.innerHTML= dashID;
var htmlElements = "";
for (var i = 0; i < senArr.length; i++) {
htmlElements += "<button onclick='fun(this.id);' id = 'btn" + i + "'>" + senArr[i] + '</button>';
}
var container = document.getElementById("container");
container.innerHTML = htmlElements;
var ii = 0;
function funDiv(clicked){
//alert(clicked);
var inText = document.getElementById(clicked).innerHTML;
document.getElementById(clicked).innerHTML = " __ " ;
ii--;
}
function fun(clicked){
//alert(clicked);
document.getElementById(clicked).style.display = "none";
document.getElementById("dashid" + ii).innerHTML = document.getElementById(clicked).innerHTML + " ";
//document.getElementById(clicked).remove();
ii++;
}
</script>
</script>
</body>
</html>
How about something like this?
<html>
<body>
<div id="sen">I am learning JavaScript by developing a simple project.</div>
<br>
<div id="dash"></div>
<br>
<div id="container"></div>
<div id="val"></div>
<script>
var sen = document.getElementById("sen").innerHTML;
var senTrim = sen.trim();
var senArr = senTrim.split(/\s+/);
var dashElement = "";
for (var i = 0; i < senArr.length; i++) {
dashElement += `<div onclick='dashClick(this.id);' style='display: inline' id=dash${i}> __ </div>`;
}
var dash = document.getElementById("dash");
dash.innerHTML = dashElement;
var htmlElements = "";
for (var i = 0; i < senArr.length; i++) {
htmlElements += "<button onclick='btnClick(this.id);' id = 'btn" + i + "'>" + senArr[i] + '</button>';
}
var container = document.getElementById("container");
container.innerHTML = htmlElements;
var picked = 0;
function dashClick(clicked) {
const dash = document.getElementById(clicked);
dash.innerHTML = " __ ";
const btn = document.getElementById(`btn${dash.btnId}`);
btn.style.display = "inline";
picked--;
}
function btnClick(clicked) {
var btnId = clicked.replace('btn', '');
document.getElementById(clicked).style.display = "none";
const dash = document.getElementById("dash" + picked)
dash.innerHTML = document.getElementById(clicked).innerHTML + " ";
dash.btnId = btnId;
picked++;
}
</script>
</body>
</html>
I have implemented it using appendChild and remove functions of JavaScript.
<html>
<body>
<div id="sen">I am learning JavaScript by developing a simple project.</div>
<br>
<div id="dash"></div>
<br>
<div id="container"></div>
<script>
var sen = document.getElementById("sen").innerHTML;
var senTrim = sen.trim();
var senArr = senTrim.split(/\s+/);
var dashElement = "";
var btnElements = "";
for (var i = 0; i < senArr.length; i++) {
btnElements += "<button onclick='btnClick(this.id);' id = 'btn" + i + "'> " + senArr[i] + ' </button>';
}
var container = document.getElementById("container");
container.innerHTML = btnElements;
var picked = 0;
function dashClick(clicked) {
//console.log(clicked);
var buttons = document.getElementsByTagName('button');
var dash = document.getElementById("dash");
dashChild = dash.childNodes;
console.log(document.getElementById(clicked).innerText);
for(i=0;i<senArr.length;i++){
if(document.getElementById(clicked).innerText.trim() == buttons[i].innerText.trim()){
//console.log("Match");
buttons[i].style.opacity = "1";
buttons[i].style.pointerEvents = "auto";
}
}
document.getElementById(clicked).remove(); // remove clicked text
}
// Button click
function btnClick(clicked) {
var dashElement = document.createElement("div");
var text = document.getElementById(clicked).innerText;
dashElement.style.display = "inline";
dashElement.innerHTML = "<div style='display: inline' onclick='dashClick(this.id);' id=" + picked +"> " + text + " </div>"; // add text at top of button
document.getElementById("dash").appendChild(dashElement);
picked++;
document.getElementById(clicked).style.opacity = "0"; //hide button that has been clicked
document.getElementById(clicked).style.pointerEvents = "none";
}
</script>
</body>
</html>

How to assign deleted textbox id to newly generated textbox when generating dynamic textbox?

I am dynamically generating textboxes and only 5 textbox are allowed.
Now say i have generated 5 textbox with Txtopt1,Txtopt2,Txtopt3 resp..
and i am removing 2nd textbox and then again I am generating 1 new
textbox then i want to assign Txtopt2 to newly generated textbox
instead of Txtopt4.
This is my Code:
var cnt = 1;
var usedIds = [];
var maxNumberOfTextboxAllowed = 5;
function Generatetextbox() {
if (cnt <= maxNumberOfTextboxAllowed) {
var id = findAvailableId();
var OrderingField = $("<div class='OrderingField' id='OrderingField" + id + "'/>");
var LeftFloat = $("<div class='LeftFloat' id='LeftFloat" + id + "'/>");
var RightFloatCommands = $("<div class='RightFloat Commands' id='RightFloat Commands" + id + "'/>");
var upButton = $("<button value='up'>Up</button>");
var downButton = $("<button value='down'>Down</button>");
var fName = $("<input type='text' class='fieldname' id='Txtopt" + id + "' name='TxtoptNm" + id + "'/>");
var removeButton = $("<img class='remove' src='../remove.png' />");
LeftFloat.append(fName);
LeftFloat.append(removeButton);
RightFloatCommands.append(upButton);
RightFloatCommands.append(downButton);
OrderingField.append(LeftFloat);
OrderingField.append(RightFloatCommands);
$("#FieldContainer").append(OrderingField);
cnt = cnt + 1;
}
else
alert("Cant create more than 5 route points")
}
function findAvailableId() {
var i = 1;
while (usedIds[i]) i++;
usedIds[i] = true;
return i;
};
function removeId(idToRemove) {
usedIds[idToRemove] = false;
};
$(document).on('click', "img.remove", function() {
$(this).parent().parent().fadeOut(1000, function() {
if (cnt > maxNumberOfTextboxAllowed)
cnt = cnt - 2;
else if (cnt == 1)
cnt = 1;
else
cnt = cnt - 1;
var id = $(this).attr("id").substr(5);
removeId(id);
$(this).remove();
console.log(cnt)
});
});
.LeftFloat
{
float: left
}
.RightFloat
{
float: right
}
.FieldContainer
{
border: 1px solid black;
width: 400px;
height: 300px;
overflow-y: auto;
font-family:tahoma;
}
.OrderingField
{
margin: 3px;
border: 1px dashed #0da3fd;
background-color: #e8efff;
height: 50px;
}
.OrderingField div.Commands
{
width: 60px;
}
button
{
width: 60px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="FieldContainer">
</div>
<button onclick="Generatetextbox()" class="btn btn-primary" type="button">Add</button>
Keep track of the IDs you've assigned, and always take the lowest ones available.
Also, You don't need to use escape characters inside your html, you can use the single quote marks to specify strings.
Something like this should help:
var cnt = 1;
var maxNumberOfTextboxAllowed = 5;
var usedIds = [];
function findAvailableId() {
var i = 1;
while (usedIds[i]) i++;
usedIds[i] = true;
return i;
};
function removeId(idToRemove) {
usedIds[idToRemove] = false;
};
function Generatetextbox() {
if (cnt <= maxNumberOfTextboxAllowed) {
var id = findAvailableId();
var fieldWrapper = $("<div class='fieldwrapper' id='field" + id + "'/>");
var fName = $("<input type='text' class='fieldname' id='Txtopt" + id + "' name='TxtoptNm" + id + "' />");
var removeButton = $("<img class='remove' src='../remove.png' />");
fieldWrapper.append(fName);
fieldWrapper.append(removeButton);
fieldWrapper.append('<br />');
fieldWrapper.append('<br />');
$("#abc").append(fieldWrapper);
cnt = cnt + 1;
} else
alert("Cant create more than 5 textbox")
}
$(document).on('click', "img.remove", function() {
$(this).parent().fadeOut(1000, function() {
if (cnt > maxNumberOfTextboxAllowed)
cnt = cnt - 2;
else if (cnt == 1)
cnt = 1;
else
cnt = cnt - 1;
var id = $(this).attr("id").substr(5);
removeId(id);
$(this).remove();
console.log(cnt)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="abc"></div>
<button onclick="Generatetextbox()" class="btn btn-primary" type="button">Add</button>

Display the checkboxes selected into a section and the unselected into another one

I want to show the checkboxes selected into a div but actually I have a duplicate item in the list and I'm not sure how to display the unselected items into another div.
You can try out here http://jsfiddle.net/tedjimenez/7wzR5/
Here my code:
JS CODE
/* Array */
var list = new Array("valuetext000", "valuetext001", "valuetext002", "valuetext003", "valuetext004", "valuetext005", "valuetext006", "valuetext007", "valuetext008", "valuetext009", "valuetext010", "valuetext011", "valuetext012", "valuetext013", "valuetext014", "valuetext015", "valuetext016", "valuetext017")
var html = "";
/* Array will be converted to an ul list */
for (var i = 0; i < list.length; i++) {
html += "<input type='checkbox' name='boxvalue' value='" + list[i] + "' /><label>" + list[i] + "</label><br>";
}
$("#elmAv").append(html);
THE HTML CODE
<form>
<div id="elmAv"></div>
<div id="selectionResult"></div>
<script>
/* Function to display the items selected */
function showBoxes(frm) {
var checkedItems = "\n";
//For each checkbox see if it has been checked, record the value.
for (i = 0; i < frm.boxvalue.length; i++) {
if (frm.boxvalue[i].checked) {
checkedItems = checkedItems + "<li>" + frm.boxvalue[i].value + "<li>";
}
}
$("#elmAv").empty();
$("#selectionResult").append(checkedItems);
}
</script>
<input type="Button" value="Get Selection" onClick="showBoxes(this.form)" />
</form>
Simply add another div after selectionResult like this:
<div id="unselectedResult"></div>
And then update showBoxes() with the following code:
function showBoxes(frm) {
var checkedItems = "Checked:<br>\n";
var uncheckedItems = "Unchecked:<br>\n";
//For each checkbox see if it has been checked, record the value.
for (i = 0; i < frm.boxvalue.length; i++) {
if (frm.boxvalue[i].checked) {
checkedItems = checkedItems + "<li>" + frm.boxvalue[i].value + "</li>";
}
else {
uncheckedItems = uncheckedItems + "<li>" + frm.boxvalue[i].value + "</li>";
}
}
$("#elmAv").empty();
$("#selectionResult").append(checkedItems);
$('#unselectedResult').append(uncheckedItems);
}
Should get the result you're looking for.
This should work. Added another array listChecked to track checked values.
<script>
/* Array */
var list = new Array("valuetext000", "valuetext001", "valuetext002", "valuetext003", "valuetext004", "valuetext005", "valuetext006", "valuetext007", "valuetext008", "valuetext009", "valuetext010", "valuetext011", "valuetext012", "valuetext013", "valuetext014", "valuetext015", "valuetext016", "valuetext017")
var listChecked = new Array();
$(document).ready(function() {
displayUnchecked();
});
/* Array will be converted to an ul list */
function displayUnchecked()
{
var html = "";
for (var i = 0; i < list.length; i++) {
if ($.inArray(list[i], listChecked) == -1)
html += "<input type='checkbox' name='boxvalue' value='" + list[i] + "' /><label>" + list[i] + "</label><br>";
}
$("#elmAv").html(html);
}
</script>
</head>
<body>
<form>
<div id="elmAv"></div>
<div id="selectionResult"></div>
<script>
/* Display the items selected */
function showBoxes(frm) {
var checkedItems = "\n";
//alert('here');
//For each checkbox see if it has been checked, record the value.
for (i = 0; i < frm.boxvalue.length; i++) {
if (frm.boxvalue[i].checked) {
listChecked.push(frm.boxvalue[i].value);
}
}
$.each(listChecked, function (index, value)
{
checkedItems = checkedItems + "<li>" + value + "</li>";
});
//alert('here');
displayUnchecked();
//$("#elmAv").empty();
$("#selectionResult").html(checkedItems);
}
</script>
<input type="Button" value="Get Selection" onClick="showBoxes(this.form)" />
</form>
</body>

Categories

Resources