pass parameter to javascript function in asp.net Page - javascript

I want to pass a parameter to a JavaScript function to use in document.getElementByID() as follows:
function PrinGridView(GridViewname)
{
var TableRow= document.getElementByID("GridViewname").getElementsBytagName("tr");
var td= TableRow.item(0).getElementsBytagName("th");
if(td.length>0)
alert('done');
}
In my asp page, I have an image button event:
onClicke="PrinGridView("<%=MyGrideView.ClientID%>")";
but it does not work well.
How can I pass the GridView to a function?
Thanks.

Javascript is case sensitive; it's getElementById not getElementByID, getElementsByTagName not getElementsBytagName etc.
There are other typos; F12 in your browser and the Error/Console will display script errors.
You need to mix quotes as the below is not valid, aside from the typo its not a parseable string as the quotes are broken:
onClicke="PrinGridView("<%=MyGrideView.ClientID%>")";
Change to
onClick="PrinGridView('<%=MyGrideView.ClientID%>')";
Within the function you quote what should probably be the argument, change from
var TableRow = document.getElementByID("GridViewname")
to
var TableRow= document.getElementById(GridViewname)

You have a typo there, onClicke. This is wrong, should be onClick.

Try like this
onClick="PrinGridView(this)"
function PrinGridView(obj)
{
var gridName = obj.id;
var TableRow= document.getElementByID(gridName).getElementsBytagName("tr");
var td= TableRow.item(0).getElementsBytagName("th");
if(td.length>0)
alert('done');
}

this works perfectly for inline code
OnClientClick='<%#String.Format("buttonstatus(""{0}"",""{1}"",""{2}"",""{3}"");return false;", Eval("listingid"), "D", "Archived", Eval("EndDate"))%>'

Related

Inserting a declared variable (var) in window.open.href

Hi guys I'm just studying about the javascript and asp.net.
I want to insert/append a declared var in window.location.href, I have this code and its working just as I wanted to.
<script type = "text/javascript">
function myFunction() {
//var siteURL = document.getElementByID("txtURL");
window.location.href = "http://www.google.com";
}
</script>
This function is called/triggered through an 'onclick' event. But When I change the code to:
<script type = "text/javascript">
function myFunction() {
var siteURL = document.getElementByID("txtURL");
window.location.href = siteURL;
}
</script>
Can someone help me make the second code given work just like the first one. Thanks in advance.
First of all there is no document.getElementByID function. It's document.getElementById (last char differs).
This function will return object so to get it's value you should use innerHTML (or value if it's input field) attribute like this var siteURL = document.getElementByID("txtURL").innerHTML; and then pass this variable to window.location.href.
Your problems lay with getElementByID. Firstly, you've made a typo, the last letter should be lower case getElementById, and secondly, this returns a Node, from which you probably want it's value
var siteURL = document.getElementById("txtURL").value;
First of all, JavaScript is case sensitive language, so the correct method name for selecting an element by ID is document.getElementById().
Next, if element with ID "txtURL" is a form field, e.g. <input> or <select> you should get its value with siteURL.value. Otherwise if it is any other text container, e.g. <div> or <span> with URL as its text, you may use siteURL.innerHTML.
var siteURL = document.getElementById("txtURL");
//siteURL is just a reference to the text field, not it's value
your variable siteURL is just a dom object at this stage, you need to call the .value property to grab it's value to use as a href. and JavaScript is case sensitive so it's .getElementById() not .getElementByID(). The code below should work just fine
<script type = "text/javascript">
function myFunction() {
var siteURL = document.getElementById("txtURL").value; //add .value here
window.location.href = siteURL;
}
</script>
document.getElementById() returns a DOM object, not a string.
If you have your url stored in a node which ID is "txtURL", you have to access the information itself, probably if stored as contents of the node: via .innerHTML or via .html() in jQuery
document.getElementByID("txtURL") returns a DOM Node. window.location.href is a String-like object. Giving it a DOM Node is silly.
If #txtURL is an input, you can do:
window.location.href = document.getElementById("txtURL").value;
If it's a TextNode you can do something like:
window.location.href = document.getElementById("txtURL").nodeValue;
but this is getting iffy.

JQuery and Eval

First of all, lets say I have about 10 divs that are hidden and have the ID's as "modal1", "modal2", "modal3", etc... Using an ajax request, the data returned contains an ID number, lets say it is 7.
In previous tasks, I have used the javascript eval function but this does not work. I wish to append the received data to the correct modal div.
var newdataobj = JSON.parse(newdata);
var ResponseDiv = "#modal" + newdataobj.ID;
$(eval(ResponseDiv)).append(newdataobj.DataToAdd);
This doesn't work and the script stops working at this point. I have also tries using the JQuery version of eval, but that did not work either.
You don't need to use eval() here, use just $(ResponseDiv).append(newdataobj.DataToAdd);
ResponseDiv is already a string and that is what you need for the selector.
Try this to confirm you have the right ID:
var newdataobj = JSON.parse(newdata);
var ResponseDiv = "#modal" + newdataobj.ID;
alert(ResponseDiv); // or console.log(ResponseDiv); - to doublecheck you have the right ID
$(ResponseDiv).append(newdataobj.DataToAdd);
ResponseDiv is already a string containing exactly what you want.
You don't want eval at all.

Can't change span content

I've got this span:
<span id="inicial"></span>
and this javascript inside a button click:
var pat = /\/\S+\//i;
context = '';
context = $('#cmd').attr('value');
context= context.match(pat);
alert(context); //this gives correctly the string i need
if (context.length){
$('#inicial').text(context); //but it fails to change the text inside the span
}
What could be the problem?
Also i noticed that it affects the whole click function, it just stops working. What could possibly be the cause?
The problem is that .match() returns an array, not a string. But .text(parm) requires parm to be a string.
So after the .match(), you should do something like:
context = context[0];
or use some other methodology to convert at least the first element in the array to a string, if not the full array.
Here's the reference for .match(): https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/match
And the ref for .text(parm): http://api.jquery.com/text/
try -- edited as per #Jonathan M
answer
$('#inicial').html(context[0]);

How do I concatenate a string with a variable?

So I am trying to make a string out of a string and a passed variable(which is a number).
How do I do that?
I have something like this:
function AddBorder(id){
document.getElementById('horseThumb_'+id).className='hand positionLeft'
}
So how do I get that 'horseThumb' and an id into one string?
I tried all the various options, I also googled and besides learning that I can insert a variable in string like this getElementById("horseThumb_{$id}") <-- (didn't work for me, I don't know why) I found nothing useful. So any help would be very appreciated.
Your code is correct. Perhaps your problem is that you are not passing an ID to the AddBorder function, or that an element with that ID does not exist. Or you might be running your function before the element in question is accessible through the browser's DOM.
Since ECMAScript 2015, you can also use template literals (aka template strings):
document.getElementById(`horseThumb_${id}`).className = "hand positionLeft";
To identify the first case or determine the cause of the second case, add these as the first lines inside the function:
alert('ID number: ' + id);
alert('Return value of gEBI: ' + document.getElementById('horseThumb_' + id));
That will open pop-up windows each time the function is called, with the value of id and the return value of document.getElementById. If you get undefined for the ID number pop-up, you are not passing an argument to the function. If the ID does not exist, you would get your (incorrect?) ID number in the first pop-up but get null in the second.
The third case would happen if your web page looks like this, trying to run AddBorder while the page is still loading:
<head>
<title>My Web Page</title>
<script>
function AddBorder(id) {
...
}
AddBorder(42); // Won't work; the page hasn't completely loaded yet!
</script>
</head>
To fix this, put all the code that uses AddBorder inside an onload event handler:
// Can only have one of these per page
window.onload = function() {
...
AddBorder(42);
...
}
// Or can have any number of these on a page
function doWhatever() {
...
AddBorder(42);
...
}
if(window.addEventListener) window.addEventListener('load', doWhatever, false);
else window.attachEvent('onload', doWhatever);
In javascript the "+" operator is used to add numbers or to concatenate strings.
if one of the operands is a string "+" concatenates, and if it is only numbers it adds them.
example:
1+2+3 == 6
"1"+2+3 == "123"
This can happen because java script allows white spaces sometimes if a string is concatenated with a number. try removing the spaces and create a string and then pass it into getElementById.
example:
var str = 'horseThumb_'+id;
str = str.replace(/^\s+|\s+$/g,"");
function AddBorder(id){
document.getElementById(str).className='hand positionLeft'
}
It's just like you did. And I'll give you a small tip for these kind of silly things: just use the browser url box to try js syntax. for example, write this: javascript:alert("test"+5) and you have your answer.
The problem in your code is probably that this element does not exist in your document... maybe it's inside a form or something. You can test this too by writing in the url: javascript:alert(document.horseThumb_5) to check where your mistake is.
Another way to do it simpler using jquery.
sample:
function add(product_id){
// the code to add the product
//updating the div, here I just change the text inside the div.
//You can do anything with jquery, like change style, border etc.
$("#added_"+product_id).html('the product was added to list');
}
Where product_id is the javascript var and$("#added_"+product_id) is a div id concatenated with product_id, the var from function add.
Best Regards!

Can I get a jQuery object from an existing element

I have a function
function toggleSelectCancels(e) {
var checkBox = e.target;
var cancelThis = checkBox.checked;
var tableRow = checkBox.parentNode.parentNode;
}
how can I get a jQuery object that contains tableRow
Normally I would go $("#" + tableRow.id), the problem here is the id for tableRow is something like this "x:1280880471.17:adr:2:key:[95]:tag:". It is autogenerated by an infragistics control. jQuery doesn't seem to getElementById when the id is like this. the standard dom document.getElementById("x:1280880471.17:adr:2:key:[95]:tag:") does however return the correct row element.
Anyways, is there a way to get a jQuery object from a dom element?
Thanks,
~ck in San Diego
Absolutely,
$(tableRow)
http://docs.jquery.com/Core/jQuery#elements
jQuery can take the DOM elements, try with:
$(tableRow)
or
$(checkBox.parentNode.parentNode)
You should be able to pass the element straight in, like this:
$(tableRow)...
I have tested this by creating a reference to a div, then passing it straight into jQuery and it creates the jQuery object for you.
You can call the jQuery function on DOM elements: $(tableRow)
You can also use the closest method of jQuery in this case:
var tableRowJquery = $(checkBox).closest('tr');
If you want to keep using your ID, kgiannakakis (below), provided an excellent link on how to escape characters with special meaning in a jQuery selector.
See this for how you should escape the id.
try:
var r = $(document.getElementById("XXXX----ID Of Your Row----XXXX"));
now, if document.getElementById doesn't return undefined you can use r as any regular jquery object.

Categories