All I want to do is write this string "runat='server'"; in javascript. and use that here:
var dropdown = "<td><asp:DropDownList ID='drpid' runat='server' DataSourceID='SqlDataSource1' DataValueField='Id' DataTextField='Text'></asp:DropDownList></td>"
error is this: SyntaxError: missing ) after argument list
ASP.NET is rendering the control inside your string definition.
The output of that <asp:DropDownList> contains newlines, double quotes, and references to javascript functions, so it will definitely make a mess of your javascript string.
Instead, let asp.net render the dropdown somewhere else (it can even be inside an invisible div) like this :
<div id="hiddenthingContainer" style="display:none;">
<asp:dropdownlist /> ... etc
</div>
Then, either use document.getElementById("hiddenthingContainer") or use jQuery or whatever dom library you prefer to get the element.
once you have it, it becomes a simple matter of getting the contents of the hidden container and presto, there's your string.
example using jQuery :
<div id="hiddenthingContainer" style="display:none">
<asp:DropDownList ID='drpid' runat='server' DataSourceID='SqlDataSource1' DataValueField='Id' DataTextField='Text'></asp:DropDownList>
</div>
<script type="text/javascript">
$(document).ready(function(){
var dropdown = $("#hiddenthingContainer").html()
});
</script>
Related
I'm trying make some stuff in jQuery using ASP.NET. But the ID from runat="server" is not the same as the id used in HTML.
I used to use this to get the ID from this situation:
$("#<%=txtTest.ClientID%>").val();
But in this case, it does not work. I'm clueless as to why.
Javascript
/* Modal */
function contatoModal() {
//alert("Test");
alert($("#<%=txtTest.ClientID%>").val());
}
HTML
< input runat="server" id="txtTest" value="test" />
Any tips?
<%= txtTest.ClientID %> should work but not in a separate javascript file where server side scripts do not execute. Another possibility is to use a class selector:
<input runat="server" id="txtTest" value="test" class="txtTest" />
and then:
var value = $('.txtTest').val();
In WebForm / HTML Page....
<asp:TextBox ID="txtUserName" runat="server" Class="form-control"></asp:TextBox>
In Jquery
var UserName = $("[id*=txtUserName]").val();
alert(UserName);
100% Sure its Working for me....
As others have mentioned, you can pass a class selector to jQuery, but that is a bit messy. I prefer to use the jQuery attribute ends with selector. Given that a generated ID is a flattened hierarchy of controls, you can use the "ends with" selector to find your element.
<input runat="server" id="txtText" />
When rendered, the generated ID becomes something like this (if within a masterpage's content place holder):
<input id="ctl00_contentplaceholder_txtText" />
To find this control:
$("input[id$='txtText']")
Take caution when using this within a repeater.
Try putting it into a variable name:
var txtTestID = '#' + '<%=txtTest.ClientID %>';
$(txtTestID).val();
I'm not sure if the <%= likes being inside double quotes. I've always had mixed behaviors when not using the single quote.
When using ASP.NET 4 and the ClientIDMode is set to “Predictable”, you can predict the ID based on hierarchy. Or set it set to “Static”, so asp.net wont mess it up.
ScottGu's article on it http://weblogs.asp.net/scottgu/archive/2010/03/30/cleaner-html-markup-with-asp-net-4-web-forms-client-ids-vs-2010-and-net-4-0-series.aspx
And this is extremely useful when using external JS file scenarios.
As Darin Dimitrov said in his answer:
<%= txtTest.ClientID %> should work but not in a separate javascript
file where server side scripts do not execute.
The solutions that I could find for those are:
<input runat="server" id="txtTest" value="test" class="txtTest" />
Use class instead of ID
Using class you can retrieve the value anywhere. This is one of the best solutions (usually the best)
var value = $('.txtTest').val();
Use ClientID code in the aspx
You can always call ClientID in the aspx, but if you are working with some kind of structure, this isn't the best solution. I like to use this method when I'm testing something.
var value = $('#<%=txtTest.ClientID%>').val();
You can also use ClientID in a external js file with a workaround. IT'S NOT PRETTY, use only if you really need it. I usually do this when I use Telerik.
In the aspx:
var id = <%=txtTest.ClientID%>;
In the js file:
var value = $('#'+id).val();
Use Control.ClientIDMode Property Static
so the HTML becomes
<input runat="server" id="txtTest" value="test" ClientIDMode="Static" />
and the js can call it as it is named of
var value = $('#txtTest').val();
The problem with this solution is that you need to be very careful to avoid duplicity on the ids of your page. Try never use Static mode in a controller.
As states MSDN:
The ClientID value is set to the value of the ID property. If the
control is a naming container, the control is used as the top of the
hierarchy of naming containers for any controls that it contains.
The link of shaans's answer is a awesome place to check extra information about ClientIDMode.
Cleaner HTML Markup with ASP.NET 4 Web Forms - Client IDs (VS 2010 and .NET 4.0 Series)
To avoid issues with rendered ID's, use a class instead. This won't change during rendering:
function contatoModal() {
//alert("Test");
alert($(".txtTest").val());
}
HTML:
< input runat="server" id="txtTest" value="test" class="txtText" />
Adding a css class to the input and then using this class in jQuery to getting the input element will solve the issue.
I have these lines of code:
<span
class="close-modal"
onclick="#Html.Action("SaveNotes", "CallCenter", new { activityId = item.callIdKey, noteText = "test1" })">
×
</span>
Notes: <br />
<textarea name="paragraph_text" rows="5" style="width:90%">
#item.NoteText
</textarea>
I would like to replace test1 from the noteText route variable and instead change it to whatever the value in the <textarea> tag is.
Is there an elegant way of doing this without writing a giant block of jQuery code?
#Html.Action() renders a partial view as an HTML string during page processing (on the server side). It doesn't exist any more in the markup, once the page is sent to the browser. You can't do what you are trying to do this way. At the very least, I'm sure you don't want to render a partial view inside the onclick event of your <span> tag.
Why not instead use an HTML helper for the <textarea> tag? Then you can get whatever value the user typed into it on the server code. You'll want to make the form post itself back to the server on the close-modal element:
<span class="close-modal" onclick="$('form').submit()">×</span>
<form method="post" action="#Url.Action("SaveNotes", "CallCenter", new { activityId=item.callIdKey }">
Notes: <br />
#Html.TextArea("noteText", item.NoteText, new { rows="5", style="width:90%" })
</form>
This assumes you have jQuery already (a common assumption with ASP.NET). You may not need the <form> tags if you already have a form on your page.
A #gunr2171 notes in the comments, the only way to dynamically update a link once it's been rendered to the browser is via some form of client-side scripting, typically JavaScript. In your case, I'd recommend doing something like this:
<span
class="close-modal"
data-href-template="#Url.Action("SaveNotes", "CallCenter", new {activityId = item.callIdKey, noteText="{note}"})"
>
×
</span>
Note: As #HBlackorby notes in his answer, you shouldn't be using #Html.Action() here; I assume you meant #Url.Action().
This way, your JavaScript has a template (data-href-template) that it can work against with a clearly defined token ({note}) to replace, instead of needing to parse the URL in order to identify where the previously replaced text is. Otherwise, you potentially end up in a scenario where you type e.g. CallCenter into your <textarea /> and it's now an ambiguous reference that you can't just blindly replace. Or, worse, you type 'a' and it's really ambiguous.
If you are already using jQuery on your site, the actual replacement might be done using something along the lines of:
$(document).ready(function () {
$('span.close-modal').click(function() {
var noteInput = $('textarea[name="paragraph_text"]');
var encodedNote = encodeURI(noteInput.text());
var template = $(this).data("href-template");
var targetUrl = template.replace("{note}", encodedNote);
window.location.href = targetUrl;
});
});
You can also do this without jQuery, obviously—and should if you're not already depending on it. The point is to illustrate that this doesn't necessarily need to be a "giant block of jQuery code". In fact, this could be done in just a few lines—and probably should be. I deliberately broke it out into multiple steps and variables for the sake of readability.
So, in a page there is a div with id #SCPcustomOptionsDiv. I want to move that div to a right place where it should be.
I tried using jQuery as well as native javascript, but can't get this to work. When i try to run the script using debugger, the result is null. here is the script.
jQuery('#SCPCustomOptionsDiv') // return []
document.getElementById('SCPCustomOptionsDiv') // return null
and here is some snippet of the source
<span style="display:none;" class="scp-please-wait"><img src="http://optimallyorganic.webmate.co/skin/frontend/base/default/images/scp-ajax-loader.1413318518.gif" class="v-middle" alt="" /> Loading... </span>
<div id="SCPcustomOptionsDiv"></div>
</fieldset>
<script type="text/javascript">
$$('#product-options-wrapper dl').each(function(label) {
label.addClassName('last');
});
</script>
is camelcase id matter when selecting the div using javascript?
The C in SCPcustomOptionsDiv is lowercase in your HTML and uppercase in your script. IDs are case-sensitive.
SCPcustomOptionsDiv
^
vs.
SCPCustomOptionsDiv
^
Use SCPcustomOptionsDiv in your script not SCPCustomOptionsDiv
jQuery('#SCPcustomOptionsDiv')
document.getElementById('SCPcustomOptionsDiv')
I'm trying make some stuff in jQuery using ASP.NET. But the ID from runat="server" is not the same as the id used in HTML.
I used to use this to get the ID from this situation:
$("#<%=txtTest.ClientID%>").val();
But in this case, it does not work. I'm clueless as to why.
Javascript
/* Modal */
function contatoModal() {
//alert("Test");
alert($("#<%=txtTest.ClientID%>").val());
}
HTML
< input runat="server" id="txtTest" value="test" />
Any tips?
<%= txtTest.ClientID %> should work but not in a separate javascript file where server side scripts do not execute. Another possibility is to use a class selector:
<input runat="server" id="txtTest" value="test" class="txtTest" />
and then:
var value = $('.txtTest').val();
In WebForm / HTML Page....
<asp:TextBox ID="txtUserName" runat="server" Class="form-control"></asp:TextBox>
In Jquery
var UserName = $("[id*=txtUserName]").val();
alert(UserName);
100% Sure its Working for me....
As others have mentioned, you can pass a class selector to jQuery, but that is a bit messy. I prefer to use the jQuery attribute ends with selector. Given that a generated ID is a flattened hierarchy of controls, you can use the "ends with" selector to find your element.
<input runat="server" id="txtText" />
When rendered, the generated ID becomes something like this (if within a masterpage's content place holder):
<input id="ctl00_contentplaceholder_txtText" />
To find this control:
$("input[id$='txtText']")
Take caution when using this within a repeater.
Try putting it into a variable name:
var txtTestID = '#' + '<%=txtTest.ClientID %>';
$(txtTestID).val();
I'm not sure if the <%= likes being inside double quotes. I've always had mixed behaviors when not using the single quote.
When using ASP.NET 4 and the ClientIDMode is set to “Predictable”, you can predict the ID based on hierarchy. Or set it set to “Static”, so asp.net wont mess it up.
ScottGu's article on it http://weblogs.asp.net/scottgu/archive/2010/03/30/cleaner-html-markup-with-asp-net-4-web-forms-client-ids-vs-2010-and-net-4-0-series.aspx
And this is extremely useful when using external JS file scenarios.
As Darin Dimitrov said in his answer:
<%= txtTest.ClientID %> should work but not in a separate javascript
file where server side scripts do not execute.
The solutions that I could find for those are:
<input runat="server" id="txtTest" value="test" class="txtTest" />
Use class instead of ID
Using class you can retrieve the value anywhere. This is one of the best solutions (usually the best)
var value = $('.txtTest').val();
Use ClientID code in the aspx
You can always call ClientID in the aspx, but if you are working with some kind of structure, this isn't the best solution. I like to use this method when I'm testing something.
var value = $('#<%=txtTest.ClientID%>').val();
You can also use ClientID in a external js file with a workaround. IT'S NOT PRETTY, use only if you really need it. I usually do this when I use Telerik.
In the aspx:
var id = <%=txtTest.ClientID%>;
In the js file:
var value = $('#'+id).val();
Use Control.ClientIDMode Property Static
so the HTML becomes
<input runat="server" id="txtTest" value="test" ClientIDMode="Static" />
and the js can call it as it is named of
var value = $('#txtTest').val();
The problem with this solution is that you need to be very careful to avoid duplicity on the ids of your page. Try never use Static mode in a controller.
As states MSDN:
The ClientID value is set to the value of the ID property. If the
control is a naming container, the control is used as the top of the
hierarchy of naming containers for any controls that it contains.
The link of shaans's answer is a awesome place to check extra information about ClientIDMode.
Cleaner HTML Markup with ASP.NET 4 Web Forms - Client IDs (VS 2010 and .NET 4.0 Series)
To avoid issues with rendered ID's, use a class instead. This won't change during rendering:
function contatoModal() {
//alert("Test");
alert($(".txtTest").val());
}
HTML:
< input runat="server" id="txtTest" value="test" class="txtText" />
Adding a css class to the input and then using this class in jQuery to getting the input element will solve the issue.
I have some html code rendered on the server side. This is passed to a jsp which renders a javascript-call with this html:
<script type="text/javascript">
window.parent.${param.popup_return}("${helpId}", "${content}");
</script>
content is like
"
This is a <p class="xyz">test</p>
"
My problem is that - according to the quotes in 'content' - the javascript-call is wrong as it is rendered to
<script type="text/javascript">
window.parent.${param.popup_return}("ybc", "This is a <p class="xyz">test</p>");
</script>
Does anyone know how I can solve this (besides manually replacing all quotes)?
Use a JSON encoder to create the encoded strings.
But you'll also have to ensure that the output doesn't contain the sequence </ in string literals, which is invalid in a <script> block (</script is the version that will also break browsers).
Many JSON encoders either by default or optionally will encode to <\/ or \u003C/ to avoid this problem.
I use this:
<div id="result" style="display:none">
${content}
</div>
<script type="text/javascript">
window.parent.${param.popup_return}("${helpId}", dojo.byId("result").innerHTML);
</script>
This seems to work perfectly
You aren't using JSTL here (you originally tagged the question with only JSTL). You are using EL in template text. It get printed plain as-is. You'd like to use JSTL core <c:out> to escape predefined XML entities (which also works for HTML in this particular case, quotes is among the escaped XML entities).
window.parent.${param.popup_return}("<c:out value="${helpId}" />", "<c:out value="${content}" />");
An alternative (if you hate that the JSP syntax highlighter or validator bugs/jerks about nested tags/quotes) is the JSTL function fn:escapeXml():
window.parent.${param.popup_return}("${fn:escapeXml(helpId)}", "${fn:escapeXml(content)}");
Have you tried using single quotes instead of double quotes? i.e. changing "${content}" to '${content}'