How to assign element values inside jquery.each() function - javascript

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.

Related

Jquery <<S.fn.init [selector]>> in Java Script Vanilla

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.

How to get the index of one specific element within an javascript object

I have been working on this problem for the second day now and I simply can't seem to find the right way to do it.
Problem:
I need to send the index value of a chosen element within a javascript object to an action in PHP. So when the user chooses a certain element, the index value of said element within the object should be send to the mentioned PHP action.
What I have so far is the following:
The button for the jump:
<!-- Button to jumpo tp specific dashboard. The select and and option tags will be generated dynamicly -->
<div style="float:right; margin-right: 10px;">
<select name="idDashboards" id="idDashboards">
<option value="">Jump to Dashboard</option>
</select>
</div>
The Array itself as well as how the HTML elements are created
// The array with the dashboards as I get it from the server
var dashboardArray = <?php echo json_encode(CHtml::listData($dashboards, 'iddashboard', 'title')); ?>;
// Loop through the elements in the dashboardArray and then create option elements to be added to the above create select element.
for (var idDashboard in dashboardArray) {
$('#idDashboards').append($(document.createElement('option')).prop({
value: idDashboard,
text: dashboardArray[idDashboard].charAt(0).toUpperCase() + dashboardArray[idDashboard].slice(1)
}));
};
How the object looks like when I log it.
{2: "Dashboard_Test_1", 3: "Dashboard_Test_2", 4: "Dashboard_Test_3", 6: "Dashboard_Test_4"}
What I have been trying so far:
var dashboardIndex = -1;
var i;
// Loop to get the indexes.
for (i in dashboardArray) {
if (dashboardArray.hasOwnProperty(i)) {
dashboardIndex++
console.log(dashboardIndex+" These are the indexes");
}
}
// Ajax request that sends data to the PHP action
$("#idDashboards").change(function() {
var idDashboard = $(this).val();
console.log("The change happened!");
$.ajax({
url: 'Path/To/PHP/File/And/Action=' + dashboardIndex,
method: 'GET',
success: function(result) {
location.reload();
console.log("So far, so good!");
}
});
});
});
Now, the dashboardIndex and the index of the elements in the object align and are good. But how do I send the index value of only the element that has been chosen by the user?
I am very sorry if this is a duplicate but I could not find anything helpful so far. Every advice/help is appreciated.
Inside your change function, you should be able to use $(this).prop('selectedIndex') to get the index of the item you selected.
I am curious, however, why the API is looking for the index of the dashboard rather than the seemingly unique ID that your API is initially responding with. This may be a more resilient approach.

Dynamic Dropdown from Mongo

I have a mongoDB with a DB = Staff and a collection = records. It contains a list of employees, and one of the fields is workgroup and it has items like "management", "union", "support staff", etc.
I want to populate a dropdown list with the values of the workgroup field and then use it to retrieve all records from the specified value selected in the dropdown.
I am using Ruby and I can retrieve the values ok (I can see them in the console), but they do not populate the dropdown list.
This is my Ruby statement:
get '/workgroup' do
Record.all.to_a.collect(&:workgroup).uniq.to_json
end
My attempt at the javascript is:
<script>
//var json = 'http://localhost:4567/api/v1/workgroup';
$(document).ready(function()
{
$.getJSON("/api/v1/workgroup",function(obj)
{
$.each(json.records,function(key,value)
{
var option = $('<option />').val(value.workgroup);
$("#dropDownDest").append(option);
})
})
});
</script>
Once I get the information in the dropdown, I want to use it to return all records with that workgroup value to a table. I haven't figured that part out yet. One step at a time!
Thanks!!
Within your $.getJSON call back you are referencing json.records, but there is no json variable or object.
The argument you are passing to the callback is obj. I think you really want to be doing $.each(obj, function(key, value)...

Set variables for multiple input IDs derived from JSON object

Directly below, the user clicks the link, which calls a PHP script and returns a JSON object, through which I parse and create INPUT fields each with their own ID, which was part of the JSON object:
$(function()
{
$('.addNewLink').click(function(e)
{
e.preventDefault();
$('#addNewForm input, #addNewForm select').val('');
$.post('api/size_types.php', function(data)
{
var obj = JSON.parse(data);
$('.size_types').empty();
var htmlToInsert = obj.map(function (item)
{
return '<div class="input-group">
<span class="input-group-addon" >'+item.SIZE_TYPE+'</span>
<input type="text" class="form-control size_types"
id="'+item.SIZE_TYPE+'" value="'+item.DEFAULT_TEU+'" />
</div>';
});
$('.size_types').html(htmlToInsert);
});
$('#addNewModal').modal('show');
});
});
In the code above, I was able to loop through the JSON and create INPUT fields all with their own ID's using item.SIZE_TYPE and have the values set to item.DEFAULT_TEU.
On the HTML side, there is a form, but hopefully I don't have to show that code. Just know there is a submit button with an ID called #addNewSubmit, which I will display the JavaScript directly below:
$('#addNewSubmit').click(function()
{
var addservice = $('#addservice').val(); // user entered field
// here is where I'm stuck
});
What I need to do is create variables using the INPUT fields automatically created by the JSON object. In my current case, 58 INPUT fields have been generated, all with their own ID and DEFAULT_VALUE. The user has the option to change the DEFAULT_VALUE.
After searching the web, I found this code and added it to the click event directly above, right beneath the first variable:
var size_types=new Array();
var j=0;
$(".size_types").each(function(){ // looking at the class, I need the ID
size_types[j]=$(this).val();
j++;
});
Using this, I can return the values of each of the INPUT fields in an ALERT box, but I need the IDs so I can send them all to a PHP script to INSERT into a database.
How can I get each ID and its VALUE and set them all to their own variables? Or, is there another way to do this?

Unable to retrieve dynamically generated content from localStorage

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]"

Categories

Resources