I am trying to call a c# function from JavaScript but the problem is, I need to pass a JS parameter for the function. How can I do this?
Here's my Js
var categoryLists = <%= this.javaSerial.Serialize(this.categoryList) %>;
function addInput(type, value, name, id, onclick, parentId) {
var element = document.createElement("input");
element.type = type;
element.value = value;
element.name = name;
element.id = id;
element.onclick = onclick;
element.src = "trash.png";
element.style.width = "25px";
element.style.height = "25px";
element.style.marginBottom = "3%";
var parent = document.getElementById(parentId);
parent.appendChild(element);
}
function addBreak(parentId) {
var br = document.createElement("br");
var parent = document.getElementById(parentId);
parent.appendChild(br);
}
window.onload = function () {
alert(this.categoryLists.length);
for (var j = 0; j < this.categoryLists.length; j++) {
var temp = "button" + j;
addInput('image', '', temp, temp, <%=DeleteCategory(%>+categoryLists[j]), 'rightdiv');
addBreak('rightdiv');
}
}
categoryLists[j] is my paramter
Here's the c# code
public void DeleteCategory(string category){
}
public JavaScriptSerializer javaSerial = new JavaScriptSerializer();
Update- I call c# functions this way... <%= function()%> and they work fine.
Thank you in advance
Update- with all the comments, I have tried using ajax or jquery - i am not sure what this is ... now my js looks like this and its broken... are there syntax issues?
$(function () {
function addInput(type, value, name, id, onclick, parentId) {
var element = document.createElement("input");
element.type = type;
element.value = value;
element.name = name;
element.id = id;
element.onclick = onclick;
element.src = "trash.png";
element.style.width = "25px";
element.style.height = "28px";
element.style.marginBottom = "3%";
var parent = document.getElementById(parentId);
parent.appendChild(element);
}
function addBreak(parentId) {
var br = document.createElement("br");
var parent = document.getElementById(parentId);
parent.appendChild(br);
}
for (var j = 0; j < this.categoryLists.length; j++) {
var temp = "button" + j;
addInput('image', '', temp, temp, temp, 'rightdiv');
addBreak('rightdiv');
}
});
You have quite a few ways to do this.
You can use the cheater approach. Drop in a text box, and a standard button (that will call server side code behind). (set clientID mode for this button and text box as static).
<asp:Button ID="btnHidden" runat="server" Text="hidden but" />
<asp:TextBox ID="TextHiddenBox" runat="server" ClientIDMode="Static" ></asp:TextBox>
Ok, now in your js you can go:
<script>
// set the value we want to pass in the hidden text box
$('#txtHidden').value("abc");
$('#hiddenButton').click;
<script>
Note: above is jQuery syntax.
You could do this: (pure js no jQuery)
var myvaluetopass = "this is some text to pass as variable";
document.getElementById('<%= TextHiddenBox.ClientID %>').value = myvaluetopass;
document.getElementById('<%= btnHidden.ClientID %>').click();
so you don't have to introduce jQuery here - it can be some "time" and "hassle" to setup + get jQuery working.
So, the above will simple click on the hidden button, and the hidden text box will have the value that the code behind can work with. Once you wire up the above?
Then hide the button and the text box like this:
<asp:Button ID="btnHidden" runat="server" Text="hidden but" style="display:none"/>
<asp:TextBox ID="TextHiddenBox" runat="server" ClientIDMode="Static" style="display:none" ></asp:TextBox>
Now, the above is certainly somewhat "klugey". But when you starting out, it can work quite well. So, you set the value of some text box (often hidden), and then with js you FIRE the click event of another button (again often hidden). This now gets you a easy way to run one particular code behind routine, and not have to wire up complex ajax code.
The next approach? Well, fire a post back command. This again like the above hidden button trick assumes you need/want a post back here in addition to calling that one routine. this approach is somewhat better in that you don't have to drop on the form two hidden controls.
You ALSO need to drop in the script manager for this to work (don't know why). But you can do this in your code:
var myvaluetopass = "this is some text to pass as variable";
__doPostBack("MyCoolEventName", myvaluetopass);
So, the above fires a page post back, and then in the load event, we have this:
If Request("__EVENTTARGET") = "MyCoolEventName" Then
Dim str As String = Request("__EVENTARGUMENT")
Debug.Print("passed value = " & str)
End If
or as C#
if (Request("__EVENTTARGET") == "MyCoolEventName")
{
string str = Request("__EVENTARGUMENT");
Debug.Print("passed value = " + str);
}
So the above are some simple ways.
The ALL above ideas do cause a full page post-back to run. Now, if the routine you calling DOES need to set/get/change/deal with/see any control on the page, then of course one does need and want that all important page post back.
Last but not least? Well, you can do a ajax call, and that will call a specific routine on your page, pass values (if you want), and ONLY run that one routine. This can be VERY nice, it fast, and you do NOT get a full page post back. So, if the routine you need to run does not have to modify, or do much of anything on the web page, then ajax is certainly the best way to go (assuming that the routine you calling does NOT need to modify or change things on the page - since as noted, no page post-back will occur. And if you looking to use that value with code behind and modify things on the page, then you will need a post-back.
But, lets assume you do need to pass one, or do values.
Well, I suggest jQuery - it just makes the code a bit easier to write.
So, say in your web page, you have this simple sub, and want to pass two values:
<WebMethod()>
Public Shared Sub MySimpleSub(MyCoolPassValue As String, Age As Integer)
Debug.Print("passed string value = " & MyCoolPassValue & vbCrLf & "Age = " & Age.ToString)
End Sub
or:
[WebMethod()]
public static void MySimpleSub(string MyCoolPassValue, int Age)
{
Debug.Print("passed string value = " + MyCoolPassValue + Constants.vbCrLf + "Age = " + Age.ToString());
}
So in above, it just a public sub. (in the code behind for that web page).
(note the Shared - it HAS to be Static sub - since we calling the page - but don't have the full class object model).
We also need a
Imports System.Web.Services
Ok, now to call the above as ajax?
We get this:
var myvaluetopass = "this is some text to pass as variable";
var age = 23;
$.ajax({
type: "POST",
async: true,
url: 'OnePicture.aspx/MySimpleSub',
data: JSON.stringify({MyCoolPassValue: myvaluetopass, Age: age}),
contentType: "application/json; charset=utf-8",
datatype: "json"
}
);
}
So in above, we passed two values to the sub in the web form.
The above did assume jQuery. I can write it out as pure JavaScript, but the above thus gives;
How to pass values - hidden control idea.
Or use __dopostback - this gets rid of the requirement to have a button + hidden text box
(and use style="display:none" to hide the button and text box above (if you using that idea, and get it working).
As noted, I don't know why, but you have to drop a Scriptmanager into the page if you going to use dopostback. (or pass a valid control ref as the first parameter - it will just to your button code behind routine). But, my dopostback example simple gets/grabs the value in teh page load event (event args).
And then last but not least, we pass a value direction to a web method (sub) in that page - this is a ajax call, and just keep VERY much in mind that the code for this routine has to work without assuming that a page post-back occurred (compared to all previous examples that assumed you need a post back).
I have an Xpages Application and I am currently using a checkbox in a repeat control to call an onChange function, I want to parse the calling element/elementID to my Client Side Javascript located in: Events->onChange. My problem is that my Javascript returns undefined when using "this". I tried to parse an object on the Function call but that doesnt seem to be possible in Xpages either.
Javascript Code (probably wont be much help):
var fieldsets = document.querySelectorAll("table.checkboxGroups");
console.log(fieldsets);
console.log("-----------------");
var fieldsetCurrent = fieldsets[0]; //this is where I need the calling elem
console.log(fieldsetCurrent);
console.log("-----------------");
var fieldsetCheckboxes = fieldsetCurrent.getElementsByTagName("input");
console.log(fieldsetCheckboxes);
console.log("-----------------");
for(i=0;fieldsetCheckboxes.length;i++){
var elem = fieldsetCheckboxes[i];
console.log(i + " : " +elem);
elem.setAttribute("checked","");
//elem.checked;
}
If your repeating on notes documents then you could add the documentid to the checkbox as an attribute and use this id to call your onChange eventhandler. dojo.query might also be of some value here.
I have a div part in my HTML(erb), whose display is "none" at first. Then I change its style to "block" detecting the input values of datetimepicker.
I have succeeded to change the style, but the style reverses to "none" if the form gets flash error message shown after validation.
Is there any way to keep the style changed even after error message shows up.
Here is my code of javascript.
$('.datetimepicker').on('dp.change', function(e) {
var x = document.getElementById("from").value;
var y = document.getElementById("to").value;
var date_y = Date.parse(y);
var date_x_day = Date.parse(x) + (1 * 86400000);
if (date_y > date_x_day) {
$('#hotel').fadeIn(500);
} else {
$('#hotel').fadeOut(500);
}
});
I tried to put the line below after "$('#hotel').fadeIn(500); " but it doesn't work.
document.getElementById('hotel').style.display="block";
Could anyone tells me the best way??
So you want to show the hotels after selecting the date, but after the form submission the page will render with a date value and dp.change never get's triggered.
You can extract that anonymous function and call it right after the page renders.
function handleHotelVisibility(){
// method body;
}
$(function(){
handleHotelVisibility();
$('.datetimepicker').on('dp.change', handleHotelVisibility);
});
I have a javascript function which is called by a 'onsubmit' within a form (Coldfusion).
<form action = "person2aa.cfm"
name = "pers2form"
method = "post"
style = "margin-left: 125px"
onsubmit = "return test()">
When the function test() is located directly below this form statement it works correctly:
<script>
function test(){
alert("got to test");
var yesa = document.getElementById('yesnoa').value;
var yesb = document.getElementById('yesnob').value;
var xx = document.getElementById('ln').value;
var x = xx.trim();
alert('supbpers2 x is ' + x);
if (x < "!"){
document.getElementById('writeval').innerHTML = "You must enter a last name.";
return false;}
else
return true;
}
</script>
(The remainder of the form continues below this script).
When I place this function anywhere else, it does not run. I have tried it in the header of the html page, and also on another page, person.js, to which the link is:
<script type = "text/javascript" src = "person.js"> </script>
The first alert 'got to test' runs in these places, but the first line starting var yesa = does not execute and the function therefore does not execute either.
The id's 'yesnoa', 'yesnob', 'ln' and 'writeval' are in the code and are correct (or the inline script would not run, but I checked anyway).
I previously had this script (minus the alerts) in the header section of my program, and it was working at one point. I have returned to retest the program some months later and the script was not functioning. I have not made any changes to this script at any time. The program itself was altered by the addition of 4 trivial queries to do various things but all look something like this:
<cfquery name = 'aa11' datasource = "Moxart">
update NameInfoDb
set perloc = <cfqueryparam value = "#perloc#">
</cfquery>
I cannot think of any connection between these additional queries and the failure of the javascript.
Can anyone explain what the problem might be? There must be an explanation, and I need to know it so I will not repeat whatever the bad code is.
I am new to javascript. I tried displaying the value of a variable on clicking a button with the following code. But it isn't working.
var i = document.getElementById("inp").value;
var m=i-1;
var s=59;
function func()
{
document.getElementById("display").innerHTML = m +":"+s;
}
In order to apply your code inside the function, you must run (call) the function:
var i = document.getElementById("inp").value;
var m=i-1;
var s=59;
function func()
{
document.getElementById("display").innerHTML = m +":"+s;
}
func();
See this JSFiddle for a live example.
At the moment your Javascript is executed the element with your id is not yet loaded because your script is located in the head.
Make sure the element you are trying to access actually exists at that moment.
Append the <script>-section at the end of your body and dont include it in the <head>.
That way the javascript runs when every element is already loaded.