For this project, I want to change the logic written in jquery with that in js vanilla.
My code looks like this
Based on the information from the input using the event keydown,
I call a function through which I do a search in api.
var selectedUsers = [] //empty array
$('#userSearchTextbox').keydown((event)=>{
var textBox = $(event.target);
var value = textBox.val();
//Function which search in api
searchUsers(value);
});
//Search in array function
function searchUsers(searchTerm){
$.get("/api/users",{search:searchTerm},results =>{
outputSelectableUsers(results,$('.resultsContainer'));
});
}
After I call another function outputSelectableUsers
which will call 2 functions one that displays the data in HTML and one that creates an array of values.
function outputSelectableUsers(results,container){
results.forEach(results => {
//Call function which will render the html
var html =createUserHtml(results,false);
/*
Here is the problem, as seen using jquery element variable selects html variable which render function
*/
var element = $(html);
/*
with jquery, I managed to select the variable and assign it a click event that when I click it calls the function that adapts the array with data
from each API call
*/
element.click(()=>userSelected(results))
//append content to the html selector
container.append(element);
});
}
//Function which will update the array
function userSelected(user){
selectedUsers.push(user);
}
This is what the visible result looks like
And when I click on one of the cards, the area adapts to the user's values.
values that I take from the array and enter them in the database.
I managed to convert everything to js using fetch instead of ajax jquery and changed the selectors and events with vanilla js code.
But the problem is I couldn't find a way to change this piece of code.
var html =createUserHtml(results,false);
var element = $(html);
console.log(element)
element.click(()=>userSelected(results))
container.append(element);
at consol.log (element) I observed asata in the console.
The question is could I choose the element with js vanilla and get the same result as in the jquery version. To use Js Vanilla code instead of
var element = $(html);
element.click(()=>userSelected(results))
let users_id = results._id;
let html = createUserHtml(results,users_id ,false);
container.insertAdjacentHTML('beforeend',html);
//Identify each element by a unique selector
document.querySelector(`[data-selectorTab ="${results._id}"]`).addEventListener('click',()=>{
userSelected(res)
})
I solve this by adding a data attribute to dinamically generated elements,using this data atribute I can make a individual selector for each user.
Related
I have a php page which calls a javascript function to populate it.
The page is a list of users each with their own form, the form id has the id appended to its name to allow edit, delete etc on each user.
The form is is the shape of an html page that is in theory sucked in for each record.
I am using jquery each() to iterate over the records, then in theory the html page should be sucked in and populated for each record. I have tried for loop also.
The code below produces the correct number of forms but empty.
Other efforts have left me with only the last record populating the fist box and the others empty.
Any help greatly appreciated.
$(Udata).each(function(uId, value){
uid = value.uid;
var uname = value.uname;
function setValues() {
window.document.getElementById("username").value=uname;
window.document.getElementById("frmDelUsr").setAttribute("name","frmDelUsr"+uid);
}
$.get("users.html",{}, function (data) {
$("#divfrmDelUser").append(data), function(){setValues();}
});
$(Udata).each(function(uId, value){
uid = value.uid;
var uname = value.uname;
function setValues() {
window.document.getElementById("username").value=uname;
window.document.getElementById("frmDelUsr").setAttribute("name","frmDelUsr"+uid);
}
$.get("users.html",{}, function (data) {
$(this).children('.divfrmDelUser').append(data), function(){setValues();} //<--- CHANGED
});
First you'd have to change the element with the ID "divfrmDelUser" by making that ID into a class(just erase "id" and type "class" obviously), then what this ought to do is select the current Udata being used, and then look for the elements within it containing the class "divfrmDelUser" and do what you set it to do past that.
I create a table dynamically and add rows, labels etc to it.
I want to be able to access those rows to make either visible or hidden AND access labels to change content on the fly. So far the table and all info is created with no problem. I spent days trying to access the data from JS, but I keep getting NULL etc on objects using ALERT to test it. Here's a snippet example of my code...
ASP.NET (C#) code
mTable = new HtmlTable();
mTable.ID = "mTable";
aCell = new HtmlTableCell();
aLabel = new Label();
aLabel.ID = "aLabel";
aLabel.Text = "TEST";
aCell.Controls.Add(aLabel);
aRow = new HtmlTableRow();
aRow.ID = "r" + x;
aRow.Cells.Add(aCell);
mTable.Controls.Add(aRow);
Ive put the following code in a SCRIPT FILE etc and ive tried many styles.
alert(document.getElementById('<%=aLabel.ClientID%>'));
If you are using plain vanilla javascript, please look at the code sample here: How do I iterate through table rows and cells in javascript?
The code sample in the above link gets the table by id, which in your case is 'mTable' (from your c# code)
var table = document.getElementById('mTable');
// will return you a reference to the table object on the page
You also have to place the code to call your javascript function that accesses data on the 'mTable' on the document load event
I'm using FancyTree for the first time, and I would like define some custom node data, specifically an attribute named "content" in the HTML data used to create the tree:
<li id="xxxx" data-content="true" class="folder">
I have an init event-handler written in JavaScript and I want to access my custom data attribute there:
init: function(event, data, flag)
{
var tree = $("#tree").fancytree("getTree");
node = tree.getNodeByKey(key);
var data = node.data;
In an online tutorial, I saw that my custom attribute would be accessible as node.data.content, but I'm unable to display my custom attribute in an alert box to demonstrate that it was actually defined. How do I access my custom data attribute in my JavaScript function?
Sheldon
Ok, so i finally got it working. Your were close to getting your result.
The key variable is a string which represent the 'id' attribute of each LI element in your tree. You will obtain the node with that key. Once the node is obtained, you can retrieve your custom data attribute associated to that node. Since our 'data' variable is an object, containing key/value, you need to call it's 'key' name on the data object to retrieve the value, like so 'data.content'.
JS
$(function () {
// using default options
//Caching DOM element
var $myTree = $("#tree").fancytree();
// Get the DynaTree object instance
var tree = $myTree.fancytree("getTree");
//Set my key
var key = "id1";
//Get the node
var node = tree.getNodeByKey(key);
//Get the custom data attribute associated to that node
var data = node.data;
//data is an object so, data.content will give you the value of the attribute
alert(data.content);
});
JSFIDDLE
Hope this helps!
I have an HTML table with the id "roster1" that allows users to add table rows with a button click, and I am attempting to save the table state via a "Save" button that runs the following piece of code:
function saveRoster () {
localStorage.setItem('rosterPd1','');
var roster = document.getElementById ('roster1');
localStorage.setItem('rosterPd1', roster);
}
If I input some static value into 'rosterPd1', then I can use the information written to localStorage with no problem. However, when I attempt to save the table by using the above code, I get [object HTMLTableElement] returned... which is CORRECT, but not particularly useful!
Can someone point me in the right direction on what I would have to do to get localStorage to save the contents of the table itself?
You can only save Strings to Storage, but it seems for what you're trying to do, innerHTML will suffice;
function saveRoster() {
var roster = document.getElementById('roster1');
if (!roster) return; // not found
localStorage.setItem('rosterPd1', roster.innerHTML); // store innerHTML
}
function loadRoster() {
var roster = document.getElementById('roster1');
if (!roster) return; // not found
roster.innerHTML = localStorage.getItem('rosterPd1'); // get+apply innerHTML
}
As for why you're getting [object HTMLTableElement], this is what happens when you call toString on a JavaScript reference to a <table>.
document.createElement('table').toString() // "[object HTMLTableElement]"
I am creating an application using javascript/HTML for windows 8 which basically displays text which is pulled from an html file.
I am using the data.js file to organise groups and items. One of the properties is the 'url' which stores the url of the html page which contains the main content for the application.
I came up with this code to retrieve the html code from the html page which contains the content to be displayed:
WinJS.UI.Fragments.renderCopy(url)
.done(function (fragment) {
return fragment;
});
How do I run this code for each item in the array in data.js and bind the data so that the content is from the HTML page, and the headings/titles are from the data.js file?
I apologise if I'm causing any confusion. I would appreciate any help.
Thanks.
Assuming you want to stick with the layout of data.js and not create your own data classes, I would use a custom renderer for the listview.
Something like this...
var customRender = WinJS.Utilities.markSupportedForProcessing(function (itemPromise) {
var currentItem = {};
return itemPromise.then(function (item) {
currentItem = item;
var myDiv = document.createElement("div");
return WinJS.UI.Fragments.renderCopy("/html/1_BasicFragmentLoad_Fragment.html", myDiv)
})
.then(function (fragment) {
var itemTemplate = WinJS.Utilities.query('.itemtemplate')[0];
currentItem.data.title = fragment.innerHTML;
return itemTemplate.winControl.render(currentItem.data);
});
}
);
In this example, I am binding the content of a html fragment to the title of a given item from data.js. You will need to update the itemtemplate and bind the title element to innerHTML instead of textContent.
<h4 class="item-title" data-win-bind="innerHTML: title"></h4>
You will also need to assign the custom renderer to the listview. You can do this in the HTML markup or just change the template js in groupItems.js to this...
listView.itemTemplate = customRender;
If you were to create your own data classes, you may want to put the promise chain from the customer renderer into the class constructor, eliminating the need for a customer renderer.