Storing selected row in array in JavaScript - javascript

How do we stor selected row in array in JavaScript?

You shoud be more specific in what kind of object youre using in your html (DOM) code.
exampl:
if you're using a SELECT 'resources' in a form
var fl = form.resources.length -1;
//Pull selected resources and add them to list
for (fl; fl > -1; fl--) {
if (form.resources.options[fl].selected) {
theText = form.resources.options[fl].text;
theValue = form.resources.options[fl].value);
//your code to store in an aray goes here
//...
}
}

If I got it you want to store selected table rows using javaScript.
If yes, this may help.
This piece of code is to accumulate selected ID's (dataId), based on selection of selected row's id(elemId), in an input (hidId).
I have modified my original code to maintain the records in an Array as well.
function checkSelection(hidId,elemId,dataId)
{
var arr =
str = '_' + dataId + '_';
hid = document.getElementById(hidId);
row = document.getElementById(elemId);
if(!row.classList.contains("selected")) {
row.classList.add("selected");
if(!hid.value.toString().includes(str)) {
hid.value = hid.value + str;
}
if(arr.includes(dataId))
arr.push(dataId);
}
else {
row.classList.remove("selected");
if(hid.value.toString().includes(str))
hid.value = hid.value.replace(str,"");
if(!arr.indexOf(dataId)==-1)
delete arr[arr.indexOf(dataId)];
}
alert(arr.toString());
}[I have tested it][1]
to focus more on the Array() a basic solution would be as below:
function checkSelect(hidId,elemId,dataId)
{
row = document.getElementById(elemId);
str = "";
if(document.getElementById(hidId).getAttribute("value")!=null)
str = str+document.getElementById(hidId).getAttribute("value");
str= str.replace('[','')
.replace(']','')
.replace('"','')
.replace('\\','');
document.getElementById(hidId).setAttribute("value",str);
alert(document.getElementById(hidId).value);
var arr = new Array();
if(document.getElementById(hidId).value.length!=0 ) {
arr=document.getElementById(hidId).value.split(',');
}
if(!row.classList.contains("selected")) {
row.classList.add("selected");
if(!arr.includes(dataId.toString())) {
arr.push(dataId.toString());
}
}
else {
row.classList.remove("selected");
if(arr.includes(dataId.toString()))
{
delete dataId.toString();
arr.splice(arr.indexOf(dataId.toString()),1)
}
}
if(arr.length>0) {
document.getElementById(hidId).setAttribute("value", arr.toString());
}
else
document.getElementById(hidId).setAttribute("value", "");
}

Related

jQuery do not accept new fields in HTML

I try to create a generator for lucky numbers. I did it with C# and now with JavaScript and jQuery. You can see this here. When I add new field - JQ do not see it. Just try to click on numbers in "Your field". I have as standard 7 fields and they work fine but when I add new line script do not recognise it like something useful. Could you give me some advice?
change below js code. check this working plunker
Your code:
$('.spielzahlen').on('click', function() {
var list = []
tablereset()
var item = $(this).text().split(', ')
item.forEach(function(index) {
if (index != "")
list.push(index)
})
console.log($(this).text())
list_temp = list
$(this).empty()
$('#temp').val(list)
var tds = document.getElementsByTagName("td")
list.forEach(function(index) {
var idt = index - 1
tds[idt].className = 'checked'
})
changeLen(list_temp.length)
})
Change it with below code , there is only change in initialization other code are same :
$(document).on('click','.spielzahlen', function() {
var list = []
tablereset()
var item = $(this).text().split(', ')
item.forEach(function(index) {
if (index != "")
list.push(index)
})
console.log($(this).text())
list_temp = list
$(this).empty()
$('#temp').val(list)
var tds = document.getElementsByTagName("td")
list.forEach(function(index) {
var idt = index - 1
tds[idt].className = 'checked'
})
changeLen(list_temp.length)
})

Preserve JSON arrays while sorting

I have two JSON arrays coming from an external website. I sort and merge the two arrays, decode them and then sort them from highest to lowest by ID.
Currently, when the option 'alphabetical' is clicked, ?sort=alphabetical is added onto the end of the URL and when the page has finished reloading, the JSON arrays are once again decoded and merged.
This is not my desired outcome: I do not want the JSON arrays to be decoded and merged again when the option is clicked - I simply want the already decoded and merged JSON arrays to be sorted alphabetically.
Arrays:
$homepage = array();
$homepage[]= '{
"info":{
"collection":[
{
"Name":"Charlie",
"ID":"7"
},
{
"Name":"Emma",
"ID":"9"
}
]
}
}';
$homepage[] = '{
"info":{
"collection":[
{
"Name":"Bob",
"ID":"5"
}
]
}
}';
Sorting:
$data = array();
foreach ($homepage as $homepage2) {
$tmp=json_decode($homepage2, false);
$data = array_merge($data,$tmp->info->collection);
}
if(!empty($_GET['sort']) && $_GET['sort'] == 'alphabetical') {
usort($data, function ($a, $b) {
return strcmp($a->Name, $b->Name);
});
}else{
usort($data, function ($a, $b) {
return $b->ID - $a->ID;
});
}
echo'
<select onchange="location.href = this.value;">
<option value="example.php?sort=alphabetical">Alphabetical</option>
</select>
';
foreach($data as $key) {
echo'
<a href="test.com">
<p>'.$key->ID.'</p>
<p>'.$key->Name.'</p>
</a>
';
}
You could use JavaScript for doing the sorting on click, and use PHP only for passing the JSON to it.
After you provided the HTML structure you want to display the list in, I updated this answer to use div elements for the records and p elements for the fields.
We could replace the select list, for selecting the sort order, by two buttons.
Here is the PHP code:
<?php
$homepage = array();
$homepage[]= '{
"info":{
"collection":[
{
"Name":"Charlie",
"ID":"13"
},
{
"Name":"Emma",
"ID":"9"
}
]
}
}';
$homepage[] = '{
"info":{
"collection":[
{
"Name":"Bob",
"ID":"10"
}
]
}
}';
$data = array();
foreach ($homepage as $homepage2) {
$tmp=json_decode($homepage2, false);
$data = array_merge($data,$tmp->info->collection);
}
?>
<div id="container"></div>
<button id="sort1">Alphabetical</button>
<button id="sort2">High to Low</button>
<script>
var collection = <?=json_encode($data)?>;
function populate(compareFunc) {
collection.sort(compareFunc);
var container = document.getElementById('container');
container.innerHTML = '';
collection.forEach(function (key) {
var div = document.createElement("div");
div.className = "inventory";
var span = document.createElement("span");
span.textContent = key.ID;
div.appendChild(span);
span = document.createElement("span");
span.textContent = key.Name;
div.appendChild(span);
container.appendChild(div);
});
}
var populateById = populate.bind(null, function (a, b) {
return a.ID - b.ID;
});
var populateByName = populate.bind(null, function (a, b) {
return a.Name.localeCompare(b.Name);
});
document.getElementById("sort1").addEventListener('click', populateByName);
document.getElementById("sort2").addEventListener('click', populateById);
document.addEventListener('DOMContentLoaded', populateById);
</script>
For the sample data this will result in the following JavaScript/HTML, which you can test here:
var collection = [{"Name":"Charlie","ID":"13"},{"Name":"Emma","ID":"9"},{"Name":"Bob","ID":"10"}];
function populate(compareFunc) {
collection.sort(compareFunc);
var container = document.getElementById('container');
container.innerHTML = '';
collection.forEach(function (key) {
var div = document.createElement("div");
div.className = "inventory";
var span = document.createElement("span");
span.textContent = key.ID;
div.appendChild(span);
span = document.createElement("span");
span.textContent = key.Name;
div.appendChild(span);
container.appendChild(div);
});
}
var populateById = populate.bind(null, function (a, b) {
return a.ID - b.ID;
});
var populateByName = populate.bind(null, function (a, b) {
return a.Name.localeCompare(b.Name);
});
document.getElementById("sort1").addEventListener('click', populateByName);
document.getElementById("sort2").addEventListener('click', populateById);
document.addEventListener('DOMContentLoaded', populateById);
span { margin-left: 5px }
div.inventory { border-bottom: 1px solid gray }
<div id="container"></div>
<button id="sort1">Alphabetical</button>
<button id="sort2">High to Low</button>
Note that I gave the three items different ID values than in your question, since otherwise the sort order would be the same for both ID and Name.
Using tables: alternative
There are nice JavaScript libraries which give much more features to represent data sets. Here is an example using jQuery with DataTables:
var collection = [{"Name":"Charlie","ID":"13"},{"Name":"Emma","ID":"9"},{"Name":"Bob","ID":"5"}];
function populate() {
var tbody = $('#collection>tbody');
collection.forEach(function (key) {
var row = $('<tr>');
row.append($('<td>').text(key.ID));
row.append($('<td>').text(key.Name));
tbody.append(row);
});
}
$(document).ready(function(){
populate();
$('#collection').DataTable();
});
<script src="http://code.jquery.com/jquery-1.12.3.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css">
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<table id="collection">
<thead>
<tr><th>ID</th><th>Name</th></tr>
</thead>
<tbody/>
</table>
The actual code is even smaller (not counting the included library) than a pure JavaScript solution would be with a basic table. But this has sorting up and down, filtering, pagination, nice styles, ...
There are several alternatives for this answer, so I will present a simple one:
Send the data already sorted, a default one, if the user made no choices. Then, set a function that sorts the data as needed, and redraws tables/divs/whatever you are using to present them.
As an quick example:
function sortAlpha(){
for each (stuff in data){
document.getElementById("aTable").textContent=data.StringRepresentation;
}
}
Then a function for sortSize, sortEtc, etc... in each function, you clear a div content, and populate it again. This way, you do not need to request new content from servers
getElementById documentation
There are multiple solutions in which you can achieve the desired results. If you want it pure PHP way what you can do is save the data in PHP Sessions and retrive them as need.
Here is the trick comes, You create function to get the result data in which you pass single parameter whether you want to get the data from external URL or from your saved data.
Now, in your application whenever you want to refresh the saved data call the same function with parameter denoting to refresh the saved data in SESSIONS to get replaced with data from external source.
Using this method you can reuse the data you've already fetched from external source without re-fetching it every-time you reload the function.
You can make another function which will return true for all cases in which application has to re-fetch the resultset from external source.
I've written pseudo code for you to understand what I'm trying to convey,
Function check whether we've to re-fetch the result from external source:
function hasToRefreshResult() {
if(/* CERTAIN CONDITIONS */) {
return true;
}
return false;
}
Couple of functions to get the data from local/external source according to the parameter passed:
function getResultArray($getdatafromlocal) {
if(!hasToRefreshResult() && $getdatafromlocal && array_key_exists("filertereddata",$_SESSION) && isset($_SESSION["filertereddata"])) {
$data=$_SESSION["filertereddata"];
} else {
$data=getDataFromExternalURL();
}
if(!empty($_GET['sort']) && $_GET['sort'] == 'alphabetical') {
usort($data, function ($a, $b) {
return strcmp($a->Name, $b->Name);
});
} else {
usort($data, function ($a, $b) {
return $b->ID - $a->ID;
});
}
return $data;
}
function getDataFromExternalURL() {
/*****
YOUR LOGIC TO GET DATA FROM EXTERNAL URL;
*****/
$data = array();
foreach ($homepage as $homepage2) {
$tmp=json_decode($homepage2, false);
$data = array_merge($data,$tmp->info->collection);
}
$_SESSION["filertereddata"]=$data;
return $data;
}
I hope this will solve your issue strictly using PHP.
Also don't forget the write session_start(); at the top of the PHP file you will be using this functions.

How can I get data of selected table rows?

I am using the following snippet and from this I can find the index of a row which one is selected on the basis of checkbox on every row of the table.How can I modify this snippet so that I can get the selected row data instead of index?
Please Help!!
<script>
function myfunction3() {
var element_table = document.getElementsByName('collection');
var element_tableRows = element_table[0].rows;
var selectedTr = new Array();
var data = "";
for (var i = 0; i < element_tableRows.length; i++) {
var checkerbox = element_tableRows[i].cells[0].firstChild;
if (checkerbox.checked) {
data = data+ element_tableRows[i].getAttribute("name");
}
}
var element_paragraph = document.getElementsByName('description');
element_paragraph.innerHTML = data;
alert(data);
}
</script>
as TJ says, i dont see any index in your code. but try something like this which is cleaner
$('.collection tr').each(function () {
//processing this row
$(this).find('td input:checked').each(function () {
// there is checkbox and it is checked, do your business with it
var value_of_checkbox = $(this).val(); // which is 'data' that you wanted
});
});

Accessing the MasterTableView Edit Form in Radgrid to get reference to textbox

There are two things I would like help with please. I need help accessing the currently edited existing row in the Radgrid, as as well as the index of the Edit form when trying to add a new record to the table/
function OnClientSelectedIndexChanged(sender, eventArgs) {
var item = eventArgs.get_item();
// alert(item.get_value());
grid = $find("<%= rgSecurity.ClientID %>");
var MasterTable = grid.get_masterTableView();
var selectedRows = MasterTable.get_selectedItems();
// alert("about to get to grid");
alert(selectedRows.length);
if (selectedRows.length > 1) {
for (var i = 0; i < selectedRows.length; i++) {
var row = selectedRows[i];
alert(row);
inputField = MasterTable.getCellByColumnUniqueName(row, "Item")
alert(inputField);
if (inputField) {
inputFieldValue = inputField.value
break;
}
}
}
else
{
// alert(inputField);
}
window.radopen('<%=PopLink %>?sel=' + item.get_value() + "&avail=" + inputFieldValue, "UserRoleDialog");
return false;
}
The currently edited grid row can be retrieved on the server using the EditItems[0] collection of the master table or through the e.Item argument inside the EditCommand server event handler. The index of the edited row can be fetched from the ItemIndex property of the item referenced as explained in the first sentence.

cannot set selectedIndex off select with javascript

I have this code and I keep getting undefined if I test the selectedIndex.
alert(x.selectedIndex);
So, setting it is also a problem.
Does anyone possibly see what the problem is?
//makes list off tags
function ttyps_select(data,naamsel,selectid, containerid){
if(!ttyps.length){
jQuery.each(data, function(index, itemData) {
ttyps.push( new Tagtype(itemData.tag_id, itemData.tag ));
});
}
opties = "<option value=\"-1\"></option>\n";
for(var i=0; i<ttyps.length; i++) {
var dfnkey = ttyps[i].tag_id;
var dfnsel = ttyps[i].tag;
if (dfnkey==selectid) {
opties +="<option value="+ttyps[i].tag_id+" SELECTED>"+dfnsel+"</option>\n";
} else {
opties +="<option value="+dfnkey+">"+dfnsel+"</option>\n";
}
}
$("<select name=\"" + naamsel + "\" size=\"1\" ></select>")
.html(opties)
.change(function(e){
select_tag(containerid);
})
.appendTo("#"+naamsel);
}
function select_tag(id) {
var x = $('#frmttypid'+id+' select');
var ttidx = x.val();
var tag = getTagtype(ttidx).tag;
x.selectedIndex=0;
x.blur();
if( tag ){
document.forms['frmtags']['frmtag'+id].value=tag;
}
}
thanks, Richard
$('selector') (jQuery) returns an object with array-like collection of matched DOM nodes. Your x variable is an jQuery object, not a reference to any particular <select/> element. use
x[0].selectedIndex
x[0] is a reference to the first DOM node in the jQuery object.

Categories