Finding ID with Multiple ASP UserControl using JavaScript - c#

I have an ASP usercontrol name ListItem. Each ListItem has 2 ASP controls on it : a label lblIndex and a button btnAction
On my page, I load 10 ListItem into a panel and set lblIndex on each ListPanel an appropriate index.
ListItem 1 : lblIndex.value = '#1'
ListItem 2 : lblIndex.value = '#2'
...
ListItem 10 : lblIndex.value = '#10'
How do I write Javascript that, each time when I click the button on a ListItem, the appropriate lblIndex's value will appear(through an Alert()). I.e. when I click the btnAction on the 2nd ListItem, the text '#2' will come out.
Thank you

to facilitate your life, use jQuery when writing javascript.
in that in mind, let's assume that your ListItem control outputs a ul list with an id... make sure that you had a class, let's imagine that you named list-item so at the end you will have:
<div id="ListItem_1" class="list-item">
...
</div>
Now, you say you some sort of a button inside that list...
<div id="ListItem_1" class="list-item>
<input id="ListItem_1_Button_1" type="button" value="I'm a Button" />
</div>
Once again, explicit give that button a class name, for example: inside-button
I don't know how you have all texts, but I'll again assume that will be a hiiden field with the text to alert ...
some thing like:
<div id="ListItem_1" class="list-item>
<input id="ListItem_1_Button_1" type="button" value="I'm a Button" />
<input id="ListItem_1_Hidden_1" type="hidden" class="text" value="Text to run" />
</div>
and assuming you have 10 lists with several buttons you can simple write:
$(".inside-button").bind("click", function() {
// a button was clicked, let's do something
});
that 1st line says: "Foreach DOM element that has a class name of inside-button attach the click event"
and inside you fire what you want to do
From your question, you only want to perform something on that list:
$(this) // that will be the .inside-button element, so the Button
.closest(".list-item") // get me the closest DOM element with a class name of "list-item"
.find(".text") // find the DOM elemnt with the class name "text"
.val(); // let's see what value that element has
then you can alert() it.
All together:
$(".inside-button").bind("click", function() {
// a button was clicked, let's do something
var txt = $(this).closest(".list-item").find("text").val();
alert( txt );
});

Related

Click on the Checkbox inside the Label or Div

I want to create the two methods, one for clicking on the specific checkbox and second for de-selecting the same checkbox.
I was trying to using the XPath and ID but unable to do so.
Please tell me how it can be done. Here is the HTML:
IJavaScriptExecutor js = (IJavaScriptExecutor)_driver;
js.ExecuteScript("window.scrollBy(200,document.body.scrollHeight)", "");
var mileageTextbox = driver.FindElement(By.Id("VehicleMileageMax"));
mileageTextbox.SendKeys("9500");
var checkBox = driver.FindElement(By.XPath("//label[text()='financial-check-all-8']::input[#type='checkbox'"));
Thread.Sleep(2000);
checkBox.Click();
Element is not visible
HTML code :
<input id="financial-check-all-8" type="checkbox" selected="filter.isDisabled" ng-model="filter.isDisabled" ng-change="vm.emptyFilterValue(filter);" class="ng-pristine ng-untouched ng-valid ng-empty" aria-invalid="false" tabindex="44"> <label for="financial-check-all-8" id="enabled-8" class="form-checkbox-label"></label>
You can try with this code :
//input[starts-with(#id,'financial-check-all') and #ng-model='filter.isDisabled']
Code :
var checkBox = driver.FindElement(By.XPath("//input[starts-with(#id,'financial-check-all') and #ng-model='filter.isDisabled']"));
checkBox.Click();
EDIT :
As per the Shared HTML you can use this xpath:
try to wait also before clicking on it, Just try with Thread.Sleep(4000); , If that works then we can easily replace that with webdriverwait.
//label[#for='VehicleMileageMax']/../preceding-sibling::div/descendant::input
or with this xpath :
//label[#for='VehicleMileageMax']/../preceding-sibling::div/descendant::label

get text from textarea and copy it in input onclick button

I'm using ASP MVC 4 Razor , I want to get text from a textarea and copy it in an input when click on button.
here is my code view
<textarea name="resultSearch" id="resultSearch" rows="10" class="form-control">
#if (ViewBag.highlightedText != null) {
foreach (var person in ViewBag.highlightedText) {
#person
}
}
</textarea>
So if I'm not misunderstanding the question you just need to write a little JavaScript. You need to make sure that your textarea, button, and input both have an id attribute. Let's assume the following:
textarea: resultSearch
button: myButton
input: myInput
With those assumptions you might write the following JavaScript (jQuery is required):
$('#myButton').on('click', function() {
$('#myInput').val($('#resultSearch').val());
});

Div elements on click fires for the first element only

I am listing my data in an ItemTemplate.Then inside the ItemTemplate, i have two div tags as follows:
<ItemTemplate>
<div id="contentdiv">
<h4 id="titleresult"><%# Server.HtmlEncode(Eval("Name").ToString())%></h4>
</div>
<div id="showclick" class=hideAll>
<p class="brief"><%# Server.HtmlEncode(Eval("LegalName").ToString())%></p>
<p class="brief"><%# Server.HtmlEncode(Eval("FirstName").ToString())%></p>
<p><%# Server.HtmlEncode(Eval("LastName").ToString())%></p>
</div>
</ItemTemplate>
Then i have the css to define the hideAll class so that when the page loads, the data in this div tag is hidden until the user clicks on the contentdiv link.
.hideAll { display:none }
.displayAll { display:block; top:0px}
Then finally i have the javascript part for firing the click event.
<script type="text/javascript">
function showResults(UserID) {
var contentdiv= document.getElementById('contentdiv');
var showclick = document.getElementById('showclick');
<%
long id =0;
DataAccess dataAccess = new DataAccess();
Data = dataAccess.GetCounterParty(id);
%>
var UserID = <%=dataAccess.GetCounterParty(id) %>
contentdiv.style.visibility = "visible";
$(showclick).removeClass('hideAll');
}
</script>
The UserID is the id of every element in the list. The problem is, the click affects only the first element no matter which other element i click on the list.
In html id is used to refer to one element.
If you use it multiple times the browser would default to the first element.
You should use a class selector. Something like:
$(".contentdiv").click(function(){
$(this).next().removeClass('hideAll');
});
Here is a working example. I used toggleClass though, it seems more appropriate to me.
An id is a unique identifier, you cannot have two or more things on the same page with the same identifier and expect things to work properly. Make your identifiers unique, and bind to the click event using a class selector instead.
you should use class instead of id, id are unique, which only exist in 1 page, class can exist in multple div
some idea for u
html
<div class="showclick hideAll">
script
$('.showclick').on('click', function(){
$(this).toggle(); //toggle to show or hide, can be any element u want to toggle instead of this
});

Pass the jqueryui selected list items to the code behind

I am using the jquery ui selectable plugin on my website. I have close to 7 different lists with multi select's on the same page, all using the above plugin.
Once the user selects a particular listitem... how do i pass those selected items back to the code-behind ?
This is how i have displayed my list's on the page...
<div>
<ol class="selectable" id="wlList" runat="server" clientidmode="static">
</ol>
</div>
And this is how I have generated the list items from the database in the code behind...
wl.ToList();
foreach (var w in wl)
{
HtmlGenericControl li = new HtmlGenericControl("li");
li.Attributes.Add("class", "ui-widget-content");
li.Attributes.Add("value", w.UserID.ToString());
li.InnerText = w.FirstName;
wlList.Controls.Add(li);
}
Grateful for the help
One possible approach is storing selected values in a hidden input and then simply reading and parsing its value on the server..
Check this fiddle which is based on jQuery UI Selectable Serialize Demo.
What you need is to add hidden input(s) to your form:
<input type="hidden" id="wlListValue" name="wlListValue" />
Then implement selectable change handler like this:
$('.selectable').selectable({
stop: function(event, ui) {
var result = '';
$(".ui-selected", this).each(function() {
result += $(this).val() + ';';
});
$('#wlListValue').val(result);
}
});
And then just read selected values after postback:
var selectedValues = Request["wlListValue"].Split(";".ToCharArray(),
StringSplitOptions.RemoveEmptyEntries);

Best way to display a group/selection of radiobuttons from the choice of a single radiobutton?

I have a form which for some questions would ask if something was included and if it isn't to supply a reason.
So I need a radio button which records to the database it's value like normal which I have setup with a RadioButtonFor and if "No"(false) is selected then a group/list of other radiobuttons will display.
Ofc this is just the ideal solution if this method isn't feasible then another solution would be to maybe a if statement in the controller so that if that main radiobutton has a value of "Yes"(true) then it would set the values of x, y and z radiobuttons to "No"(false) when it records the form to the database.
These are the 2 ideas I have on how to get the same end result but for the 1st idea I think the easiest way to perform it's function would be in jquery which I'm fairly new at so would struggle to come up with how to do it
For the 2nd idea it's 1 not ideal and 2 I'm not sure how I would then reference those radiobuttons/code the if statement to do said task.
Any other ideas would also be welcome but hopefully with help on how to implement them.
Well, this may sound overkill, but I would go with both solutions. You need the javascript script side code to do it right from a presentation standpoint - and you need the server-side code to do the validation right too.
If you implement only the client-side validation, how the system will behave if a browser has no support to javascript, or if it is just disabled? You cannot take javascript support for granted...
OTOH, you would offer a best user experience if you added that client-side functionality you're talking about...
And about your doubt of how to do the server-side validation: that's easy with ASP.NET MVC - on load, just set the same ViewData entry/ViewModel property that you have read during post.
Edit So let's talk about a complete solution.
Again, I'm not sure I understood what you need here. You're talking about radiobuttons, but you also seem to think you'll be able to control them individually (many radios binding to many fields). That's not usually the case - a group of radiobuttons is normally bound to the same field, with each radiobutton meaning a different value (so exactly like a single dropdown list). Of course, that does not mean your database must behave in the same way...
See this example:
<% using(Html.BeginForm("HandleForm", "Home")) { %>
Select your favorite color:<br />
<%= Html.RadioButton("favColor", "Blue", true, new { id = "rbColorBlue", class = "favColor" }) %> Blue <br />
<%= Html.RadioButton("favColor", "Purple", false, new { id = "rbColorPurple", class = "favColor" })%> Purple <br />
<%= Html.RadioButton("favColor", "Red", false, new { id = "rbColorRed", class = "favColor" })%> Red <br />
<%= Html.RadioButton("favColor", "Orange", false, new { id = "rbColorOrange", class = "favColor" })%> Orange <br />
<%= Html.RadioButton("favColor", "Yellow", false, new { id = "rbColorYellow", class = "favColor" })%> Yellow <br />
<%= Html.RadioButton("favColor", "Brown", false, new { id = "rbColorBrown", class = "favColor" })%> Brown <br />
<%= Html.RadioButton("favColor", "Green", false, new { id = "rbColorGreen", class = "favColor" })%> Green
<%= Html.RadioButton("favColor", "Other", false, new { id = "rbColorOther", class = "favColor" })%> Other
<div id="divOtherColorText" style="display: block">
Describe the color you want here:<br />
<%=Html.TextArea("otherColorText", new { id = "taOtherColor" }) %><br />
</div>
<% } %>
This will bound to a single controller parameter, favColor, with a default value of "Blue". See that, for convenience, we're assigning a distinct client-side id for each radiobutton (rbColorBlue, rbColorGreen and so forth). That means that you'll be able to treat each radiobutton individually in your jQuery code, even if they represent a single value to the server-side controller.
Talking about the server-side code, that's how the action will look like:
public class HomeController : Controller
{
public ActionResult HandleForm(string favColor, string otherColorText)
{
// Add action logic here
// If you want to have a separated field for your database,
// just do something like that:
MyDbFacade.BlueColorField = (favColor == "Blue");
MyDbFacade.GreenColorField = (favColor == "Green");
...
return View();
}
}
(Of course, you could also work with a ViewModel, but I'll not talk about that option here.)
Back to client-side. Let's suppose you don't want to show taOtherColor, unless the user selects the rbColorOther radiobutton. The jQuery code would be something like this:
$(document).ready(function() {
// If user selects any radiobutton:
if ( $('#rbColorOther:checked').length > 0) {
$("#divOtherColorText").show();
} else {
$("#divOtherColorText").hide();
}
});
I guess that would be it. Let me know if I have missed something... :-)
I would go with your first solution. Render both groups of radio buttons on the page but hide the second group with css. Then set some onclick events on the radio buttons in your first group to show/hide the second group depending on which one is clicked.
I think it is easier to just write the html for the radio buttons by hand because of the onclick handlers you are writing, but you could probably manage it using RadioButtonFor as well.
So your yes/no would look like this:
<input type="radio" name="yesNo" id="yes" onlclick="$('#other-options').hide();' value='true' <%: Model.YesNo ? "checked='checked'" : "" %>/><label for='yes'>Yes</label>
<input type="radio" name="yesNo" id="no" onlclick="$('#other-options').show();' value='false'<%: !Model.YesNo ? "checked='checked'" : "" %>/><label for='no'>No</label>
Your other options would look like this:
<div id='otherOptions' <%: Model.YesNo ? "style='display: none;'" : "" %>>
<input type="radio" name="XYesNo" id="xyes" value='true'/><label for='xyes'>X Yes</label>
<input type="radio" name="XYesNo" id="xno" value='false'/><label for='xno'>X No</label>
<input type="radio" name="YYesNo" id="yyes" value='true'/><label for='yyes'>Y Yes</label>
<input type="radio" name="YYesNo" id="yno" value='false'/><label for='yno'>Y No</label>
<input type="radio" name="ZYesNo" id="zyes" value='true'/><label for='zyes'>Z Yes</label>
<input type="radio" name="ZYesNo" id="zno" value='false'/><label for='zno'>Z No</label>
</div>
In your action method ignore any x,y,z values if the first YesNo was true :
if(model.YesNo){
//persist false values for x,y,z
} else {
//check model for values of x,y,z
}
Well I figured out the simpliest way to get the controller to sort out the validation which was
if (wd.AppTher == true)
{ wd.AppTherRea = 0; } this is the example for a drop down and for another radiobutton it would be instead of "0" or whatever value u want for the drop down for it to be "false" or if you want/have multiple options with int at the db field type then you just set your N/A or w/e value as the = too, for multiple RB or DDL then just add more in between { and }, wd was the value assigned to represent the table and otherwise a viewmodel value could be used.

Categories