How to get values from dynamically added (using javascript) elements? - javascript

On my aspx page I dynamically create html controls on client side using javascript. For example, after page load you can click button in a browser, by clicking button html input and select elements appear. You may click once again, and this elements (input and select) will added again. So, you can create so many inputs and selects as you want (all this using javascript, no postbacks)
After user created some inputs and selects and entered some information in it, he posted form. I want on server side to find all this dynamically added elements and perform some actions depends on values in this controls.
How can I find dynamically added elements, and what is the best and elegant way to achieve this?
Thanks in advance.

In the Javascript that creates the new elements, increment a counter each time an element is created. Add the value of the counter to the name of the input element so each element has a unique name.
Add the final value of the counter to a hidden form field when the form is posted.
In your server side code, create a loop that starts at zero and continues until you have reached the value of the counter. Within the loop, fetch the posted value of the corresponding form field.

When you add the elements, assign unique IDs to them, and then retrieve their values using Request.Form["UniqueIdHere"] (C#) or Request.Form("UniqueIdHere") (VB.NET).

Create a loop that loops through each input and select object, that grabs the name/id of the current object and its corresponding value. Then add those items to an array and once the loop is completed, pass those values to your aspx file.
You can view an example with this approach at: http://jsfiddle.net/euHeX/. It currently just alerts the values, but you could easily modify it to pass the values as a parameter via ajax to your handler aspx file. The code will add new inputs or select boxes based off of the input provided. This would of course be modified to reflect your current setup.
HTML:
<div id="dynamic"></div>
<input type="button" id="submit-form" value="Submit>>">
JavaScript (using jQuery):
function createInput(type){
for(var i=0; i<5; i++){
if(type==0){
var obj = '<input type="text" id="'+i+'" class="dynamicContent">';
}else if(type==1){
var obj = '<select id="'+i+'" class="dynamicContent"><option>--Select--</option></select>';
}
$("#dynamic").append(obj);
}
}
function getContent(){
var inputArray = [];
$(".dynamicContent").each(function(k,v){
var o = $(this);
var oType;
if(o.is("input")){ oType = "input"; }
if(o.is("select")){ oType = "select"; }
var oID = oType+o.attr("id");
var oValue = o.val();
inputArray.push(oID+'='+oValue);
});
alert(inputArray);
}
$("#submit-form").click(function(){
getContent();
});
// Set type to 0 for input or 1 for select
var type = '1';
createInput(type);

If you're using jQuery you can use .live() to achive this like a peace of cake!
http://api.jquery.com/live/

I don't know if your controls will survive the postback the way you're creating them, but a good technique for accessing dynamically generated controls (assuming that you've figured out how to persist them) is to do something like the following:
Add a panel to your page. Add your dynamically created controls to this panel.
In the OnClick event handler (or other method), do something like the following:
foreach (DropDownList ddl in Panel1.Controls.OfType<DropDownList>())
{
//put code here
}
foreach (TextBox txt in Panel1.Controls.OfType<TextBox>())
{
//put code here
}

Related

JQUERY DOM: Select Elements Created After Dom Load

I am working on a project where I need to change the value of all select inputs of a certain class when a function is called. The problem is some of the select inputs do not exist when the dom is first loaded, they are created dynamically via Javascript.
The function works fine for selecting all the select inputs that exist when the page was loaded, but does not work for any select inputs that were added to the dom dynamically.
I understand event binding with .on but in this particular case I am not trying to key off of an event like click. I want to get all elements of this class when this function is called.
Here is the code I am using to create the new select elements.
var this_cell = document.getElementById('produce_batch_line_td['+x+']');
var new_select = document.createElement("select");
new_select.name = "produce_batch_line["+x+"]";
new_select.id = "produce_batch_line["+x+"]";
new_select.className = "produce_batch_line["+invoice_number+"]";
this_cell.appendChild(new_select);
var new_option = document.createElement("option");
new_option.text = "test";
new_option.value = "test";
new_select.add(new_option);
Here is the code I am using to select all select elements of this class.
function SetDetailValue(invoice_number, obj) {
$(".produce_batch_line\\["+invoice_number+"\\]").each(function() {
this.value = obj.value;
});
}
How can I get items of this class added to the dom dynamically?
Check this link. I have put one that already exist. And when you click add button it creates dynamicly as well. When you Click the set button it finds them with a java query and puts them into a for loop that changes each ones value one by one.
http://cr8code.co/editor.php?workid=1a446530189d751d0b15ce104a286eee
Here is the DEMO

How to get any column of any row of a Table in HTML?

Suppose there is Table with variable number of rows of fixed number of columns, and suppose each row has a button too, now I want to select for example a column's value(let's say this selected column is textarea, so I select it's content) when that row's button is clicked.
For example in above image I want that if submit is pressed than all data of 'textarea' of corresponding row should be stored in a variable.
You can use the jQuery closest() function to find an element near the clicked button. Add click handlers to the buttons and then traverse up to find the textarea.
$('.button').on("click",function(){
var thisRowsTA = $(this).closest("textarea");
console.log($(thisRowsTA).val());
});
A simply way is to:
Put an ID pattern to your textareas, like: txt_area_1, txt_area_2, txt_area_3.
Then, on the Click Event of your buttons, make them catch the corresponding textarea in their row. Use the ID patterns to do this.
Post your code for further help.
You will need to ad an event handler for each button. Inside of that you can write something like this.
function eventHandler(e){
var row = this; // start at the button
while(row.nodeName != 'TR' && row.parent){
// go up till we find the row
row = row.parent;
}
var textArea = row.querySelector('textarea');
var value = textArea.value;
// do something with supplied feedback.
}
In order to attach the handlers, you would do something like this.
function attachTableEvents(){
var table = document.querySelector('table'); // or more specific selector if needed
var buttons = table.querySelectorAll('button');
for (var i = buttons.length; i--;){
buttons[i].addEventListener(eventHandler);
}
}
Counting on the DOM structure is really BAD.
I would put an attribute in my controls that holds the line number. Then when clicking an element you can easily query the DOM by element type and the property value to get any elements in this line.
Later if you change to DIVs or change structure your will still run correctly

jQuery clone elements with-in a main wrap

I am trying to create a summary page where I grab all content form the main page and show it in a overlapping div sort of like images are displayed these days.
Now problem that I get I lose input and select values once I past it into a summary / print wrap.
jQuery
$(".header").clone().appendTo('.page');
$(".task").clone().appendTo('.page');
$(".options").clone().appendTo('.page');
.header and .task are just plain text input. And that works just fine. However with in the .options I have many controls like textarea, input, and select ... I get all the elements into .page however I lose all the selected values and text.
Any suggestion?
Thanks
The value of the inputs are not stored in the attribute tag value. This means that the copy will not have the value set. So before you copy them set the value attr.
function CopyStuffToPage() {
// Doing this will change the HTML for all the input elements
$('input').each(function(index,element) {
$(element).attr('value',$(element).val());
});
$('textarea').each(function(index,element) {
$(element).html($(element).val());
});
$('select').each(function(index,element) {
var value = $(element).val();
$(element).children('option').removeAttr('selected');
$(element).children('option[value='+value+']').attr('selected','selected');
});
// Then you can do this
$(".header").clone().appendTo('.page');
$(".task").clone().appendTo('.page');
$(".options").clone().appendTo('.page');
}
For selects you will have to add the attribute 'selected' to the option for which the select has selected.
I had this same issue when I wanted to save the contents of a div through PHP I had to set the attribute tags then send the HTML.
Edit: To Clerify the values of the elements you are copying are not stored as
<input value='this value'/>
they are stored in the DOM thus cloning them only clones the html not the value.
You can use localstorage for a quick patch to your problem.
Store the values within the textbox and textarea as,
//retrieving value from textbox and text area,
var textbox = $("#id-of-textbox").val();
var textarea = $("#id-of-textarea").val();
//retrieving the selected value for 'select'
var selectedValue = $('#id-of-select').val();
//storing the value in localstorage
localstorage.setItem("textbox", textbox);
localstorage.setItem("textarea", textarea);
localstorage.setItem("select", selectedValue);
//You can retrieve the above stored values anywhere you want as,
var newtextbox = localstorage.getItem("textbox");
var newtextarea = localstorage.getItem("textarea");
var newselect = localstorage.getItem("select");
//It is advisable to remove the store data after it's use,
localstorage.removeItem("textbox");
localstorage.removeItem("textarea");
localstorage.removeItem("select");
Advantage of using localstorage is that the data is stored within user's browser so you can access it on any page just like session data.

jQuery: Put dynamically generated input values to span/div

I'm trying to create form for printing with dynamically generated inputs.
Contents of the fields is shown later in PreviewDiv.
It works fine as long as I specify where they should be, for example:
$('#Prw_CapacityA_1').text($('#CapacityA_1').val());
$('#Prw_CapacityB_1').text($('#CapacityB_1').val());
$('#Prw_CapacityC_1').text($('#CapacityC_1').val());
But if the user creates 100 fields this would be a lot of code to write.
There must be other methods to fix this dynamically, for example:
$('#Prw_CapacityA_'+ counter).text($('#CapacityA_'+ counter).val());
Here's the js fiddle
You could try using attribute starts with selector to select the elements starting with the specific id's and then loop through them using the each() function.
There is no need to have html within your preview table. You can generate it when the user clicks on preview. Modified fiddle
$('#PreviewButton').click(function(){
var capB = $('td input[id^=CapacityB_]');
var capC = $('td input[id^=CapacityC_]');
var table = $("#AddFieldsToPreviewDiv");
table.empty(); //build table everytime user previews so that previously appended values are removed
table.append('<tr><td>ID</td><td>Text 1</td><td>Text 2</td><td>Text 3</td></tr>');
$('td input[id^=CapacityA_]').each(function(i){
table.append('<tr><td>#'+(i + 1)
+'</td><td>'+$(this).val()
+'</td><td>'+$(capB[i]).val()
+'</td><td>'+$(capC[i]).val()
+'</td></tr>');
});
// Show PreviewDiv and hide FormDiv if PreviewButton clicked
$('#PreviewDiv').show();
$('#FormDiv').hide();
});
You could try giving them a unique class (Normally I'd suggest ID but you're using one) say a class of "getinfo"
You could then try the .each() function
https://api.jquery.com/each/
$( ".getinfo" ).each(function( index ) {
var text = $(this).val();
alert(text);
});
This will make an alert box for every element it finds with the class 'getinfo' and then retrieve the value and display it, I hope this gives you a better idea.
If the amount of inputs can change from one page load to the next then you need to use a loop, rather than pulling all the values by 'hand', More code will help better understand what you're trying to achieve and from what.

How to store multiple related values in javascript?

I have a set of checkboxes in a page and each checkbox is associated with a textbox.
What I need to do is to disable the textbox if the checkbox is unchecked and put a default value inside it(each textbox has a different default value).
Right now I have written a function which accepts checkboxId, textboxId and the default value which is called onClick of the checkbox.
Is there a way to store this information(checkBoxId,textBoxId,defaultValue) statically(like a map or something) in javascript so that my function does not require any arguments and can be called onLoad of the page?
This is something I did before:
<input type="checkbox" id="sample">
<input data-requires="sample" data-default="Default">
function applyControls(){
$("input[data-requires]").each(function(){
var target = $(this);
$("#" + target.data("requires")).click(function(){
if(this.checked){
target.prop("disabled", false);
}else{
target.prop("disabled", true).val(target.data("default"));
}
});
});
}
applyControls();
Note: This code is written with jQuery. You can easily convert this to native code by substituting jQuery methods with native methods.
Demo: http://jsfiddle.net/DerekL/VnHAc/
Now this way you don't have to create any map or Object to store these relations (you don't even need ids for individual textboxes!) By using data-* attributes, you do not have to modify a "map" every single time you add connections. In fact, this is the preferred way1 of doing it in HTML5.
1 https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes

Categories

Resources