Get input value from input in array - javascript

So, this is kinda difficult to explain, and also to search for.
My situation:
i have a webpage which allows users to fill up to 48 time fields, all these time fields are dynamically generated, each with an ID of their own, all in a div.
Now, the user also has the option to delete a field, in any place. In this case i want to re-order them all.
Example: user has timebox 1 to 8, removes 5.
6 becomes 5, 7 becomes 6, 8 becomes 7.
This should also count for the ID's.
Now, when a user deletes a box, i pick up all the divs in a specific div (DailyControls) and put them in an array. All of these divs have a class named timepicker.
Now i need to get the value from the input boxes which are now also stored in the array.
This is for creating the textboxes (with the div, some text infront and the remove button)
var newTextBoxDiv = $(document.createElement('div')).attr("ID", 'time' + boxID);
newTextBoxDiv.after().html('<label>Herrinering #' + boxID + ' : </label>' +
'<input type="text" name="timebox' + boxID +
'" id="timebox' + boxID + '" value="" class="timepicker" >' + '<img src="<%= Page.ResolveUrl("~") %>images/ico_delete.png" id="Delete'+ boxID +'" onclick="DeleteTime()"/>');
newTextBoxDiv.attr("class", "timerdiv");
To remove them i am currently using the following:
function DeleteTime() {
var id = event.target.id;
var IdNO = id.replace("Delete", "");
$("#time" + IdNO).remove();
var elemdivs = [];
for (var i = 0; i < $(".timerdiv").length; i++) {
elemdivs.push($(".timerdiv")[i].innerHTML);
}
$('.timerdiv').remove();
for (var i = 0; i < elemdivs.length; i++) {
alert(elemdivs[i]);
}
};
in the alert i can see the input element, and also the div ect.
But i dont know how to get the value from there

Based on the information you provided this would probably work:
function DeleteTime() {
var id = event.target.id;
var IdNO = id.replace("Delete", "");
$("#time" + IdNO).remove();
var elemdivs = [];
for (var i = 0; i < $(".timerdiv").length; i++) {
elemdivs.push($(".timerdiv")[i]); // don't push innerHTML
}
$('.timerdiv').remove();
for (var i = 0; i < elemdivs.length; i++) {
alert($(elemdivs[i]).find('input').val());
}
};
Instead of inserting the innerHTML from your timerdiv into the you put in the timerdiv itself. Then when accessing it you .find() the input field inside of the timerdiv ($(elemdivs[i])) and then get the .val() from that.

Related

Using variable for an identifier name (using jquery selectors)

Believe me, I've been looking for examples online for hours. None of them seem to help.
I'm working on making a table. There are some columns with dropdown menu and I've assigned ID to each menu. Inside a loop, I'm trying to assign selected value for each dropdown menu.
var row$ = $('<tr/>');
function updateDataBodyGenerator(myList) {
for (var i = 0 ; i < myList.length ; i++) {
var row$ = $('<tr/>');
var colIndex = 0;
for (var key in myList[i]) {
var cellValue = myList[i][columns[colIndex]];
if (cellValue == null) { cellValue = ""; }
var severityDropDownMenu = "severityDropDownMenu" + i;
colIndex++;
switch (key) {
case "Test Case":
...
break;
case "Test Result":
...
break;
case "Severity":
var severitySting = '<td><select id="' + severityDropDownMenu + '" class="dropDownMenu">' +
'<option value="Red">Red</option>' +
'<option value="Green">Green</option>'+
'<option value="Yellow">Yellow</option>';
row$.append($(severitySting));
//failed
//$("#severityDropDownMenu" + i).val(cellValue);
//failed
//var selectorString = "#" + severityDropDownMenu.toString();
//$(selectorString).val("Green");
//failed
//$("#" + severityDropDownMenu).val(cellValue);
//failed
//var selectorString = '#' + severityDropDownMenu;
//$(selectorString).val(cellValue);
//works
//$('#severityDropDownMenu0').val(cellValue);
...
As you can see in the comments, I've tried several approaches and only 1 worked which was $('#severityDropDownMenu0').val(cellValue); but that will only change 1 dropdown menu.
I appreciate your time and assistance.
Currently you're trying to use the # selector to target the dropdown by ID.
The issue here (as mentioned in the comments) is that this selector will search the DOM for the element, however because you've never added this element to the DOM, it doesn't exist on the page; the selector will return nothing.
What you can do instead is actually turn your severitySting into a jQuery element to set its value. Whenever you do append it, the value will be properly set. Like so:
var $severity = $(severitySting); //This is the <td>
var $dropdown = $severity.find("select") //This is the <select>
$dropdown.val(cellValue); //Set dropdown value
Demo:
var severityDropDownMenu = "mytest";
var cellValue = "Yellow";
var severitySting = '<td><select id="' + severityDropDownMenu + '" class="dropDownMenu">' +
'<option value="Red">Red</option>' +
'<option value="Green">Green</option>' +
'<option value="Yellow">Yellow</option>';
var $severity = $(severitySting);
var $dropdown = $severity.find("select");
$dropdown.val(cellValue);
$("tr").append($severity);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr></tr>
</table>

How do i mark as selected a specific option from a select which his options are loaded depending of an input number?

take your time to read my explanation and ask me if i didn't explain myself well, thanks.
Don't mind how i print whith php, it it okay this way, this is a php setting.
i have in a template an input number that the client will fill with an amount of pallets, in the same template i have a table with as many tr as boxes the order has.
so, there are as many selects as tr, because it is used to assign the box to a pallet.
When the process is done i have the info in my database and if the client enters again he will need to have all the data in place, so the input number is filled and that fills all the selects with the amount of otions as the input, ok.
the fill process is made with jquery.
in the template, i have only this to make the select
<td><select class="pallets_assign" name="boxes[<?=$box;?>][which_pallet]"></select></td>
UPDATE:
to load the options in the selects i use this inside a document ready :
var someone = function() {
var something = function(from_pallets, to_pallets) {
var qty = $(from_pallets);
var select = $(to_pallets);
var update = function() {
select.empty();
for (var i = 1; i <= qty.val(); i++) {
select.append('<option value="' + i + '">' + i + '</option>');
}
};
qty.on('change', update);
update();
}
});
form the tamplate i call it like this:
var init = function() {
someone.something('#total_pallets', '.pallets_assign');
};
total_pallets is the id of the input number
My question is: how do i mark as selected the option which value i have stored in my database if i don't have the options created when the DOM is loaded but when that input number changed?
Thanks for your time.
Thanks to #AlonEitan to helping me find a way to solve this
in the template i had a script that did something like this:
var init = function() {
someone.something('#total_pallets', '.pallets_assign');
};
changed to:
var init = function() {
var option = [];
<? foreach ($products as $product) { ?>
<? for ($i = 1; $i <= count($product["boxes"]); $i++) { ?>
option.push(<?=(somechecks ? $product["boxes"][$i]["which_pallet"] : false);?>);
<? } ?>
<? } ?>
someone.something('#total_pallets', '.pallets_assign', option);
};
and in my js file i had this:
var someone = function() {
var something = function(from_pallets, to_pallets) {
var qty = $(from_pallets);
var select = $(to_pallets);
var update = function() {
select.empty();
for (var i = 1; i <= qty.val(); i++) {
select.append('<option value="' + i + '">' + i + '</option>');
}
};
qty.on('change', update);
update();
}
});
which is now:
var someone = function() {
var something = function(from_pallets, to_pallets, option) {
var qty = $(from_pallets);
var select = $(to_pallets);
var update = function() {
select.empty();
select.each(function(i) {
for (var j = 1; j <= qty.val(); j++) {
$(this).append('<option value="' + j + '"' + (j == option[i] ? ' selected="selected"' : '') + '>' + j + '</option>');
}
});
};
qty.on('change', update);
update();
}
});
It is a shame that in the beginning this got that many downvotes because i think is a cool way to solve this kind of issue and people will profit of this, but anyway.

jQuery: building a form dynamically from an array with a for loop

I have a jQuery function that receives id of div element and json array
function FormBuilder(selector,myList){
for (var i = 0 ; i < myList.length ; i++) {
var rowHash = myList[i];
if(rowHash['id'] > 0 ){
$(selector).append('<form id="DialerInfo">');
for (var key in rowHash) {
$(selector).append(key +': <input type="text" name="' + key + '" value="' + rowHash[key] + '"><br/>');
}
$(selector).append('</form>');
}
}
}
And I expected this to build a proper form, i.e. all inputs should be between <form> and </form> tags. But I'm receiving something completely different:
First goes
<form id="DialerInfo"></form>
then below all input fields. Why are they outside the form tags? does jQuery close all tags automatically? how to prevent this behavior then?
DOM creation using jQuery doesn't work like string concatenation
You can create a form and append all the elements to it
function FormBuilder(selector, myList) {
var $form = $('<form id="DialerInfo"></form>').appendTo(selector);
for (var i = 0; i < myList.length; i++) {
var rowHash = myList[i];
if (rowHash['id'] > 0) {
for (var key in rowHash) {
$form.append(key + ': <input type="text" name="' + key + '" value="' + rowHash[key] + '"><br/>');
}
}
}
}
//use
$.each(arrayorJSON,function(KEY,VALUE){
//YOUR CODE HERE
})
//it is a jquery looper which accepts both array and json values and compatible with all browsers instead of for loop

How to get id of a element in all the rows of a table using jQuery

My table id is "termTable". I am iterating through each row of the table. The id of textbox is "label'+ i +'" since I used for loop to generate ids randomly. The values of i will be unordered maybe after adding the rows or deleting the rows. Example: IDs are label1, label2, label3. After deleting the 2nd row, I am adding another row. So now the IDs are label1,label3, label4. I want to retrieve all the ids of all the textbox elements. How can I achieve it? Please help.
for (var i = 0; i < firstTabLength; i++) {
var row = $("#termTable tr").eq(i);
var id = row.find('input[type="text"]').attr('id'); // I could see id = undefined
}
This is Html. This is for adding the new rows to table. Guess you can visualize the table structure with the help of below code.
function AddCustomTerm1() {
len = len + 1;
var table = document.getElementById("termTable");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML = '<input type="text" class="form-control" id="label' + (len - 1) + '" name="label' + (len - 1) + '" value=""><input type="hidden" id="step' + (len - 1) + '" value="1"/>';
row.insertCell(1).innerHTML = '<select class="form-control" id="dataTypes' + (len - 1) + '" name="dataTypes' + (len - 1) + '" onchange="changeDataType(this)"></select>'
row.insertCell(2).innerHTML = '<input type="text" class="form-control" id="ContractTerm' + (len - 1) + '" name="ContractTerm' + (len - 1) + '" value="">';
var DD = document.getElementById("dataTypes" + (len - 1));
for (var i = 0; i < datatypesarray.length; i++) {
var opt = document.createElement("option");
opt.text = datatypesarray[i];
opt.value = datatypesarray[i];
DD.appendChild(opt);
}
without you html format cant help much.
but try this ones.you dont even need a for loop to get all the textbox and their ids from table.
var ids=[];
$('#termTable input[type="text"]').each(function(){
ids.push($(this).attr('id'))
})
if you want ids of the textboxes in first column of the table.the try this
var ids=[];
$('#termTable tr').each(function(){
ids.push($(this).find('td:first-child input[type="text"]').attr('id'))
})
The best practice is to add a specific class to all of your elements that need to be iterated.
For example add the class term-table-input to your inputs:
row.insertCell(0).innerHTML = '<input type="text" class="form-control term-table-input" id="label' + (len - 1) + '" name="label' + (len - 1) + '" value=""><input type="hidden" id="step' + (len - 1) + '" value="1"/>';
And iterate them with:
var termTableInputIDs = [];
$('.term-table-input').each(function () {
termTableInputIDs.push($(this).attr('id'));
});
Also you could read more about writing efficient css here:
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Writing_efficient_CSS
Since you have more than one input[type="text"] in a row, you should take the first. Also you can use each() instead of for.
$('#termTable tr').each(function() {
var id = $(this).find('input[type="text"]:first').attr('id');
console.log(id);
});
You find all the input elements inside the table by using $('#termTable input') and to loop through all the selected elements you use $.each API
Use Code like below.
var InputIds = []; //array to hold your id's
$.each($('#termTabel input[type="text"]'),function(i,v){
InputIds.push($(this).attr('id'));
});
console.log(InputIds.toString());
//this finds all inputs which id start from "label"
$('#termTable input[id^="label"]').each(function(){ console.log(this.id); });
example: https://jsbin.com/lisuratere/edit?html,js,output

Listing down stored records localStorage | Google Chrome Extensions

How do I get to list down the stored records in the for loop?
Basically I want it to list down the records like this:
'<div id="record_' + number + '">' + localstorage value + '</div>'
The number in the class should add 1 every record, e.g. 1, 2, 3, 4 every record it lists down, and so on.
The localstorage value should show the localStorage[] but the problem is, the localStorage name has the same, e.g.
(clicks on button)
it will save the value of the URL into a localStorage
I then open the application and shows the window.html
inside there is list of stored records by using this:
'<div id="record_' + number + '">' + localstorage value + '</div>'
INCLUDING the record number to add per record 1, 2, 3, etc... like this:
<div id="record_1">localstorage value</div>
<div id="record_2">localstorage value</div>
<div id="record_3">localstorage value</div>
<div id="record_4">localstorage value</div>
<div id="record_5">localstorage value</div>
<div id="record_6">localstorage value</div>
etc...
EDIT:
for (var i = 1; i < localStorage.length; i++) {
document.write('<div id="record_' + i + '">' + i + '<span style="float:right;">Delete</span></div>');
}
window.addEventListener("load", windowLoaded, false);
function windowLoaded()
{
chrome.tabs.getSelected(null, function(tab)
{
var btn = 'Add to Favourites';
document.getElementById('current-link').innerHTML = '<p>' + btn + '</p>';
});
}
function Save(url)
{
localStorage.setItem("cilium-favs", url);
}
You can iterate localStorage as well.
for (var i=0; i < localStorage.length; i++) {
console.log(localStorage.key(i));
}
Is that what you want?
I think this is more what he was looking for. A couple of years late, but Mohamed Mansour's answer helped me, and this might help others.
for (var i = 0; i < localStorage.length; i++) {
var key = localStorage.key(i);
console.log(i, key, localStorage[key]);
}

Categories

Resources