Adding views programmatically, then referencing those views. - javascript

I'm a novice in the java world, so thanks in advance for the help.
What I am trying to do is this:
I have two EditText fields and a Button. When I hit the button, I want to take the contents of the two fields, combine them and display them below button. The fields are cleared. Then if they are filled again and the button is pushed, combine the fields and display them below previously generated textview.
Example:
Before Button Click:
eT1___ eT2____ |Button|
After Button click
eT1___ eT2____ |Button|
eT1-eT2
After 2nd Button click
eT1___ eT2____ |Button|
eT1-eT2
eT1-eT2
And so on however many times the button is clicked. What I need help with is the new views that are being added. Currently I am using a Relative Layout. What I am trying to figure out is how to reference the new textView's that I am creating within the code so that when new views are added, they can reference the previously added view.
This is what I've been attempting at the moment:
private TextView createNewTextView(String desc, Double cost){
RelativeLayout.LayoutParams lparams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);;
TextView newTextView = new TextView(this);
if (i==1) {
lparams.addRule(RelativeLayout.BELOW, mButton.getId());
}
else {
lparams.addRule(RelativeLayout.BELOW, mLayout.getId());
}
lparams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
newTextView.setLayoutParams(lparams);
newTextView.setText(desc + " - $" + cost);
newTextView.setTag(i);
i++;
return newTextView;
}
I was trying to use "i" as an incrementing variable that I could use to reference the previous view by except on the first pass when it the new view references based on the button.
Any help would be greatly appreciated. Thanks in advance and for everything I've lurked already!

Create a member variable of ArrayList of TextView :
ArrayList<TextView> textviews = new ArrayList<>();
and then in your createNewTextView() method, store the reference of TextView you are adding:
textviews.add(newTextView);
So the TextView you've added at the first will be at index 0 and so on. Then you can easily reference your TextViews.
Suppose you want to get the second TextView,
TextView secondTv = textviews.get(1);

Just add your textviews to a global list and find them based on the tag from there.

Related

How do you store new value in a variable with an existing value based on a click?

I am making a map using leaflet where on click, the values stored in the geojson properties populate textareas in a sidebar. I will use these values to construct an URL that will hit an API. My intention is that the user can click any three box where class = "selected" and get back info on the map based his or her selection. But I am unable to clear the previous variable that was stored in groupSelected with the new one clicked.
//This grabs the geojson values and stores into the textarea tags in the sidebar
function checkInfo(e) {
var properties = e.target.feature.properties;
$("#nabe-name").html(properties.Name)
$("#top-group").html(properties.largest)
$("#second-group").html(properties.second)
$("#third-group").html(properties.third)
};
//This is where I am stuck:
$(".selected").on("click" ,function(e) {
nabe = $("#nabe-name").val();
var groupSelected= $(".selected").val();
}
<textarea id="nabe-name">Neighborhood</textarea>
<textarea class ="selected" id="top-group">Top</textarea>
<textarea class ="selected" id="second-group">Second</textarea>
<textarea class ="selected" id="third-group">Third</textarea>
I need groupSelected variable to change everytime I click into a different textarea. I have to consider how I close my functions since I need the two variables available to the AJAX request.
Please help. If not obvious, I am new to JS.
Thx
You are always getting the value of the first .selected element. Access the clicked element with this keyword from inside the click event handler.
var groupSelected= $(this).val();
I think groupSelected should be a global variable to hold the previous value and will be changed for the next click .I mean instead of creating in the click as var groupSelected it should be out side of the click listener

Jquery doesn't update an attribute as expected

I have an MVC App and on one of my pages as part of the display I will render one of two partials based on a user selection of a radio button. This bit all works ok, but I have a button on the main form where I need to set/reset values that will be passed to my controller based on the user selection. The button is declared on my main form as:
#Html.GlobalModalAuthorizeButton("Upload Document", "Upload", "Documents", new { serviceUserId = Model.ServiceUser.Id, folderId = Model.CurrentFolderId, viewType = Model.ViewTypes.ToString() }, new { #class = "icon upload btn-primary" })
when this page is initially rendered the viewtype is set to the default view that the user is initially presented with. when the user changes the view the viewtype doesn't seem to get updated. So from the partial that has been loaded I try to set the value to the correct value. Using the Chrome browsers Developer tools if I do the following:
$(this).parent().parent().parent().parent().find($('.upload')).attr('data-url').replace('FileView', 'TreeView');
it returns in the console window the value I want (idea is that i set the value on the button before the user presses it). The trouble is the above doesn't really seem to have changed the data-url attribute on the button so consequently when the controller is hit, 'FileView' is still passed through.
For full attribute:
var new_attr = "/ServiceUser/Documents/Upload?serviceUserId=21&viewType=FileView";
$(this).parent().parent().parent().parent().find($('.upload')).attr('data-url', new_attr);
Or, as #Rup already suggested, you should first get the original attribute value, modify that using replace method and then reassign the new_attr.
jQuery got a special method to read and write data attributes:
var uploadButton = $(this).parent().parent().parent().parent().find('.upload');
var currentUrl = uploadButton.data('url');
uploadButton.data('url', currentUrl.replace('FileView', 'TreeView'));

Pass information to bootstrap modal from Angular.js controller

Simplified problem
I have a store. For a product to be included in the store there needs to be a shelf for it. So, to add a new product to the store the workflow is:
Add a shelf
Add product to that shelf
(The workflow can not be changed)
Realization
The shelf is realized by a row in a table, which in turn is controlled by an Angular.js controller (each shelf is an object in an array). To add an product the user selects "create product" in a drop-down menu that is present on each row. This will show an bootstrap modal where I have from a controller added a tab for each product that is possible to add (since each product needs configuration :) ) , then when the user presses a "create" button in the modal a JavaScript method is called interfacing a REST interface to add the product (the UI is updated by a Socket.io event send from the server when the product has been added successfully.
Problem
The JavaScript method (CreateProduct) needs to now what row (R) was affected as well as what tab (T) was selected so that the "onclick" method for the button is CreateProduct(R, T);
My current solution is pretty ugly imho, I have two global variables for R and T, then I use jQuery to capture show event and tab event from the modal, the link in the dropdown has a field "data-row-id" that is identifying the row
HTML (Jade) snippet from dropdown menu:
a(data-toggle="modal", href="#createProduct", data-row-id="{{row.RowID}}") Create Product
JavaScript:
var R = null;
$('#productModal').on('show.bs.modal', function(e) {
R = $(e.relatedTarget).data('row-id');
});
var T = null;
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
T = e.target.text;
});
I hope there is a better solution to this, I probably am just thinking a bit upsidedown due to inexperience with Angular.js , perhaps there is a way to pass these through the model? Perhaps add these to the modal controller, but then, how to pass the row? My dream would be something like this on the button code
button(type="button", class="btn btn-default", data-dismiss="modal", ng-click="storeCtrl.CreateProduct({{modalCtrl.shelf, modalCtrl.Product)") Create Product
I found a better way (at least I don't need to use jQuery) using ModalService
I created a CreateProductModalController having a variable selectedProduct, this is set on a ng-click event in the tab
ul(class="nav nav-pills", id="tabContent")
li(ng-repeat="prod in products", ng-class="{active: $index == 0}", ng-click="activateTab(prod.name)")
a(href="#{{prod.name}}", data-toggle="tab") {{prod.name}}
The ModalService is called with the rowID that was clicked.
The only problem I have now is that all must be in $scope, I want it to be more encapsulated

Creating a language dropdown menu with reroute and local storage

I have a web application using Umbraco (MVC .NET) that has (for now) only two roots. They are named "English" and "Swedish". English is the default webpage and Swedish should be optional for the user. In order for the user to be able to change language I display them in a dropdown menu using Razor:
#{
List<SelectListItem> languages= new List<SelectListItem>();
foreach (var language in Model.Content.Siblings())
{
languages.Add(new SelectListItem
{
Text = language.Name,
Value = language.Url
});
}
#Html.DropDownList("LanguageSelect",new SelectList(languages,"Value","Text"), htmlAttributes: new { id = "LanguageSelect" });
}
This properly outputs the names of the roots at root level. Now using javascript i reroute using onchange:
document.getElementById("LanguageSelect").onchange = function() {
window.location.href = this.value;
};
This works for going from one language to another. Now the hard part starts: because this dropdown exists in my master template inherited by all views, when a new view is loaded, everything from the template is reloaded. Therefor the dropdown is reloaded and the selected language is lost in the dropdown. Instead of looking at the URL for which value should be set in the dropdown I wanted to use local storage. So I tried setting this in the onchange function for the dropdown:
localStorage.setItem("LanguageSelectStoredUrl", this.value);
But this saves the URL. I would like to save the text aswell, i.e. "Swedish" and just set the current value of the dropdown to the stored value. This should work, right? If so how do I do that? Any reasons not to?
Another reason why I wanted to do it this way is because I want the user in a later session not having to choose language again by using:
$(document).onload(function(){
if(localStorage.getItem("LanguageSelectStoredValue") != null){
// Check if the dropdown value is equal to the stored value
// If so do nothing
// Else reroute to locally stored URL
But as I don't know how to store the text value of the dropdown I cant do this and maybe there is a more fitting event to hook on to than onload?
Here is a summary of my questions that I need help with in order to fulfill the task at hand:
How do I get the text of the selected dropdown item?
How do I programmaticly select one of the values in the dropdown?
Is there a better event to hook on to than onload?
Anything else that I might have overlooked?
Thanks!
To get the selected text of a drop down list:
JavaScript:
var languageSelect = document.getElementById("LanguageSelect");
var selectedText = languageSelect.options[languageSelect.selectedIndex].text;
jQuery:
$('#LanguageSelect option:selected').text();
Using $("#LanguageSelect").val('ValFromDdl'); will allow you to select an item in a drop down list.
You can use $(document).ready to read your storage object and initialize the drop down list.

find ASP.NET dynamically created radio button selected value using javascript

I use VS2010,C# to develop my ASP.NET web app, I'm creating a vote page for my users, I get some questions from my DB, each question is displayed in a dynamically created row, also there are 5 options (very good, good, bad....), user must select one. I use following code to create a radio button for each choice, of course all five radio buttons of a row have a unique group name:
tr = new TableRow();
tr.HorizontalAlign = HorizontalAlign.Right;
tc = new TableCell();
tc.HorizontalAlign = HorizontalAlign.Center;
RadioButton r = new RadioButton();
r.Text = "";
r.GroupName = i.ToString();
tc.Controls.Add(r);
tr.Cells.Add(tc);
tc = new TableCell();
tc.HorizontalAlign = HorizontalAlign.Center;
r = new RadioButton();
r.Text = "";
r.GroupName = i.ToString();
tc.Controls.Add(r);
tr.Cells.Add(tc);
// five radio buttons are created in each row
now I'm going to find user choices, I think the best approach is using a JavaScript function to find selected value for each question, then perform the calculations, how can I do so? I don't want to use AutoPostback for radio buttons as it can be really slow,
thanks
Just add a submit button. In the submit event handler, use c# to browse through the controls and get the selected values. You don't need JavaScript for this.
Update
Basically, you will need to assign some similar names to your dynamically generated controls. I.E. Question1Radio1, Question1Radio2, etc..
After that you can use the Request.Form method to retrieve the values from the radio buttons by calling Request.Form("Question1Radio1"), Request.Form("Question1Radio2"), etc.. in your submit handler.

Categories

Resources