Asp Net 1.1 - Issue Accessing Asp DropDownList with Jquery - javascript

I have a bunch of dropdownlists that are filled dynamically with Jquery but i'm trying to convert them to Asp:DropDownLists instead of actual pure HTML select dropdowns so i can access and manipulate their values directly from the server side more easily (so i can save the Session value) instead of having to use the Request.Form command. Since the Asp:DropDownList class has it's particularities, i had to adapt the code i had including the Javascript/Jquery functions which access the drops and fill them (all of their ids share a similar nomenclature but with a different number at the end). However, when i try to access the ID, this doesn't seem to work:
$('#<%= select_plan_'+i+'.ClientID %>')
I always seem to get this compilation error:
CS1026: ) expected
The "i" has to be there since i'm using a "for" loop to go through all of the drops and fill them. Like i mentioned, all of the drops's ids share a similar nomenclature but with a different number at the end.
This is how one of the drops is defined:
<asp:DropDownList runat=server id="select_plan_4" onchange=ChangePrice(this,4);SetSelectedText(4); name=select_plan_4>
...
</asp:DropDownList>
Anyway, how can i get over this issue? Is there a better alternative? Thanks in advance!
UPDATE: Js function code added.
function ChangePlan(n, control) {
family = decodeURIComponent(window.location.search).split('=')[1];
$('#select_plan_'+n).find('option').remove().end();
for (var i = 1; i < data.length-1; i++) {
var aux = data[i].split(';');
if (aux[0] == family) {
var html='<asp:ListItem Value="'+aux[control]+'" Text="'+aux[1]+'" >'+ aux[1] +'</asp:ListItem>';
$('#select_plan_'+n).append(html);
}
}
}

Have a look at the rendered HTML of your page in the Dev Tools for your browser (e.g. by pressing F12 when using Chrome). You'll see that usually the controls, when they're actually rendered, don't have the IDs you've assigned them.
You need to find the actual ID of the rendered control. For a good description of a few techniques for doing this, check out this blog post.

Related

parse javascript variable in .net getElementById?

I feel like I already know the answer to this is going to be "not possible" but just in case.
Let's say I have this javascript function used to read .net webform field's value:
function getById(theId) {
return document.getElementById(theId).value;
}
which I can call like this:
getById("<%=txtField1.ClientID%>");
Ok, that works fine.
But it is a given that .ClientID is always going to be in there, which means this function could be whittled down, but only if it is possible to represent the form field as a variable by itself. Something like this:
function getById(fieldName) {
return document.getElementById(<%= + fieldName + .ClientID%>).value;
}
to be called like this (much cleaner)...
getById("txtField1");
Is this possible?
Well yes and no/maybe.
Yes Part:
JS order of operations supports the ability to append strings before the get element call. For example if I had a textbox with id "searchTerm" then I could do this in js and be absolutely fine:
var check = document.getElementById('search' + 'Term').value;
NO Part: unless webforms differs significantly than what I remember way back when, that original function you have there is created to specifically get values when js is called inline and is about as optimized as you are going to get for that action. Once the page is loaded all of those server side variables will no longer be available for javascript and you would have to use the true client side elements IDs. Once workaround I suppose is to add onClick action to pass the client side ID such like so
<input type="text" onClick="WhatIsLove(this.id)" value="BabyDontHurtMe" id="Sing">

Can't access object in jquery (prevObject?)

A function in my WP plugin has just randomly (as far as I can tell) stopped working.
Here's the code in question:
window.send_to_editor = function(html) {
var classes = jQuery('img',html).attr('class');
var items = classes.split(" ");
... more stuff here
}
I've confirmed that the html variable is indeed an img html tag. Here's what firebug shows when I do a console.log of the object (console.log(jQuery('img',html));):
Object[]
context -> undefined
jquery -> "1.11.2"
length -> 0
prevObject -> Object[img.alignnone.size-full.wp-image-1234 name.jpg]
And the error it shows is classes is undefined.
I figure there's something wrong with the object I get, but this used to work recently and I'm not aware of any changes in the site that could have caused this.
I'd appreciate any input on this.
EDIT:
More info. This happens with two plugins which are supposed to be unrelated (made by different people). It happens when, after uploading an image to the server (or selecting a previously uploaded picture) you try to insert it into the post.
As I said before this error has appeared out of nowhere, it was working as intended a couple days ago. The only thing I can think of that has changed since then is the domain name, but I can't see how that could be related.
The jQuery selector always returns a jQuery object, but when the length is 0 then no elements were found matching the selector that you provided. In your example you've confirmed that nothing is selected as the length of the jQuery object is 0. Perform a check whether an element was selected like this:
var $els = jQuery('img',html),
classes;
if ($els.length) {
classes = $els.attr("class");
}
Keep in mind that your DOM query is limited by what you pass in as the html parameter. If you simply want to find the images on the page do: var $els = jQuery('img');
I finally managed to fix this; the key was parsing the html string variable into proper HTML, using jQuery.parseHTML(). Thanks to everyone who helped!

Adding Javascript variables to HTML elements

So, I have some code that should do four things:
remove the ".mp4" extension from every title
change my video category
put the same description in all of the videos
put the same keywords in all of the videos
Note: All of this would be done on the YouTube upload page. I'm using Greasemonkey in Mozilla Firefox.
I wrote this, but my question is: how do I change the HTML title in the actual HTML page to the new title (which is a Javascript variable)?
This is my code:
function remove_mp4()
{
var title = document.getElementsByName("title").value;
var new_title = title.replace(title.match(".mp4"), "");
}
function add_description()
{
var description = document.getElementsByName("description").value;
var new_description = "Subscribe."
}
function add_keywords()
{
var keywords = document.getElementsByName("keywords").value;
var new_keywords = prompt("Enter keywords.", "");
}
function change_category()
{
var category = document.getElementsByName("category").value;
var new_category = "<option value="27">Education</option>"
}
remove_mp4();
add_description();
add_keywords();
change_category();
Note: If you see any mistakes in the JavaScript code, please let me know.
Note 2: If you wonder why I stored the current HTML values in variables, that's because I think I will have to use them in order to replace HTML values (I may be wrong).
A lot of things have been covered already, but still i would like to remind you that if you are looking for cross browser compatibility innerHTML won't be enough, as you may need innerText too or textContent to tackle some old versions of IE or even using some other way to modify the content of an element.
As a side note innerHTML is considered from a great majority of people as deprecated though some others still use it. (i'm not here to debate about is it good or not to use it but this is just a little remark for you to checkabout)
Regarding remarks, i would suggest minimizing the number of functions you create by creating some more generic versions for editing or adding purposes, eg you could do the following :
/*
* #param $affectedElements the collection of elements to be changed
* #param $attribute here means the attribute to be added to each of those elements
* #param $attributeValue the value of that attribute
*/
function add($affectedElements, $attribute, $attributeValue){
for(int i=0; i<$affectedElements.length; i++){
($affectedElements[i]).setAttribute($attribute, $attributeValue);
}
}
If you use a global function to do the work for you, not only your coce is gonna be easier to maintain but also you'll avoid fetching for elements in the DOM many many times, which will considerably make your script run faster. For example, in your previous code you fetch the DOM for a set of specific elements before you can add a value to them, in other words everytime your function is executed you'll have to go through the whole DOM to retrieve your elements, while if you just fetch your elements once then store in a var and just pass them to a function that's focusing on adding or changing only, you're clearly avoiding some repetitive tasks to be done.
Concerning the last function i think code is still incomplete, but i would suggest you use the built in methods for manipulating HTMLOption stuff, if i remember well, using plain JavaScript you'll find yourself typing this :
var category = document.getElem.... . options[put-index-here];
//JavaScript also lets you create <option> elements with the Option() constructor
Anyway, my point is that you would better use JavaScript's available methods to do the work instead of relying on innerHTML fpr anything you may need, i know innerHTML is the simplest and fastest way to get your work done, but if i can say it's like if you built a whole HTML page using and tags only instead of using various semantic tags that would help make everything clearer.
As a last point for future use, if you're interested by jQuery, this will give you a different way to manipulate your DOM through CSS selectors in a much more advanced way than plain JavaScript can do.
you can check out this link too :
replacement for innerHTML
I assume that your question is only about the title changing, and not about the rest; also, I assume you mean changing all elements in the document that have "title" as name attribute, and not the document title.
In that case, you could indeed use document.getElementsByName("title").
To handle the name="title" elements, you could do:
titleElems=document.getElementsByName("title");
for(i=0;i<titleElems.length;i++){
titleInner=titleElems[i].innerHTML;
titleElems[i].innerHTML=titleInner.replace(titleInner.match(".mp4"), "");
}
For the name="description" element, use this: (assuming there's only one name="description" element on the page, or you want the first one)
document.getElementsByName("description")[0].value="Subscribe.";
I wasn't really sure about the keywords (I haven't got a YouTube page in front of me right now), so this assumes it's a text field/area just like the description:
document.getElementsByName("keywords")[0].value=prompt("Please enter keywords:","");
Again, based on your question which just sets the .value of the category thingy:
document.getElementsByName("description")[0].value="<option value='27'>Education</option>";
At the last one, though, note that I changed the "27" into '27': you can't put double quotes inside a double-quoted string assuming they're handled just like any other character :)
Did this help a little more? :)
Sry, but your question is not quite clear. What exactly is your HTML title that you are referring to?
If it's an element that you wish to modify, use this :
element.setAttribute('title', 'new-title-here');
If you want to modify the window title (shown in the browser tab), you can do the following :
document.title = "the new title";
You've reading elements from .value property, so you should write back it too:
document.getElementsByName("title").value = new_title
If you are refering to changing text content in an element called title try using innerHTML
var title = document.getElementsByName("title").value;
document.getElementsByName("title").innerHTML = title.replace(title.match(".mp4"), "");
source: https://developer.mozilla.org/en-US/docs/DOM/element.innerHTML
The <title> element is an invisible one, it is only displayed indirectly - in the window or tab title. This means that you want to change whatever is displayed in the window/tab title and not the HTML code itself. You can do this by changing the document.title property:
function remove_mp4()
{
document.title = document.title.replace(title.match(".mp4"), "");
}

Retrieve all data from LocalStorage (without knowing the key name)

I'm looking for a way to get all the information out of localStorage. The trouble I'm having is I don't know what the data will be as it is user generated.
So here what happens, a user inputs some text, it uses javascript to manipulate it depending on what check boxes they have ticked on the input form. these boxes are for symbols for example if they tick the box for # then the text + the #At (symbol then word) will be placed in local storage with the other half of the pair as a Boolean (1 or 0 in this case) representing whether its been checked.
the exact pair would look like this:
someString..#At        | 1
someString..#Hash     | 0
etc.
It should also be noted that this is intended to be used in a Chrome Extension so compatibility in other browsers is not a requirement for me (although it could well be usful to others reading this as I can't find anything else covering it on the web).
So, if there anyway I can extract all the values in localStorage without actually knowing the name of each key?
Is it possible to use any kind of wild card or regular expression maybe, I have tried this but should make it work using a for loop.
Thanks,
Wez
window.localStorage.key is the solution.
Example:
var i = 0,
oJson = {},
sKey;
for (; sKey = window.localStorage.key(i); i++) {
oJson[sKey] = window.localStorage.getItem(sKey);
}
console.log(oJson);

Get User control id within user control at runtime

is it possible to get the ID assigned to User Control from the control using javascript or jquery.
Thanks
What ASP.NET normally does is prefix your control's ID with a string that it uses to determine where in ASP.NET's control tree your actual control resides.
With that in mind, what I normally do is to use jQuery's 'ends with' selector to get the full ASP.NET-parsed ID at runtime.
Something like:
// get a handle on your original control
var myControl = $('[id$="<myOriginalId>"]');
// and then access it's properties
var myRuntimeId = myControl.eq(0).attr('id');
As you can most probably imagine, that's not going to cut it when you've got UserControls with the same ID used in different places of the form. I just jump in and put in some tweaks here and there (probably with using the .eq() function) to suit my business need.
You could put a class on the usercontrol, and then use something like $(".myUC").attr("id")
This might help you to look at it from a different point of view:
In .Net you can get the generated ID by using myControl.ClientID.
If you put that in a javascript variable - I know it's not neat - you can then easily fetch it.
<!--mypage.aspx-->
<script>
var myIdVar = "<%=myControl.ClientID%>";
if(myIdVar == "foo")
{
alert("bar");
}
</script>

Categories