Populating HTML table based on checkboxes - javascript

I have multiple checkboxes on a HTML page, and I would like to be able to populate a table on a second HTML page based on what checkboxes have been clicked.
As a basic example, here is a div containing 2 of the checkboxes. I would like it so that if, say, awareness_checkbox was checked, the word Awareness and it's value (0.01 CPC) would be added to a table on my second HTML page.
How would be the best way to go about doing this? My intention is to have a HTML button that links to the second page (let's call it 'page2.html') so that when it is clicked, every checkbox that has been checked on the page has it's label and associated value added to a table that will appear on the second page.
Any help would be greatly appreciated.
<div class="campaignstrategy">
<h1>1. Campaign Strategy</h1>
<input type="checkbox" name="awareness" id="awareness_checkbox" value="0.01">Awareness<br>
<input type="checkbox" name="directresponse" id="directresponse_checkbox" value="0.01">Direct Response<br>
</div>

Note
okay, so I re-did all the code and tested locally on chrome, just save both files in the same directory and then open page1.html in chrome.
Code Extracts - Page 1
Assign a custom action to the input button, this will check all checkbox input type inputs,
it will then see whether or not it is checked, if it is checked then it will add an entry into table_info variable, after checking all inputs
it will then convert the javascript object into a json string, then we convert that json into base64 encoded string.
then we browse to the page2.html file and in the url we pass a key called "table_data" and its value is the base64 encoded string.
$('#next_page_button').click(function(){
let table_info = [];
$('.campaignstrategy input[type=checkbox]').each(
function(index, value){
if($(this).is(':checked')){
table_info.push(
{
name: $(this).attr('name'),
value: $(this).attr('value'),
}
);
}
});
let base64str=btoa(JSON.stringify(table_info));
window.location = "page2.html?table_data=" + base64str;
});
Code Extracts - Page 2
when this page is loaded into the browser, the following script will check the query keys, in this case we are looking for 'table_data' key.
this will be accomplished by a helper function (see pastbin for details, left out to keep the answer short)
once we have the data, we will decode it from base64 to json, then using the json.parse function we will recreate the javascript object.
after creating the object, we will loop through the array, remember the javascript object that we decode is an array of dictionaries,
[{'name':'awareness','value':'0.01'}] as you see, it has the checkbox's name and its associcated value.
then we create the table row, and append the name and value to the table row inside a table data element, one for each name and value.
// actual code
let table_data = getUrlParameter('table_data');
let data_from_page_1 = JSON.parse(atob(table_data));
for(let i=0;i<data_from_page_1.length;i++){
let row = $("<tr></tr>");
let recordName = $("<td></td>").text(data_from_page_1[i].name);
let recordValue = $("<td></td>").text(data_from_page_1[i].value);
row.append(recordName, recordValue);
$('#output_table').append(row);
}
Examples
Page 1
Page 2
Instructions
save the contents of this to a file called page1.html Code Link For Page 1
save the contents of this to a file called page2.html Code Link For Page 2

Related

How can I write the code to append all of the items(XPages)?

I have many documents in Notes, all of the documents have a different form, like this picture :
(possibly like pic 1, pic 2, or pic 3)
How can I write the code in Xpages?
use the "computed field"? Or use the "input text"?
I used the "input text".But only for one item, not for all.
var doc = purchase.getDocument();
var A0 = doc.getItemValueString("DAY_A0");
if(A0 != 0){
return "Division processing";
}
If the form not only has one item, like the pics. How can I write the code to append all of the items?
I'm making the following assumptions here:
You have 10 fields in the document with numbers that might or might not be > 0
The 11th value (Total) shall be computed
You want to show one document at a time, not a list
You know how to add a data source to a page
Version 1:
Create a regular XPages form, use the wizard when adding the document data source. It now would show also the field with 0 values
Click on each ROW and change visibility property to computed (make sure you hit the row, not the cell or field) and add a visibility formula based on the field oof that row. Something like doc.DAY_A0 > 0
Add a computed field where you add the values of all 11 fields
done
Version 2:
in the page open event, get a handle on the document and compute a scoped variable that only contains the values you are interested in. Could be messy since you need a label (that is not your field name) and a value
Use a repeat control to render the values
Hope that helps

Struts- About saving checkboxes when following a link

I'm working on a jsp containing some checkboxes. My jsp is linked to a form (called SuiviTransfertForm), and this form has an attribute called checkboxUID, which is an array containing the ids of my checked checkboxes.
private String[] checkboxUID = {};
This attribute is mapped with the checkboxes of my jsp like this :
<html-el:multibox name="suiviTransfertForm" property="checkboxUID"/>
I would like to follow a link on this jsp and get the content of checkboxUID when I'm on the next page.
On the next page, I'm getting back my form like this :
SuiviTransfertForm suiviTransfertForm = (SuiviTransfertForm) form;
The problem is that checkboxUID is correctly filled if I stay on the same page, but always empty when I'm changing page. I can't find a way to achieve this.
Many thanks for your help !
When you're clicking the link it's not submit the form. Hence you cannot get any values from form. Try sending through URL (script way - though it's not a best practice)
var arrayValues = [12,34,54,67]; //Get the selected checkbox values when clicking link
var QueryString = JSON.stringify(arrayValues);
var a = document.getElementById('yourlinkId');
a.href = 'myLink?params='+QueryString;
or you can use jQuery for simple code,
$('#yourlinkId').attr({"href" : '/myLink?params=' + arrayValues.join(',')});
Try and let me know if it helps.
I finnaly fixed the problem by listing my checked checkboxes and setting them to the form after clicking my link.
Many thanks for your help guys !

retrieve value from textbox that is not on the current pagination - datatables

I am using VB.Net, MVC, Razor, javaScript and jQuery with the Datatables plugin. I am rendering a table that contains text boxes. The user is allowed to type values into these text boxes and submit the values to the database.
Everything works fine as long as the table is only one page long. In the event that the table is multiple pages, only the values that are visible are submitted. However if the user enters values on page one, moves to page two, then back to page one, the values that were typed into the text boxes are still there. This leads me to believe the values are still on the web page somewhere. I am currently using javaScript getElementsByClassName to retrieve the values.
Here is how my table is rendered:
<tbody>
#For i As Integer = 0 To Model.History.Count - 1
#<tr>
<td>#Model.History(i).Quarter</td>
#If Model.History(i).MeterUsage < 0 Then
#<td>
<input class="edit" id="#(Model.History(i).dateToRecord)" type="text" placeholder="meter usage" />
</td>
Else
#<td>#Model.History(i).MeterUsage</td>
End If
<td>#Model.History(i).KeyOperator</td>
<td>#Model.History(i).BackUpKeyOperator</td>
</tr>
Next
</tbody>
Here is my javaScript:
function submitChanges(changes) {
var changes = document.getElementsByClassName('edit');
var myChanges = {
listOfIDs: [],
listOfValues: []
};
}
Is there some way to capture the values that are entered on page 1 of the table, when the user is viewing another page of the table?
Use $() API method to get access to all elements in the table.
function submitChanges(changes) {
var changes = $('#example').DataTable().$('.edit');
var myChanges = {
listOfIDs: [],
listOfValues: []
};
}
Replace example with your actual table ID.

Jquery each loop showing first value as zero or NaN

I am using jquery to gather data from a dynamically created table via Jquery. I am able to get the data, but now I want to sum up the fields and put the result inside a text field or label etc dynamically when I press enter. I am using the following code:
$("#iq").keypress(function(e)
{
if(e.which==13)
{
var tot=0;
$('#tab .itemtotal').each(function()
{
tot = tot + parseInt($(this).html());
});
$("#totalamount").val(tot);
}
});
My problem is that the value showing in the textfield is zero or NaN for the first time and after that its calculating correctly. I used the same code and associating it with a button and checking its click event and its working properly and showing first item also.
Any suggestions? If need some more clarification let me know. Thanks in advance.

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

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
}

Categories

Resources