Get and pass array values from Javascript - javascript

Bit of background info - the developer of the system we use has left the company and I've been asked to add a few new features. Needless to say, there's no documentation and to make matters worse I'm an absolute novice so am having to learn as I go along. I'm kind of managing to do most things but have come totally stuck on this problem. For anyone kind enough to help me out, if you could really dumb any answers down that would be great. So, the problem........
HTML page that is dynamically populated with a list of items. For each item in the list there's a checkbox, and for each checkbox that's ticked I need to update a MySQL database. The code that adds the checkboxes to the page is
echo("<td class=\"tableRight\" style=\"width: 5%\"><input type=\"checkbox\" name=\"costume[]\" value=\"".$costume['id']."\" id=\"costume_".$costume['id']."\" onclick=\"tickrow(".$costume['id'].");\" /></td>");
The JavaScript file is loaded in the page head with
<script src=\"costume-list.js\" type=\"text/javascript\"></script>
The button's code that should kick off the database update is
echo("<div class=\"navContainer\" onClick=\"batch_move() \" class=\"navItem\">");
echo("<img src=\"/resource/img/icon/move.png\" border=\"0\" /><br />Batch Move Costumes");
echo("</a></div>");
And finally the JavaScript I've managed to put together is
function batch_move() {
var combo = document.getElementById("cbo_title");
var move_to = combo.options[combo.selectedIndex].text;
var move_to_id = combo.options[combo.selectedIndex].value;
if (move_to.length==0) {
alert("Please select the location you want to move the costumes to.");
return;
}
var resp_move = confirm("Are you sure you want to MOVE the selected costumes to "+move_to+" ?");
if (resp_move==true) {
alert("Lets move em");
window.open ("http://path-to-server/costume/batch-move-costume.php? loc="+move_to_id+"&items="+INeedTheArrayHere,"mywindow","menubar=1,resizable=1,width=350,height=250");
}
}
So what I want to do is first make sure that at least one checkbox is ticked and if it is then get the values of the ticked boxes into an array to pass to the called PHP form. I can manage the update code in the opened form, it's just getting the array to it.
Sorry for long post, but hope that's enough info. If there's anything else you need to know please ask and I'll supply more details. Many thanks

First off, you have my deepest sympathy. It totally sucks to get something like this mess dumped on you. This should help:
var valString = "";
var list = document.querySelectorAll('input[type ="checkbox"]');
for(var node in list) {
if(list[node].checked) {
valString += list[node].name + ',';
//you will need to add a name property when you create the html
//<input type='checkbox' name='dress'>Dress
}
}
This will create a comma-delimited string of all the checked checkbox values that you can send to the server. You can split it into an array on the server side. You will not be able to just drop an array into the GET part of the url like you have 'IneedArrayHere' above, hence the string. Also, if there are too many selections (URLS have a length limit) you will need to switch from GET to POST, which is a whole other issue.
P.S. I highly recommend that you take all those escaped double quotes and make them unescaped single quotes. That sort of thing is done by people who are used to things like SQL varieties where the difference between single and double quotes is significant, but in javascript and most (all?) sever-side languages (like php) the difference is irrelevant.

<script>
function myFunction()
{
var collection =document.getElementById("boxes").getElementsByTagName('INPUT');
var res =[];
for (var x=0; x < collection.length; x++) {
if (collection[x].type.toUpperCase()=='CHECKBOX')
var b = [collection[x].name ,collection[x].checked ] ;
res[res.length] = b;
}
alert(JSON.stringify(res));
}
</script>
<html>
<div id="boxes">
<input type="checkbox" name="1" value="1">eded</input>
<input type="checkbox" name="2" value="2">eded</input>
</div>
<input type="button" onclick="myFunction()" value="ok">
<html>
Now you can simply send the JSON to the server.

many thanks for your answer. I've plugged in your code into the JavaScript and ticked a few of the checkboxes on the form. When the code runs I get the first prompt message, but not the message box with a the value of valString ?.
It's obviously something I'm doing wrong - as I said I'm a complete novice and struggling to get to grips with this system I seem to have inherited (not through choice!)
Current code looks like this, and any pointers to my latest mistake would be much appreciated
function batch_move() {
var combo = document.getElementById("cbo_title");
var move_to = combo.options[combo.selectedIndex].text;
var move_to_id = combo.options[combo.selectedIndex].value;
if (move_to.length==0) {
alert("Please select the location you want to move the costumes to.");
return;
}
var resp_move = confirm("Are you sure you want to MOVE the selected costumes to "+move_to+" ?");
var valString = "";
var list = document.querySelectorAll('input[type ="checkbox"]');
for(var node in list) {
if(list[node].checked) {
valString += list[node].name + ',';
}
}
alert(valString);
if (resp_move==true) {
alert("Lets move em");
window.open ("http://path-to-server/costume/batch-move-costume.php?loc="+move_to_id+"&items=2,3,4,5","mywindow","menubar=1,resizable=1,width=350,height=250");
}
}

Related

Get Unsorted list list items that are added dynamically in the Controller

I am working on a project (MVC) with Razor views.
I am trying to populate a list dynamically (trying with ul/li but the select/option would also be fine) with a click on a button. The user is filling in a field, clicks a "add" button and this adds it to a ul/li structure.
When I am looking at the inspect element, I can see my values being added, my issue is to store them into Session["..."] ... Or in a hidden field so that I can iterate on them in the Controller action.
I tried several JS/Jquery answers from the net but none of them seemed to work in my case.
Here is how I populate the ul/li structure:
function addPrice() {
var priceValue = $("#PriceValue").val() // this is the input that users fill in
var ul = document.getElementById("priceListBox");
var li = document.createElement("li");
li.setAttribute('class', "list-group-item list-group-item-action"); // set the class for design
li.setAttribute('id', priceValue); // set the id to be able to remove
li.appendChild(document.createTextNode(priceValue));
ul.appendChild(li);
}
Above correctly populates a ul with list items holding the value of the user input.
This is my hidden field attempt:
<input type="hidden" name="PriceValues" value="" runat="server"/>
This is my predefined ul:
<ul class="list-group col-md-3" id="priceListBox" name="priceListBox" runat="server"> </ul>
This is the latest attempt I tried to build up my array and access these values in the controller action:
function SetItemsToArray() {
//const listItems = document.querySelectorAll('li');
//for (let i = 0; i < listItems.length; i++) {
// alert(listItems[i].textContent);
//}
var listItems = document.getElementById('priceListBox').getElementsByTagName('li'), myArray = map(listItems, getText);
function map(arraylike, fn) {
var ret = [], i = -1, len = arraylike.length;
while (++i < len) ret[i] = fn(arraylike[i]);
return ret;
}
function gettext(node) {
if (node.nodetype === 3) return node.data;
var txt = '';
if (node = node.firstchild) do {
txt += gettext(node);
} while (node = node.nextsibling);
$('#PriceValues').val(txt); // Jquery attempt
document.getelementbyid("PriceValues").value = txt; // js attempt
}
}
I would like to know:
What is the best way of achieving this?
What is the quickest way of achieving this?
Why is the current attempt not working?
Thank you all for any response, if any question ask and I will do my best to reply correctly to it.
Kind regards.
Perhaps, I'm wrong but, your input hidden, has a "name" attribute, instead of id? So shouldn't you assign an id instead of a name?
So with everyones input and several attempts i have succeeded to get the values in my controller.
#joseatchang, you are totally right, good point! Thank you for pointing that out. #Andreas, you are correct as well, with alerts i can see that it stops running at the "var listItems ..." and then it doesn't run any further. I am not able to make it work neither, i changed the getElementById syntax as well but i can't get the function to work properly but i still want to know what is wrong so if you want to elaborate on that i would appreciate it greatly.
#Scott Rickman, i tried several approaches with .textContent and others but the following worked like a charm (thanks for the splitting tip as well ;)):
This worked by putting it where i add the list items dynamically:
document.getElementById("PriceValues").value += priceValue + ";";
and in my controller:
var a = Request.Form["PriceValues"];
Thank you all for helping me, i really appreciate it!
Have a good week, kind regards!

Removing multiple input names on output formdata strings/arrays with Javascript

I figured it out using the /=on/g global value and it worked there... Thanks for the help ^_^
Any other advice is appreciated though! :D
I currently am having difficulty trying to figure out where to put the formdata.Replace to remove all =on tags after output from my form.
I have multiple check boxes, the ones that are submitted go to the next page and it displays all the inputted data. However, it also keeps the =on tag from the javascript and I can only figure how to remove one of them. I'm assuming I need to input another loop somewhere, but I am confused as to how to do that since there is an unknown number of checkboxes they can choose at one time (this output is being used on multiple pages, and there's different numbers of checkboxes per page).
This is the original script I found:
<script type="text/javascript">
<!-- HIDE FROM INCOMPATIBLE BROWSERS
if (window != top)
top.location.href=location.href
document.write("<h1>Your form has been submitted!</h1><h2>You entered the following data:</h2>");
var formData = location.search;
formData = formData.substring(1, formData.length);
while (formData.indexOf("+") != -1) {
formData = formData.replace("+", " ");
}
formData = unescape(formData);
var formArray = formData.split("&");
for (var i=0; i < formArray.length; ++i) {
document.writeln(formArray[i] + "<br />");
}
// STOP HIDING FROM INCOMPATIBLE BROWSERS -->
</script>
I added formData = formData.replace("=on", " "); in the while loop, which removes the first one but not any of the other ones. I am not sure where to put it, however.
You'll want to be careful with that code, unless you don't expect user-generated input, as you may end up replacing something that you didn't want to. There are a few JS libraries that will pull out the submitted values for you in a much safer way that you may want to research.
The issue that you're encountering is that it will only replace "=on" as many times as it replaces "+" with " ". If you add an additional while-loop, you can replace "=on" until they're all gone.
while (formData.indexOf("+") != -1) {
formData = formData.replace("+", " ");
}
while (formData.indexOf("=on") != -1) {
formData = formData.replace("=on", "");
}

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

Getting a dynamic textbox name using javascript

Please forgiving if the title is a little non-descriptive. Here is what im doing. Im making dynamic textboxes in a table using javascript. For example i add one row to the table, give the textbox a name for instance tname, i want to make each textbox unique so i add a row number to the end of it, so the textbox name is tname1, next would be tname2...etc. Now I want to create another function to loop through this table to get all of the values. Here is the code im using to get the value of the textbox below. I didnt put the for loop b/c I know that the loop works, b/c i got the correct number of rows.
txt = document.getElementById('tname' + a)
alert(txt.value)
I know that there is a function that you put around this: ('tname' + a) to let javascript know that your concatenating it together b/c i did it before just cant remember the function. If any can help, it would be very much appreciated
If you assigned the id (not name) then dirty pure JavaScript work around is:
var a = 1;
while (true) {
var id = 'tname' + a;
var txt = document.getElementById(id);
if (txt == null)
break;
alert("value of " + id + " is: " + txt.value);
a++;
}
This will keep looking for elements, until it can't find any - hope this makes sense.
You need to use ID and name. For example,
<input type="text" name="tname1" />
should be
<input type="text" name="tname1" id="tname1"/>
Use JQuery. It simplifies tasks like this:
$('input[type="text"]').map(function(){
return (this.value.length > 0) ? this.value : null;
}).get().join(',');
Working demo: http://jsfiddle.net/AlienWebguy/wLteQ/
Have you tried:
var els = document.getElementsByName(...);
// Or if you only focusing on newer browsers:
var els = document.querySelectorAll(..);
// els is now a HTMLCollection / NodeList
console.log(els[0].value);

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