How do I get a textbox with particular ValidationGroup in jQuery? - javascript

I have an ASP.NET TextBox ID="txtDate" in my usercontrol. It has ValidationGroup="MyUC" set. Now my UC is inside a Repeater Control. So there will be multiple instances of the same textbox.
I am able to get all textboxes like: $("[id$='_txtDate']");
Each of the txtDate will have a separate ValidationGroup assigned to it, dynamically.
So I want to get a textbox based on the id + ValidationGroup using jQuery / javascript.
How can it be done? Any guidance really appreciated.
Edited based on Josiah's Reply and the way I found:
Sorry, my scenario is kind of complicated to include entire code. In short the textboxes are attached to jquery datepicker and the code below runs when a date is selected. The same handler is attached to multiple textboxes. Here is what I have:
var valgrp="MyGroup"; /*this mygroup is dynamic but keeping static for e.g.*/
var txtdate1 = $("[id$='txtDate']").filter(function(){if(this.Validators!=null){return this.Validators[0].validationGroup == valgrp;}});
var txtdate2 = $("[id$='txtDate']").filter(function(){return this.validationGroup == valgrp;});
alert("date1- " + txtdate1.val()); /*this returns date selected from datepicker*/
alert("date2 " + txtdate2.val()); /*this returns empty*/
Depending on the date I want to do something else. So txtdate1 is currently working for me where I don't have to add class to my textbox. I was playing with the txtdate2 which isn't behaving how I was expecting and so I had to post this question.
Here is a sample test to see this.validationGroup not returned:
$(function () {
$("#btntest").click(function () {
$("[id$='txtDate']").each(function () {
alert(this.validationGroup);//returns undefined
alert(this.Validators[0].validationGroup); //returns "test"
});
});
});
<input id="btntest" type="button" value="button" />
<asp:TextBox ID="txtDate" runat="server" ValidationGroup="test"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Text="*" ErrorMessage="Required." ControlToValidate="txtDate" ValidationGroup="test"></asp:RequiredFieldValidator>

While Josiah's solution didn't work but his idea of attaching class to textbox could have been a potential solution. Since it didn't exactly fit my needs I would answer my own question. Here is the solution I came up with:
var valgrp="MyGroup"; /*this mygroup is dynamic but keeping static for e.g.*/
var txtdate1 = $("[id$='txtDate']").filter(function(){if(this.Validators!=null){return this.Validators[0].validationGroup == valgrp;}});
The above returns me the textbox I am looking for. The key is
this.Validators[0].validationGroup
It gets the validationGroup of the first validator control attached to the textbox (this).

From a few searches, the validation group is stored as a property on the Form Element.
So you can add a class selector like so:
$("[id$='_txtDate']").each(function(){
var group = this.validationGroup,
$this = $(this);
if(!$this.hasClass('validationgroup'))
$this.addClass('validationgroup ' + group);
});
Of course if you have a repeater you will need to run this code each time an row is repeated. But now you can select fields by validation group like this:
$('.validationgroup.[group name]')

I don't use jQuery, but I'd think it would be:
$("#txtDate[ValidationGroup='MyUc']")
since jQuery's selectors are based on CSS. That works with document.querySelector, unless having more that one element with the same id is causing problems.

Related

capture the control ID in a javascript function, by passing parameter

HI so my JS skills are a little rusty but I'm trying to create a few functions so they work on the client side, rather than running server code, here's what I'm trying to do:
I have a drop down control, and a textbox. The textbox is depended on the value from down down and is disabled on page load.
i'm trying to call a function so if YES is selected from dropdown, the textbox will be enabled for text entry. Here's what I'm doing:
function DependentControlByDropDown(sender, Control, DependentControlID) {
try {
var senderControl = sender.selectedOptions[0].text;
var controlEnable = (senderControl == Control);
console.log(controlEnable);
var control = document.getElementById(DependentControlID); this gives me NULL if i do console.log(control)
DependentControlID.disabled = controlEnable; //controlEnable has a value of either TRUE or FALSE but it doesn't work on DependentControlID
}
catch (e) {
alert("DependentControlByDropDown : " + e.message);
}
}
I'm calling this in dropdown like so:
onchange="DependentControlByDropDown(this,'Yes','txtbox1')"
So what's happening here is I get the right value 'Yes', or 'No' I tested it with console.log. The problem is with the dependednt control. If I do console.log(DependentControlID) it is showing me the correct control, but when I try to disabled=false it doesn't work. I also tried document.getElementByID(DependentControlID).disabled=false but that doesn't work either. Any help?!
As we've deduced in the comments of your question, you're using ASP.NET.
This is extremely important to note, because ASP.NET overrides assigned IDs to ensure that they are unique. For example, if you were to do...
<asp:Textbox runat="server" id="txtbox1"></asp:Textbox>
...the rendered HTML may look something like (example)...
<input id="ctl00$MainContent$txtbox1">
Because of this, getElementById("txtbox1") doesn't find anything.
To prevent this from happening, you can add ClientIdMode="static" to your textbox:
<asp:Textbox runat="server" ClientIdMode="static" id="txtbox1"></asp:Textbox>
The rendered HTML will now be the following...
<input id="txtbox1">
NOTE: If you have more than one of these textboxes on the page, for example if you're using it in a GridView or a Repeater, do not use ClientIdMode="static"! It will create duplicate IDs, which are not valid.
The problem is that you were trying to access the textbox via it's ID as text. You need set the disabled attribute on it's node value, which you already have, i.e. control.
Additionally you were trying to set the textbox's disabled attribute to the same value as controlEnable. I've set it to the OPPOSITE of controlEnable
function DependentControlByDropDown(sender, Control, DependentControlID) {
try {
var senderControl = sender.selectedOptions[0].text;
var controlEnable = (senderControl == Control);
console.log('controlEnable',controlEnable);
console.log('DependentControlID', DependentControlID);
var control = document.getElementById(DependentControlID);
console.log('control', control);
control.disabled = !controlEnable;
} catch (e) {
alert("DependentControlByDropDown : " + e.message);
}
}
<input id="txtbox1" />
<select onchange="DependentControlByDropDown(this,'Yes','txtbox1')">
<option value=""></option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>

Focus on First asp:textbox in each bootstrap tab when clicking tab link

i am new to development and started developing a simple asp.net application. I am using bootstrap tabs having some asp labels and textboxes in each. I want focus on first textbox in the tab content when click on that tab. I searched various answers but all are for input fields(exp: input type="text"). can't find any for asp textbox. Any help will be appreciated.
Thanks
ASP.NET TextBoxes are HTML textboxes. By default, the ClientIDMode of controls are Predictable. This means the rendered HTML's id is auto-generated.
// ASP.NET TextBox
<asp:TextBox ID="TextBox1"/>
// Rendered HTML
<input type="text" id="ContentPlaceHolder1_TextBox1_1"/>
What you can do is add ClientIDMode="Static" to the TextBox. This will make the rendered (HTML) id of the input the same as the ID you passed to the TextBox.
// ASP.NET TextBox
<asp:TextBox ID="TextBox1" ClientIDMode="Static"/>
// Rendered HTML
<input type="text" id="TextBox1"/>
You can then target that via JavaScript using the answers you've searched for.
EDIT:
If you don't want to target the TextBoxes via id, you can probably just use CSS classes to tag them like:
<asp:TextBox ID="TextBox1" CssClass="default-focus" />
Then with jQuery:
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
var target = event.target.attributes.href.value;
var $textbox = $(target + ' .default-focus');
$textbox.focus();
});
There is another way to achieve this though its longer but worked for me.
In this solution we can search which navbar tab we are currently in and then set focus to this tabs contents first text box by using its id.
code:
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e)
{
var target = e.target.attributes.href.value;
if (target == "#tab1")
{
$("#<%=txttab1.ClientID%>").focus();
}
else
{
if (target == "#tab2")
{
$("#<%=txttab2.ClientID%>").focus();
}
else
{
if (target == "#tab3")
{
$("#<%=txttab3.ClientID%>").focus();
}
}
}
}

How to show typed item in a textbox into another textbox or div in asp.net and javascript?

I want to show the data of one textbox into another textbox for preview purposes. The data needs to be visible in the same page but inside another textbox or div at the same time the user types in the characters inside the first textbox. Here is what I am trying, but it is not working to achieve my goal:
Asp.net:
<asp:TextBox ID="txtCustomWord" runat="server" Width="300px" ClientIDMode="Static"
placeholder="Enter your custom word (11 Characters)" MaxLength="11"
onkeyup="show(document.getElementById('txtCustomWord').value);"></asp:TextBox>
Javascript:
function show(text) {
document.getElementById("text").innerHTML = text;
}
Passing Things Along
Just use this.value to pass in the value from your current element to simplify things and avoid having to pass in a complete reference to your current element :
onkeyup="show(this.value);">
Then depending on the type of element, you'll want to set the value accordingly. If it is a <div>, you'll want to use the innerHTML property to set the value, otherwise, you'll want to use value if it is an <input> :
function show(text) {
// Use innerHTML for <div> elements, use value for <input> elements
document.getElementById('text').innerHTML = text;
}
Example
You can see all of the necessary code to produce this below :
<form id="form1" runat="server">
<asp:TextBox ID="txtCustomWord" runat="server" Width="300px" ClientIDMode="Static" placeholder="Enter your custom word (11 Characters)" MaxLength="11" onkeyup="show(this.value);"></asp:TextBox>
<div id="text"></div>
</form>
<script>
function show(text) {
document.getElementById('text').innerHTML = text;
}
</script>
You can see an interactive example of the rendered markup this generates here and an example of it in action below :
Since you used jQuery tag, here is a solution with that
$('#txtCustomWord').keyup(function(){
$('#txtDisplay').val($(this).val());
});
https://jsfiddle.net/45z0a32w/1/
You should use the ClientID of the asp:TextBox to access their value in JavaScript: the method signature for show() will be like the following:
Let <Div id="DisplayDiv"></Div> be the div in which we want to display the content;
function show() {
var TextObject = document.getElementById('<%= txtCustomWord.ClientID %>');
if(TextObject != null)
document.getElementById('DisplayDiv').innerHTML =TextObject.value;
}
Specifically:(Javascript function)
var inputs= document.getElementById("txtCustomWord");
inputs.onkeyup = function(){
document.getElementById('text').innerHTML=inputs.value;
}
And remove the onkeyup event from your textbox itself.
Here's a link to a very similar question.
I think it will address your problems.
I tried to use a different event (onchange) but that doesn't apply when you still have focus to the textbox.
While typing in a text input field, printing the content typed in a div

Get variable value from aspx and use it in code behind

I am having a little issue. I have a drop down list which can have multiple values selected. I did that by simply adding a $('#id').attr('multiple','multiple');
I know there is a simple way of accessing variable from code behind to aspx page but now i need the opposite thing, because when I multiselect it, from the code file it doesn't recognize the multiselection but only takes 1 value. So basicly I was hoping for something like
var temp = $('#id').val(); --- It takes the selected items correctly
<% simplevariable= %> = temp;
You can add a HiddenField
<asp:HiddenField ID="hiddenField" runat="server" />
Set its value like
$("#<%=hiddenField.ClientID%>").val($('#id').val())
You can use HiddenField.Value in code behind

Access(checkall, uncheck, middlestate) to dynamic checkbox in asp table via javascript

I'm trying to write privilige group checkbox. Something like
this
So far I made page where I put empty control made by me which looks like this
<fieldset>
<legend><asp:CheckBox ID="GroupName" runat="server" TextAlign="Left" text="test" onclick="checkAll()"/></legend>
<span> <!--class="filterTableSpan"-->
<asp:Table ID="priviligeTable" runat="server" CssClass="groupTable">
</asp:Table>
</span>
</fieldset>
then I fill priviligeTable
CheckBox privilCheck = new CheckBox();
privilCheck.ID = this.ID + "_" + privName; //ID of group
TableCell tc = new TableCell();
tc.ID = this.ID + "_tc" + privName;
tc.Controls.Add(privilCheck);
TableRow tr = new TableRow();
tr.ID = this.ID + "_tr" + privName;
tr.Cells.Add(tc);
this.priviligeTable.Rows.Add(tr);
and now I'd like to make javascript for select all, unselect and mid state to Privilige Group Name checkbox, but I do not know how to access dynamic generated checkboxes. Furthermore I'm a newbie with javascript. I would be pleased if someone could show me a way to solve this problem or rather a direction which I should head to solve by my efforts this problem.
Do these roles come from a list in a database? If so, my instinct would be to avoid the and use instead. The Gridview gives you more built-in functionality including templates that enable you to create all the checkboxes on the go.
However, what you are doing could work too.
I suggest using jQuery - it will make your life a lot easier and ensure your code works across all browsers.
Then you need something like this. This will toggle all the checkboxes on or off.
function checkAll() {
// Find all the checkboxes in the table
var $checkboxes = $('table.groupTable input[type=checkbox]');
if($(this).is(':checked')){
// Check them
$checkboxes.attr("checked","checked");
} else {
// Uncheck them
$checkboxes.removeAttr("checked",);
}
}
I think that should do it. Not sure what you mean by 'mid-state' though. They are either checked or not.
Don't forget that on postback you need to recreate all the checkboxes to be able to read their contents.

Categories