Storing data in javascript for server side processing - javascript

The problem is simple. I have something like chessboard in HTML. The fields have coordinates, stored in ID attribute (ROW|COLUMN)
Clicking on a specific field makes it marked/unmarked. What is more, selected field's row and column are stored in a <input type="hidden"/> in the form of ROW|COLUMN,ROW|COLUMN,...
For every click I have to process the value of input hidden to check whether the field is already stored, add new field, remove existing and so on. It's a little awkward.
Are there any better ways? Or maybe it is the best way?:)

You don't have to store the fields state in an input field. Better use the a global JavaScript array or manipulate the DOM and serialize it's state before sending it to the server.
Here is some sample code in a JSFiddle: http://jsfiddle.net/U2D9Q/
The important part is where the className of the columns
$td.bind("click", function(e) {
$(this).toggleClass("selected");
});
and how it's serialized when you click the button
var serialize_table = function() {
var output = new Array();
$("table tbody").children().each(function(y) {
var row = new Array();
$(this).children().each(function(x) {
row[x] = $(this).get(0).className;
});
output[y] = row;
});
return output;
}
I used jQuery to keep the code clean. Feel free to use any JS Framework you like or write native JS.

Related

Adding "values" to a texfield in jquery/js

When writing a new email, I've got a modal(pop-up window in boostrap) that shows a list of contacts. When I select (through checkboxes) a couple of contacts, the selected ones are written into a checkbox. Problem is I'm just writing the lastone I select instead of all of the selected ones.
If you need further explanation please ask. (Sorry for my english)
$("#tblContacto").on("click", ".ck", function(event){
if($(".ck").is(':checked')) {
selected_index = parseInt($(this).attr("alt").replace("Check", ""));
var contacto = JSON.parse(tbContactos[selected_index]);
$("#txtDestinatarios").val(contacto.Email);
} else {
$("#txtDestinatarios").val("");
}
});
Assuming that you want to add all E-Mails into a textfield with id txtDestinatariosthe cause of your Problem is the usage of the $("#txtDestinatarios").val(); function.
Calling val() with an argument sets (and thus overwrites) the value within the textfield. (See demo at http://api.jquery.com/val/#val2)
You would have to first retrieve the value of the textfield using code like var currentValue = $("#txtDestinatarios").val() and then add/remove the E-Mail from/to the string before setting the resulting string back as the value.
If you want to set all selected items in the checkboxes into Textfiled you can use the following line of code :-
$("#txtDestinatarios").val( $("#txtDestinatarios").val()+ ","+contacto.Email);

Naming of input elements in a dynamically created form

I am very new to Javascript, so sorry if I don't use the correct terminology.
I have a form that can dynamically grow. In other words I have buttons that will add labels and input fields to whenever the user clicks it.
At the end of the form, I'd like to have some "done" button that runs another JavaScript function.
However I notice that all of the input fields have the same id (since the function makes the id the same each time).
What is the correct way to access these variables???
Below is the function to dynamically create the fields.
I havent written the function to use the form yet.
function buildDefaultFields(){
// Define container
var chargeItem_container = document.getElementById("chargeItem_container");
// INPUT Start Date
chargeItem_container.appendChild(document.createTextNode('Start Date: '));
var startDate = document.createElement("input");
startDate.type = 'date';
startDate.name = 'startDate';
startDate.id = 'startDate';
chargeItem_container.appendChild(startDate);
chargeItem_container.appendChild(document.createElement("br"));
}
Don't use an id if its not going to uniquely identify a single element, instead use a class
startDate.className = 'startDate';
then use getElementsByClassName to retrieve them
var elements = document.getElementsByClassName ('startDate');// then loop through the elements
You should dynamically add the elements such that each element gets a new id. You could use a simple counter to append to your id names.
For example, if you keep a global var count = 0, then your first id could be 'startDate-' + count which will be startDate-0, then perform an increment on count, so that the next time you add an element, it will get the id 'startDate-' + count = startDate-1.
Hope that helps.

Getting value of field with Javascript/jQuery

This is my page:
http://bryntum.com/examples/gantt-latest/examples/basic/basic.html
I want to get current value of Start and Finish date.
( I will later implement a button, that user can press and then it will get all dates and post them somewhere). At the moment I just need somehow to get the date values.
At first the values are loaded from XML, but you can change the values manually.
I tried looking into source code, but was not able to get the field IDs etc.
So how I can access those fields with JS?
In case you're still looking for JS solution:
I couln't use Jquery, does the server support it?
By using JS, since the cells do not have an ID, you can access your fields by class name:
document.getElementsByClassName("x-grid-cell-inner ");
And than iterating trough the returned array.
Complete code:
var data = document.getElementsByClassName("x-grid-cell-inner ");
var mark = 0;
var out = "";
var patt=/\d\/\d/;
for (i in data) {
var txt = new String(data[i].innerHTML);
if (patt.test(txt)) {
if (mark == 0) {
out += "start: "+txt+" ";
mark = 1;
} else {
mark = 0;
out += "end: "+txt+" ";
}
}
}
It would be totally wrong to do this with jquery - It's an Extjs component with really good documentation.
Gnt.panel.Gantt has a getStart method:
Method to get a the current start date of the scheduler view
and a getEnd method:
Method to get a the current end date of the scheduler view
http://bryntum.com/docs/#!/api/Gnt.panel.Gantt
Edit:
Try getTaskStore, then getById on the store witch will return a Task that has a StartDate and EndDate fields.
unfortunately, there's no unique id on the divs so you can't access them. but they seem to have unique class="" values:
class="x-grid-cell x-grid-cell-startdatecolumn-1011"
class="x-grid-cell x-grid-cell-enddatecolumn-1014"
create a javascript like this
document.getElementsByClassName("x-grid-cell x-grid-cell-enddatecolumn-1014")
to access them and then you can get their start and end dates

Javascript: access server side variable client side using variable

I am attempting to:
Use JQuery to 'loop' through all elements on a page that belong to the same CSS class ("boilerplate")
Check the current value of each against it's server side assigned value (property: StaticPrefill)
Apply a special css class ("editedbackcolor") if the two values do not match (ie I'm trying to flag when someone has edited the prefilled text on textboxes)
CSS I am using:
.boilerplate = assign to all text boxes I'm trying to check on the form
.editedbackcolor = different shade I want to assign to textboxes where current value does NOT equal server side StaticPrefill value.
jQuery code I have so far is:
jQuery(document).ready(function () {
// select each element with class boilerplate and run a function against it
jQuery('.boilerplate input').each(function () {
var target1 = jQuery(this).attr("id");
matchcheck(target1);
});
});
and I'm working on the "matchcheck) function which is where I am having a problem. I'm trying to pull back the server side "StaticPrefill" property value that I can use as a comparison. I've successfully queried this by hardcoding a control name, like:
function matchcheck(){
var TSP1 = '<%= TextBox1.StaticPrefill %>';
// If current textbox value does NOT equal it's static prefill value
if (document.getElementById("Textbox1_textbox1").value != TSP1) {
alert("TB1 has differnt value than static prefill");
// change background color to flag it
jQuery("#Textbox1_textbox1").addClass("EditedBackColor");
}
}
That works fine, but I don't want to use a variable to loop through all elements instead of the hardcoded "TextBox1" in the first line of the function. I've tried different syntaxes in an attempt to put a variable between the '<%= ' and '%>' tags but the page won't compile when I try this.
Is this possible w/o using code behind of some sort? Any suggestions?
An easier approach, if I understand your question, is to bind to the change event in jQuery.
$(document).ready(function() {
jQuery('.boilerplate input').change(function() {
if(jQuery(this).val() !== jQuery(this).attr("prefill")) {
jQuery(this)removeClass('boilerplate').addClass("EditedBackColor");
}
});
});
You will also need to add an attribute called "prefill" to your input elements. You can do that server side or client side. It should look something like this:
<input class="boilerplate" id="input1" type="text" prefill="123" value="123"/>
The caveat here is that if they change it back to the original value, it will still show as changed. I'm not sure if that works for you in your scenario. They did change it per se. You would have to save off the original value as an attribute if it did not exist. The other option is to send down a model, maybe a json object, and compare to that model based on index.

ExtJS - Get array on DOM nodes in Grid, highlight()?

Here's what I'm trying to accomplish. I have a grid with entries that a user can "batch update", that is a user can select a single or multiple entries from the grid, select values from a form above the grid that they want to apply to all entries, and then submit.
What I'd like to accomplish is a highlight() done on all the changes rows. The problem I'm having is I don't know how to run a highlight() on all of the changes values at once, so I've been doing it individually. I might just be running through the loop wrong. Here's what I'm doing to update the values.
// for every property we have in our batchUpdateValues
for (var propertyName in batchUpdateValues) {
// change the selected banners attributes to match
for (var i = 0 ; i < bannersToUpdate.length ; i++)
{
// if they've selected "Name", we only want to append, not replace"
var oldName = bannersToUpdate[i].get('bannerName');
if (propertyName == 'bannerName') {
bannersToUpdate[i].set(propertyName, oldName + ' ' + batchUpdateValues['bannerName']);
} else {
bannersToUpdate[i].set(propertyName, batchUpdateValues[propertyName]);
}
var changedRowId = this.getStore().indexOf(updatedBanners[i]);
var changedRow = this.getView().getRow(changedRowId);
Ext.get(changedRow).highlight();
}
}
What's happening now is if the user selects 4 "attributes" to update form the form the highlight gets run 4 times, so I'd need to put that code outside the loop. How would I grab all of the DOM attributes for each row and then run a highlight on them()?
My first suggestion is to make sure you understand the SelectionModel. It's described in the documentation. I'd link you but I'm not sure which version you're using. Actually, what version of Ext JS are you using? The answer to this question might be different in 3.x vs. 4.x.
I'd be happy to answer in more detail but I'll need you to clarify with an example. Could you build a small table with some dummy data and then explain when you're talking about rows/columns in the model?

Categories

Resources