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?
Related
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.
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.
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 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 new to Javascript. I am hacking one application wherein I
need to get the values from the form and do processing on it :
icode=document.forms[0].intcode;
lamt=document.forms[0].lnamt.value;
nom =document.forms[0].nomon.value;
and update the values in the other fields in the form depending on the
above three values like this :
document.forms[0].monpmt.value=Math.round(mamt);
document.forms[0].totamt.value=totamt;
Note: these values must automatically appear in the form depending on the above three
values entered by the user.
function setTotamt() {
icode=document.forms[0].intcode;
lamt=document.forms[0].lnamt.value;
nom =document.forms[0].nomon.value;
intrate=icode.options[icode.selectedIndex].myvalue;
if(lamt >0 && nom>0 && intrate>0) {
document.forms[0].monpmt.value=Math.round(mamt);
document.forms[0].totamt.value=totamt;
}
}
I am doing this on Linux platform and tomcat.
> icode=document.forms[0].intcode;
> lamt=document.forms[0].lnamt.value;
> nom =document.forms[0].nomon.value;
Variables should be declared with var to keep them local (presuming the above is intended to be in a function). The syntax is more or less correct, it suggests an HTML structure like:
<form ...>
<input name="intcode" ... >
<input name="lnamt" ... >
<input name="nomon" ... >
...
<input name="monpmt" ...>
<input name="totamt" ...>
</form>
So if you have a button in the form that runs a function to get some values and update the value of some other control, it might look like:
<input type="button" onclick="updateForm(this);" ...>
and the update function might look like:
function updateForm(el) {
var form = el.form; // store a reference to the form
var icode = document.forms[0].intcode; // reference to element named "intcode"
// Get the value of some controls
var lamt = document.forms[0].lnamt.value;
var nom = document.forms[0].nomon.value;
// Do something with the values
var mamt = ...;
...
var totamt = ...;
// Set some values in the form
// Have a reference to the form so use it
form.monpmt.value = Math.round(mamt);
form.totamt.value = totamt;
}
Note that form control values are always strings and that you should test the values you get to make sure they are what you expect. If you want to update values without the user pressing a button[1] you can use the blur event to call updateForm.
You will need validation of input values and to deal with errors (updates before the user has filled in all the fields and invalid data being the obvious ones). Also you'll likely want to format the data when putting it back, such as formatting numbers to two decimal places perhaps.
A button is best as it can be a submit button so that if javascript is disabled or not working, the form is submitted and updated at the server and an updated form returned. If scripting is available, you can cancel the submit and do the processing on the client. You could have the update on the blur event and button if you want.