I want to remove an array item when generated check box checked - javascript

I made a todolist which is taking value from input and add an item from array so when the given value shown in page i want to remove an item form array whn checkbox checked.
Html part :
<input type="text" id="field" placeholder="Type name" />
<button type="submit" onclick="insertitem()">Submit</button>
<p id="para"></p>
javascript part:
var list = [];
var input;
function insertitem() {
input = document.getElementById('field').value;
list.push(input);
DisplayItem(list);
document.getElementById('field').value='';
}
function DisplayItem(data) {
var contain = document.getElementById('para');
contain.innerHTML='';
for ( var i in data) {
contain.innerHTML +="<div><input id='box' onClick='remove()' type='checkbox' /><label>" + data[i] + "</label></div>";
}
}
function remove() {
var check = document.getElementById('box').value;
for ( var i in list) {
if (list[i]!= check) {
}
}
}

Try this with pure javascript :
Array.splice and Array.indexof()
Add with checkbox inside the label tag.
And click event change with remove(this).Then easly find the label
text and match with list array.
contain.innerHTML +="<div><label><input id='box' onClick='remove(this)' type='checkbox' />" + data[i] +
"</label></div>";
}
var list = [];
var input;
function insertitem() {
input = document.getElementById('field').value;
list.push(input);
DisplayItem(list);
document.getElementById('field').value='';
}
function DisplayItem(data) {
var contain = document.getElementById('para');
contain.innerHTML='';
for ( var i in data) {
contain.innerHTML +="<div><label><input id='box' onClick='remove(this)' type='checkbox' />" + data[i] +
"</label></div>";
}
}
function remove(that) {
var check = that.parentElement.textContent;
//that.remove() if you need remove clicked box
for ( var i in list) {
if (list[i] == check) {
list.splice(list.indexOf(check),1);
}
}
console.log(list)
}
<input type="text" id="field" placeholder="Type name" />
<button type="submit" onclick="insertitem()">Submit</button>
<p id="para"></p>

var list = [];
var input;
function insertitem() {
input = document.getElementById('field').value;
list.push(input);
DisplayItem(list);
document.getElementById('field').value='';
}
function DisplayItem(data) {
var contain = document.getElementById('para');
contain.innerHTML='';
for ( var i in data) {
contain.innerHTML +="<div id='remove" + i + "'><label for='box" + i + "'><input id='box" + i + "' onClick='remove(" + i + ")' type='checkbox' />" + data[i] + "</label></div>";
}
}
function remove(targetId) {
var check = document.getElementById('box' + targetId).checked;
if(check){
console.log('Remove box' + targetId);
document.getElementById('remove' + targetId).innerHTML='';
}
}
<input type="text" id="field" placeholder="Type name" />
<button type="submit" onclick="insertitem()">Submit</button>
<p id="para"></p>
I just modified your JavaScript to pass an ID with a number to set each label apart from each other..

Related

How to send a table html as a serialize array to database?

I want to send my javascript and dynamic table to my database as a text variable.
I explained whatever I did:
I used jquery to get the values
Then I stored HTML table values in a java script array
I converted javascript array to JSON format
I sent JSON array to a php script by JQuery AJAX
But, I don’t know how to send it to database?
Here is my code:
function readTblValues() {
var TableData = '';
$('#tbTableValues').val(''); // clear textbox
$('#tblDowntimes tr').each(function(row, tr) {
TableData = TableData +
$(tr).find('td:eq(1)').text() + ' ' // downtime
+
$(tr).find('td:eq(2)').text() + ' ' // equipment
+
$(tr).find('td:eq(3)').text() + ' ' // starttime
+
$(tr).find('td:eq(4)').text() + ' ' // finishtime
+
$(tr).find('td:eq(5)').text() + ' ' // descriptio
+
'\n';
});
$('#tbTableValues').html(TableData);
}
function storeAndShowTableValues() {
var TableData;
TableData = storeTblValues();
$('#tbTableValuesArray').html('<br>JS Array: <br>' + print_r(TableData));
}
function storeTblValues() {
var TableData = new Array();
$('#tblDowntimes tr').each(function(row, tr) {
TableData[row] = {
"DOWNTIME": $(tr).find('td:eq(1)').text(),
"equipment": $(tr).find('td:eq(2)').text(),
"startdowntime": $(tr).find('td:eq(3)').text(),
"finishdowntime": $(tr).find('td:eq(4)').text(),
"description": $(tr).find('td:eq(5)').text()
}
});
TableData.shift(); // first row will be empty - so remove
return TableData;
}
function convertArrayToJSON() {
var TableData;
TableData = $.toJSON(storeTblValues());
$('#tbConvertToJSON').html('<br>JSON array: <br>' + TableData.replace(/},/g, "},<br>"));
}
function sendTblDataToServer() {
var TableData;
TableData = $.toJSON(storeTblValues());
$('#tbSendTblDataToServer').val('JSON array to send to server: <br<br>' + TableData.replace(/},/g, "},<br>"));
$.ajax({
type: "POST",
url: "test.php",
data: "pTableData=" + TableData, // post TableData to server script
success: function(msg) {
// return value stored in msg variable
$('#tbServerResponse').html('Server Response:<br><br><pre>' + msg + '</pre>');
}
});
}
function print_r(arr, level) {
var dumped_text = "";
if (!level)
level = 0;
//The padding given at the beginning of the line.
var level_padding = "";
for (var j = 0; j < level + 1; j++)
level_padding += " ";
if (typeof(arr) === 'object') { //Array/Hashes/Objects
for (var item in arr) {
var value = arr[item];
if (typeof(value) === 'object') { //If it is an array,
dumped_text += level_padding + "'" + item + "' \n";
dumped_text += print_r(value, level + 1);
} else {
dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
}
}
} else { //Stings/Chars/Numbers etc.
dumped_text = "===>" + arr + "<===(" + typeof(arr) + ")";
}
return dumped_text;
}
<html>
<head>
</head>
<body>
<form name="data-entry" method="post" action="data-entry.php">
<input id="product-name" name="product-name" />
<input id="product-quantity" name="product-quantity" />
<input name="Downtime" id="Downtime" />
<input name="equipment" id="equipment" />
<input type='time' name='startdowntime' id='startdowntime' />
<input type='time' name='finishdowntime' id='finishdowntime' />
<input type='text' name='description' id='description' />
<input type="button" value="add rows" id="btnAdd" onclick="addDowntime(this)" />
<input type="button" value="remove rows" onclick="deleteSelected()" />
<table id="tblDowntimes" class="downtime">
<tr>
<th><input type="checkbox" id="chkAll" onclick="chkAll_click(this)" /></th>
<th>downtime</th>
<th>equipment</th>
<th>start-time</th>
<th>finih-time</th>
<th>description</th>
</tr>
</table>
<input type="button" value="1. Read Table Values" name="read" onClick="readTblValues()" />
<input type="button" value="2. Store values in JS Array" name="store" onClick="storeAndShowTableValues()" />
<input type="button" value="3. Convert JS Array to json" name="convert" onClick="convertArrayToJSON()" />
<input type="button" value="4. Send json array to Server" name="send" onClick="sendTblDataToServer()" />
<div id="tbTableValues"></div>
<div id="tbTableValuesArray"></div>
<div id="tbConvertToJSON"></div>
<div id="tbServerResponse"></div>
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
and Here is my php code:
function processJSONArray() {
$tableData = stripcslashes($_POST['pTableData']);
$tableData = json_decode($tableData);
var_dump($tableData);
}
echo processJSONArray();
With aforementioned code, I manage to get the array in client side, but when I use this code that error is appeared (Undefined variable: tableData)
if(isset($_POST[‘submit’])){
echo $tableData;
}

how to serialize a form under specific conditions

Taka a look at this fiddle here this is a form where a business user enters the offered services.I sent the data with ajax and by serializing the form.
Click edit and add(plus sign) a service...in the example an input is added where it's name attribute value is of this **form= form[5]...**contrast with this with the form of the name attribute value in the other inputs...only the newly added services have the name attribute like this and the reason for that is to serialize only these...and not the others already present in the DOM/stored in the DB.
And now my problem:
Imagine that the user goes to edit the already registered services(or that he goes to edit them and add a new one)...at this case the already registered services wont'be serialized cause of the form the name attribute value has...(and the reason for this is explained above).
What can I do in this case?Sometimes I must serialize only part of a form and sometimes whole of the form.If all the inputs have name attribute value of form[1....] then along with the newly added input...already registered services will be serialized again.
Thanks for listening.
Code follows(you can see it in the fiddle too)
$('.editservices').click(function() {
//console.log(('.wrapper_servp').length);
originals_ser_input_lgth = $('.services').length;
var originals = [];
$('.show_price')
// fetch only those sections that have a sub-element with the .value
class
.filter((i, e) => $('.value', e).length === 1)
// replace content in remaining elements
.replaceWith(function(i) {
var value = $('.value', this).data('value');
var fieldsetCount = $('#serv').length;
var index = fieldsetCount + i;
return '<div class="show_price"><p id="show_p_msg">Price
visibility</p></div>' + '\
<div class="show_p_inpts">' +
'<input class="price_show"' + (value == 1 ? "checked" : "") + '
type="radio" name="form[' + index + '][price_show]" value="1">yes' +
'<input class="price_show"' + (value == 0 ? "checked" : "") + '
type="radio" name="form[' + index + '][price_show]" value="0">no' +
'</div>'; // HTML to replace the original content with
});
$('#buttons').removeClass('prfbuttons');
$('#saveserv').addClass('hideb');
$('.actionsserv').removeClass('actionsserv');
priceavail = $(".price_show:input").serializeArray();
});
$('#addser').on('click', function() {
$('#saveserv').css('border','2px solid none');
var serviceCount = $('input.services').length + 1;
var serv_inputs = '<div class="wrapper_servp"><div class="serv_contain">\n\
<input placeholder="service" class="services text" name="form[' + serviceCount + '][service]" type="text" size="40"> \n\
<input placeholder="price" class="price text" name="form[' + serviceCount + '][price]" type="text" size="3"></div>';
var p_show = '<div class="show_p">' +
'<p id="show_p_msg">Price visibility;</p>' +
'<span id="err_show_p"></span><br>' +
'</div>';
var inputs = '<div class="show_p_inpts">' +
'<input class="price_show" type="radio" name="form[' + serviceCount + '][price_show]" value="1">yes' +
'<input class="price_show" type="radio" name="form[' + serviceCount + '][price_show]" value="0">no' +
'</div></div>';
$('.wrapper_servp').last().after(serv_inputs + p_show + inputs);
$('#saveserv').removeClass('hideb');
$('#remser').css('display', 'inline');
});
$('#cancelserv').click(function(e) {
e.preventDefault();
//var newinputs = $('.wrapper_servp').length;
//var inp_remv = newinputs - originals_ser_input_lgth;
//$('.wrapper_servp').slice(-inp_remv).remove()
$('.show_p_inpts')
.filter((i, e) => $('.price_show:checked', e).length === 1)
.replaceWith(function(i) {
var value = $('.price_show:checked').attr('value');
return '<span data-value="' + value + '" class="value">' + (value == 1 ? "yes" : "no") + '</span>'
});
});
var groupHasCheckedBox = function() {
return $(this).find('input').filter(function() {
return $(this).prop('checked');
}).length === 0;
},
inputHasValue = function(index) {
return $(this).val() === '';
};
$('#saveserv').click(function(e) {
e.preventDefault();
//from here
var $radioGroups = $('.show_p_inpts');
$('.show_p_inpts').filter(groupHasCheckedBox).closest('div').addClass("error");
$('.services, .price').filter(inputHasValue).addClass("error");
//to here
var $errorInputs = $('input.services').filter((i, e) => !e.value.trim());
if ($errorInputs.length >= 1) {
console.log($errorInputs);
$('#err_message').html('you have to fill in the service'); return;
}
if ($('input.price').filter((i, e) => !e.value.trim()).length >= 1) {
$('#err_message').html('you have to fill in the price'); return;
}
});
var IDs=new Array();
$('body').on('click', '#remser', function(e){
var inputval=$('.services:visible:last').val();
if(inputval!=='')
{r= confirm('Are you sure you want to delete this service?');}
else
{
$('.wrapper_servp:visible:last').remove();
}
switch(r)
{
case true:
IDs.push($('.services:visible:last').data('service'));
$('.wrapper_servp:visible:last').addClass('btypehide');
if($('.serv_contain').length==1)$('#remser').css('display','none');
$('#saveserv').removeClass('hideb').css('border','5px solid red');
//originals.servrem=true;
break;
case false:var i;
for(i=0;i<originals.ser_input_lgth;i++)
{
$('input[name="service'+i+'"]').val(services[i].value);
$('input[name="price'+i+'"]').val(prices[i].value);//εδω set value
}
$('.services').slice(originals.ser_input_lgth).remove();
$('.price').slice(originals.ser_input_lgth).remove();
$('.openservices').addClass('hide').find('.services,.price').prop('readonly', true);
var text='<p class="show_price">Θες να φαίνεται η τιμή;<span data-value="'+ show_pr_val.value +'" class="value">' +(show_pr_val.value==1 ? 'yes':'no') + '</span></p>';
$('.show_p_inpts').remove();
$('.show_price').replaceWith(text);;
break;
}
});
I have an Idea for you. What you can do is when you show the currently existed value in you html instead of giving name attribute just give data-name attribute. I.e
Change this
<input class="services text" data-service="21" size="40" value="hair" type="text" name="service0" readonly="">
To This
<input class="services text" data-service="21" size="40" value="hair" type="text" data-value="hair" data-name="service0" readonly="">
Now when user update this values you can bind an event in jQuery like below.
$(document).ready(function(){
$(".services input").on("change paste keyup", function() {
if($(this).val() === $(this).attr("data-value"))
{
$(this).removeAttr("name");
}else{
$(this).attr("name",$(this).attr("data-name"));
}
});
});
By this way you can give name attribute to only those elements whose values are changed. Now each time you can serialize the whole form and it will only get the value of changed elements.
Don't forget to give unique class to already existed elements so you can bind on change event. Hope its clear to you.

Make a html unordered list from javascript array

I'm having a bit of a problem. I'm trying to create a unordered list from a javascript array, here is my code:
var names = [];
var nameList = "";
function submit()
{
var name = document.getElementById("enter");
var theName = name.value;
names.push(theName);
nameList += "<li>" + names + "</li>";
document.getElementById("name").innerHTML = nameList;
}
<input id="enter" type="text">
<input type="button" value="Enter name" onclick="submit()">
<br>
<br>
<div id="name"></div>
For example, if I post 2 names, Name1 and Name2 my list looks like this:
•Name1
•Name1,Name2
I want it to look like this:
•Name1
•Name2
If you look at your code, you are only creating one li with all your names as the content. What you want to do is loop over your names and create a separate li for each, right?
Change:
nameList += "<li>" + names + "</li>";
to:
nameList = "";
for (var i = 0, name; name = names[i]; i++) {
nameList += "<li>" + name + "</li>";
}
If you are interested in some better practices, you can check out a rewrite of your logic here: http://jsfiddle.net/rgthree/ccyo77ep/
function submit()
{
var name = document.getElementById("enter");
var theName = name.value;
names.push(theName);
document.getElementById("name").innerHTML = "";
for (var I = 0; I < names.length; I++)
{
nameList = "<li>" + names[I] + "</li>";
document.getElementById("name").innerHTML += nameList;
}
}
You are using an array, when you print an array JavaScript will show all the entries of the array separated by commas. You need to iterate over the array to make it work. However you can optimize this:
var names = [];
function displayUserName()
{
var theName = document.getElementById("enter").value;
if (theName == "" || theName.length == 0)
{
return false; //stop the function since the value is empty.
}
names.push(theName);
document.getElementById("name").children[0].innerHTML += "<li>"+names[names.length-1]+"</li>";
}
<input id="enter" type="text">
<input type="button" value="Enter name" onclick="displayUserName()">
<br>
<br>
<div id="name"><ul></ul></div>
In this example the HTML is syntactically correct by using the UL (or unordered list) container to which the lis (list items) are added.
document.getElementById("name").children[0].innerHTML += "<li>"+names[names.length-1]+"</li>";
This line selects the div with the name: name and its first child (the ul). It then appends the LI to the list.
As #FelixKling said: avoid using reserved or ambiguous names.
<div>
<label for="new-product">Add Product</label><br /><br /><input id="new-product" type="text"><br /><br /><button>Add</button>
</div>
<div>
<ul id="products">
</ul>
<p id="count"></p>
</div>
var products = [];
var productInput = document.getElementById("new-product");
var addButton = document.getElementsByTagName("button")[0];
var productListHtml = "";
var abc = 0;
addButton.addEventListener("click", addProduct);
function addProduct() {
products.push(productInput.value);
productList();
}
function productList() {
productListHtml += "<li>" + products[abc] + "</li>";
document.getElementById("products").innerHTML = productListHtml;
abc++;
}

Jquery insert values of text-field into list-box.?

I want to fetch value from the textfield and add to the listbox.
Here is my jquery code
JS:-
{
$('#btn_AddToList').click(function(
{
var select = document.getElementById('lst_Regions');
var region = $('#txt_RegionName').val();
if('' != region)
{
var newOption = document.createElement('option');
newOption.text = region;
newOption.value = region;
if($.browser.msie)
{
select.add(newOption);
}
else
{
select.add(newOption, null);
}
}
return false;
});
});
here is my html code
html:
<input type="text" name="region" id="txt_RegionName" /><br />
<input type="button" name="add" id="btn_AddToList" value="add" class="btn btn-success" /></br />
<select size="10" id="lst_Regions" style="width: 500px;">
</select>
question: I cannot add the value of the txt_RegionName to the lst_Region ,where i am going wrong?
Thank you.
$('#btn_AddToList').click(function () {
var val = $('#txt_RegionName').val();
$('#lst_Regions').append('<option>' + val + '</option>');
$('#txt_RegionName').val('').focus();
})
jsFiddle example
you can do this like:
$('#btn_AddToList').click(function(event)
{
var region = $('#txt_RegionName').val();
if(region && !$('#lst_Regions>option[value=' + region + ']').length){
var newOption = $('<option value="' + region + '">' + region + '</option>');
$('#lst_Regions').append(newOption);
}
//return false;
event.preventDefault();
event.stopPropagation();
});
just to let you know, you can prevent it from duplicate values using:
$('#lst_Regions>option[value=' + region + ']').length
which has to be zero, and as you see I have added that to my answer.
{
$('#btn_AddToList').click(function()
{
var select = document.getElementById('lst_Regions');
var region = $('#txt_RegionName').val();
if ('' != region) {
$(document.createElement('option')).text(region).val(region).appendTo(select);
}
return false;
});
};

Build a array of div's id using each DIV inside section

I'm trying to get the ID of each DIV inside this HTML code
<section id="choices">
<div id="talla_choice_24" style="">
...
</div>
<div id="color_choice_25" style="">
...
</div>
<div id="sport_choice_26" style="">
...
</div>
<button type="button" class="create-variation" id="create-variation" style="">Crear variaciones</button>
<section id="variations_holder" style="display: none"></section>
</section>
So I made this:
function getDivId(div) {
var inputValues = [];
$("#" + div + ' > div').each(function() {
inputValues.push($(this).val());
})
return inputValues;
}
And I call here:
$('#choices').on("click", "#create-variation", function(e) {
var parent_id = $(this).closest("section").attr("id");
var element = getDivId(parent_id);
iterateChoices("", element[0], element.slice(1), 0);
});
I need to build something like this:
var element = new Array($('#talla_choice_24 input:text'), $('#color_choice_25 input:text'), $('#sport_choice_26 input:text'));
But I get this error:
Uncaught TypeError: Object has no method 'each'
What is wrong?
UPDATE
This is the code for iterateChoices() function:
function iterateChoices(row, element, choices, counter) {
if ($.isArray(choices) && choices.length > 0) {
element.each(function(index, item) {
if (counter == 0)
row = '<input type="text" required="required" value="" name="pupc[]" /><input type="text" required="required" value="" name="pprice[]" /><input type="text" required="required" value="" name="pqty[]" />';
iterateChoices(row + '<input value="' + item.value + '">', choices[0], choices.slice(1), counter + 1);
});
} else {
html_temp = "";
$.each(element, function(index, item) {
html_temp += row + '<input value="' + item.value + '"><br>';
});
html += html_temp;
}
}
I also made some changes at this code:
function getDivId(div) {
var inputValues = [];
$("#" + div + ' > div').each(function() {
inputValues.push("#" + $(this).attr('id') + ' input:text');
});
return inputValues;
}
And now the error change to this:
Uncaught TypeError: Object #talla_choice_24 input:text has no method 'each'
UPDATE 2
I still continue change getDivId() function to build a array like this:
var element = new Array($('#talla_choice_24 input:text'), $('#color_choice_25 input:text'), $('#number_choice_23 input:text'), $('#sport_choice_23 input:text'));
But can't get it since array values are constructed as strings, see below:
function getDivId(div) {
var inputValues = [];
$("#" + div + ' > div').each(function() {
inputValues.push('$("#' + $(this).attr('id') + ' input:text")');
});
return inputValues;
}
I'm getting:
("$('#talla_choice_24 input:text')", "$('#color_choice_25 input:text')")
I think there is the problem
You are using the val method on a div element, which just returns an empty string. There is no each method on a string.
You don't need the id of each div to get the input elements inside them. This will get you the inputs in a single jQuery object:
var element = $(this).closest("section").find("> div input:text");
If you really need an array of separate jQuery objects, you can then do this:
element = element.map(function(){ return $(this); }).get();
var arr = [];
$("#create-variation").on('click', function(){
$("#choices > div").each(function(a,b){
arr.push($(this).text());
});
});
After some headaches I realized how to fix the (my) error, here is the solution to all the problems:
function getDivId(div) {
var inputValues = [];
$("#" + div + ' > div').each(function() {
inputValues.push($("#" + $(this).attr('id') + " input:text"));
});
return inputValues;
}

Categories

Resources