How to create a delimited string dynamically with Jquery? - javascript

I'm creating a dynamic form builder where table rows can be dragged, dropped, reordered and so on. Most of this is working but when it comes to deleting rows how would I created an array or set of values that I could post back to the php script that I am using to update the database.
The way I am going to handle it is create a delimited string and post this back.
How would I go about creating the the string dynamically by appending a value like the following: 23| every time the user clicks a button? For example the if user click the button 3 times the sting would be 23|25|26| and then when they clicked save that value could be posted back to be processed.
This is the code I have for the delete function so far but its only removing the table rows and not actually generating the string.
$(".reMove").live('click', function(e) {
$(this).parent().parent().remove();
var al = $(this).attr('rel');
$("#form1").find(".del").val(al);
e.preventDefault();
sortt();
});

I would use an array:
var deletions = [];
// When deleting
deletions.push(value);
// When sending to your PHP script, create a string via Array#join
var deletionsString = deletions.join("|");
Alternately, if you like, you can just use a string and append to it:
var deletions = "";
// When deleting
deletions += "|" + value;
// When sending to your PHP script
if (deletions.length > 0) {
deletions = deletions.substring(1); // Skip the leading "|"
}
...but I prefer the array route.

I can see you've got a form here. You could dynamically create a hidden input:
var $input = $('<input/>')
.attr('type', 'hidden')
.attr.('name', 'del[]')
.val(al);
$("#form1").append($input);
After posing this form back you could simply delete all records from $_POST['del'] array.
Maybe this is the solution you're looking for?

Related

Display different text everytime you call onclick function

I have this code where I am trying to pull users from my firebase database:
function pullFromDB(){
usersRef.on('value', function(snapshot) {
function next_user(){
for (user in snapshot.val().users){
document.getElementById("users").innerHTML = user
}
}
So far it will return just one of the users as I believe it must be going through the whole users array and then putting the last name into the "users" element.
How can I iterate to the next item in the array and display a different name every time I click a button?
I have no idea what's return from DB but first try the console.log() to see what's the type of result. This will give you the answer if you are working on array or other data type.
Then if it's an array, your code:
for (user in snapshot.val().users){
document.getElementById("users").innerHTML = user
}
It iterates the whole array and .innerHTML puts user string as the last iteration. If you want to change it each time you click a button you need a variable that will contain inteager of index that's currently aplied to id="users".
Then for each click you need to increase the variable by one.
Here is an example of working with arrays in JS. http://www.w3schools.com/js/tryit.asp?filename=tryjs_array_element
Your are iterating through the whole array and only the last one is possible shown. You just need to assign an index and use it.
I don't know your remaining code, but by the given information, this should to the trick:
i = 0;
function pullFromDB(){
usersRef.on('value', function(snapshot) {
lastnames = Object.keys(snapshot.val().users); // get all keys, in your case the last names
function next_user(){
user = lastnames[i];
document.getElementById("users").innerHTML = user;
i++; // increase after click
// when you want to access more information of the user, you can do it like this (as an example)
// user_id = snapshot.val().users[user].id;
}

how to remove element from session storage array when there are lot of

I am trying to remove elements from localStorage array. all i could find is localStorage.removeItem(key);
I couldn't understand how it works because I have 2 sessionStorage. is that okay?
I have this so far
var theCart = JSON.parse(sessionStorage.getItem("ProductName")); // Retrieving
var quantity = JSON.parse(sessionStorage.getItem("QuantityOFprod"));
var prodprice = JSON.parse(sessionStorage.getItem("sum"));
ProductName, QuantityOFprod and sum is arrays.
I don't now how to form the localstorage.removeItem to select the array and then select an element inside the array. I have tried this
sessionStorage.removeItem("ProductName", JSON.stringify(namee));
namee is the a variable which contains the element I want to delete inside the specific sessionStorage array. But all it was doing is deleting everything.
You have to do this way:
read the entry
decode from JSON
remove the element
encode to JSON
update the entry
tmp = JSON.parse(sessionStorage.getItem("ProductName"));
delete tmp["key to remove"];
sessionStorage.setItem("ProductName", JSON.stringify(tmp));
Done.

Deleting everything inside table and replacing it - sqlite

Here's my problem...I have some code here:
db.transaction(function(transaction) {
var optgroup = String($('#myselect').val());
var optarray = optgroup.split(',');
for(var i=0; i<optarray.length; i++){
transaction.executeSql('INSERT INTO table1(colum1)\
VALUES(?)',[optarray[i]],
nullHandler);
}
});
This in itself isn't a problem, it works as expected. Each value from the array is stored in a different row of the table. My problem is that I want to update the table if the user selects different values from myselect.
If I do INSERT OR REPLACE then obviously, while iterating through the array it will only put the last value into a single row. Is there a way to delete everything inside the table and then store the new values? I basically want a system whereby I can get rid of the previous rows that the user made and put in new ones based on the new input a user makes.
I'm really struggling to wrap my head around how to do this.
Realised it was actually really simple, I guess I just forgot about the DELETE query >.<
db.transaction(function(transaction) {
transaction.executeSql('DELETE FROM table1 WHERE Id > 0\
',
nullHandler);
});
db.transaction(function(transaction) {
var optgroup = String($('#myselect').val());
var optarray = optgroup.split(',');
for(var i=0; i<optarray.length; i++){
transaction.executeSql('INSERT INTO table1(colum1)\
VALUES(?)',[optarray[i]],
nullHandler);
}
});
So before inserting the new values, it deletes everything inside the table first. This works fine.

jQuery parsing html into JSON

I am currently using the following code:
jQuery('#book-a-service').click(function(){
var selectedServices = jQuery('.selected').parent().parent().html();
console.log(selectedServices);
});
and that returns:
<td rowspan="3">Brakes</td>
<td class="service-title">BRAKES SET</td>
<td class="service-description"><p>Setting of front and rear brakes for proper functioning (excluding bleeding)</p></td>
<td class="service-price">R <span id="price-brakes-set">R75</span><div id="select-brakes-set" class="select-service selected"></div>
</td>
which is what i want, except i need an array of all the elements with '.selected' class in JSON.. i just want to know how i could almost parse it in a way that i only get the contents of the td tags and as for the "service-price" only the numeric value and then how would i insert those values into a json object?
Any Help Greatly Appreciated..
jQuery is not my most formidable frameworks, but this seems to do the trick.
jQuery('#book-a-service').click(function(){
var selected = jQuery('.selected');
selected.each( function() {
var children = jQuery(this).parent().parent().find('td');
var json = {};
console.log(children);
json.type = jQuery(children[0]).text();
json.title = jQuery(children[1]).text();
json.description = jQuery(children[2]).find('p').text();
json.price = jQuery(children[3]).find('span#price-brakes-set').text();
console.log(json);
console.log(JSON.stringify(json));
});
});
in action: http://jsfiddle.net/3n1gm4/DmYbb/
When various elements share the same class and you select them with $(".class"), you can iterate through all of them using:
$(".selected").each(function() {
var element = $(this); // This is the object with class "selected" being used in this iteration
var absoluteParent = $(this).parent().parent();
// Do whatever you want...
var title_element = $(".service-title", absoluteParent); // Get service-title class elements in the context provided by "absoluteParent", I mean, "inside" of absoluteParent
var title = title_element.html();
});
In the specific case of prices, I don't know exactly what is the price (probably R75?). Anyway, it should be inside a div and then select that div to obtain the price. If it is R75, then note that the "id" property should be unique for every DOM object in your HTML.
Also note that, when getting HTML, you're only getting a string, not the actual element, so it will probably not be useful for getting new values in an easy way (you won't be able to navigate through DOM elements with an ordinary string, even if it represents HTML from an actual object). Always get jQuery objects and work with them, unless you actually need the HTML.
For generating a JSON string, just create a global array and add the objects/values you need there. Then you can obtain a JSON string using var jsonText = JSON.stringify(your_array);
Consider not doing this in Javascript, as it's not useful in the majority of cases. Just send the values through POST value to a script (PHP, for example) and in the PHP you will get the actual value. The other way (PHP to Javascript) will be useful to return JSON (using json_encode($a_php_array)) and then, in Javascript, transform to a JS array using var my_array = JSON.parse(the_string_returned_by_php);.

how to construct JSON before submitting form using javascript

I have the following demo on jsFiddle. I would like to submit this form using javascript and send a JSON object back to my controller.
As you can see multiple rows can be added to the table and submitted. In my JSON data I would like to keep track of which checkboxes got clicked for which rows. So for example, based on the below screen shot:
I would like the JSON object to look like this:
{light:[{red:on}, {yellow:off},{green:on}], dark:[{red:off}, {yellow:off},{green:on}]}...
The code I came up with looks like this:
var jsonObject = {};
$('.input-row').each(function(index, row) {
var innerObject = {};
$(':checkbox', row).each(function(index, checkbox) {
innerObject[checkbox.name] = checkbox.checked ? 'on' : 'off';
});
var key = $('input[type="text"]', row).val();
jsonObject[key] = innerObject;
});
console.log(jsonObject);
// use jsonObject somehow
We're creating an empty object that will be our overall JSON object (called jsonObject).
Then we're iterating over each of the rows of inputs (I've added an input-row class to these so they can be selected easily).
For each row, we create another empty object (called innerObject), then iterate over its checkboxes. For each checkbox, we add a property to innerObject: the key is the name attribute/property of the checkbox, the value is on or off depending on the checked state. Finally, we get the value of the text input on that row to use as the key in jsonObject, and add the property to it.
Here's a working example of the above code.
The easiest way to serialize a form as JSON is to use jQuery's serializeArray()
JSON.stringify($('form').serializeArray());
You should build your own JSON string and then use jQuery.parseJSON() to do this loop all your tr elements in the table and collect the information you need.
The below code is a start for you according the html in fiddler.
var strJSON = '';
$("#blacklistgrid tr").each(function (i) {
if (i != 0)
{
var currentRow = $(this)
strJSON += "{ " + currentRow.find("input[name='shade']").val() +"[{red: currentRow.find("input[name='red']").is(":checked")} ] }";
}
});
var theJSON = jQuery.parseJSON(strJSON);
please check the correct format for JSON string and I could not check the code if it working but you can get the logic here.

Categories

Resources