How to pass javascript var to server side on asp.net - javascript

I'm trying to pass a textarea value to the server side. The textarea cant be runat=server though.
heres my code:
<script type="text/javascript">
function replace() {
//Replace < and > on textarea
var obj = document.getElementById('recipient_list');
var str = obj.value;
str = str.replace(/</i, "(");
str = str.replace(/>/i, ")");
obj.value = str;
alert("rec_lst.value: " + document.getElementById('recipient_list').value);
//Pass value to server.
alert("passing to server");
document.getElementById("ctl00$ContentPlaceHolder1$txtEmails").value = str;
alert("Passed to server");
alert("txtEmails.value: " + document.getElementById("ctl00$ContentPlaceHolder1$txtEmails").value);
}
</script>
This isn't working though... Any ideas how to fix or better implement this??..

Try this:
var txtEmail = document.getElementById("<%=txtEmails.ClientID%>");
txtEmail.value = str;
However this won't pass anything to the server, just change text box value.
To have it sent to the server user will have to click submit button, or if you have server side button have such code to "auto click" it thus performing post back:
document.getElementById("<%=btnSubmit.ClientID%>").click();

you cant pass value from client to server using JS .
JS is only a client side code.If you can do something like this, Hacking will be so easy :)
one thing you can do is add some text or label control as invisible and assign the value to the control and pass it to server when some event happens.
Sample code
<asp:TextBox ID="textbox1" runat="server" ></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="callOnEvets()"/>
function callOnEvets()
{document.getElementById('textbox1').value = 10; }

Related

Retrieve value from javascript funcion on client click

I have a function on JS that must execute before the codebehind, but i'm having trouble retrieving it.
It will return a variable that i should use on the codebehind. The function i created is this one:
<script type="text/javascript" >
function returnHash() {
var checkout = new DirectCheckout('086F7D02A071267FEBF102EB759D9845B8B3333DFA65BC45B807F41A8525AD8D'); /* Em sandbox utilizar o construtor new DirectCheckout('SEU TOKEN PUBLICO', false); */
debugger;
var month = document.getElementById("txtDataVencUser").value;
var year = document.getElementById("txtDataVencUser").value;
var cardData = {
cardNumber: document.getElementById("txtNumeroCartaoUser").value,
holderName: document.getElementById("txtNomeCartaoUser").value,
securityCode: document.getElementById("txtCodSegurancaUser").value,
expirationMonth: month.substring(0, 2),
expirationYear: "20" + year.substring(3, 5)
};
checkout.getCardHash(cardData, function (cardHash) {
----------------------------> I NEED TO RETRIEVE "cardHash" VALUE IN CODEBEHIND
}, function (error) {
console.log(error);
});
}
</script>
I don't know if this step is correct, but i am using the onClientClick to try to execute the JS before the codebehind:
<asp:Button ID="btnFinalizarCompraJunoUser" runat="server" Text="FINALIZAR COMPRA" OnClientClick="returnHash()" OnClick="btnFinalizarCompraJunoUser_Click" Visible="true" />
I am having trouble figuring out what to do next, can someone help me please?
There are a number of ways - perhaps as many flavors of ice cream.
But, since you are going to run a "code behind" stub based on the click?
I would just drop a hidden field on the page, and then just set that value in js
So right below your button - add a hidden field say like this:
<form id="form1" runat="server">
<br />
<asp:Button ID="Button1" runat="server" Text="Button"
OnClientClick="myfun();return true" Width="68px"
ClientIDMode="Static"/>
<asp:HiddenField ID="HiddenField1" runat="server" ClientIDMode="Static" />
</form>
<script type="text/javascript">
function myfun() {
// do whatever - walk the dog - have fun!!!
var f1 = document.getElementById("HiddenField1");
f1.value = "2222";
}
</script>
So in above I just shove 2222 into the hidden1 field.
Now, in the the code behind button stub, you can do this:
Debug.Print("my click f1 = " & HiddenField1.Value);
So the code behind will now have a good old regular plane jane control to look at and get the value in question.
So, it depends on how many values - but using a code behind friendly (asp.net) control and setting the value with the js client side code probably is the least effort here.
I also of course used "staticID" for the above. If you for some reason don't like (or want) to use staticID for above, then the js selection would be:
var f1 = document.getElementById("<%=HiddenField1.Clientid%>");
f1.value = cardHash;

How to bring value of selected radio button to server side

After getting the value, how can I bring the var to ASP.net server side so I can use it in server side?
function btnSelect_OnClick() {
var PCType;
if (document.getElementById('r1').checked) {
PCType = document.getElementById('r1').value);
}
}
If you don't want to use an AJAX solution, consider storing the value in a HiddenField.
JavaScript
function btnSelect_OnClick() {
var PCType = "";
if (document.getElementById('r1').checked) {
PCType = document.getElementById('r1').value);
}
document.getElementById('hfPCType').value = PCType;
}
ASP.Net
<asp:HiddenField runat="server" id="hfPCType" ClientIDMode="static" />
C#
string PCType = hfPCType.Value;

Trying to pass value from ASP.NET JavaScript script to my C# Code Behind function using Hidden Field

I have a JavaScript script inside my ASP.NET Web site, and i want to get a value from a function in my C# Code Behind, with a argument i pass it from my ASP.NET Hidden Field.
Here is my ASP.NET & JavaScript part, i define a HiddenField and assigns the chatMessage var to it, than assigns a value to the var, and try to send its value to the returnLiClass() function.
(Important part is the first line, and the 13,14,17 lines):
<asp:HiddenField ID="chatMessage" runat="server" />
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (name, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div /> ').text(message).html();
var tremp_id = $('<div /> ').text("<%=Request.QueryString["trempid"]%>").html();
var chatMessage = document.getElementById('<%= chatMessage.ClientID %>');
chatMessage.value = 'value from javascript';
// Add the message to the page.
$('#discussion').append('<li class="<%=returnLiClass(chatMessage.Value)%><strong>' + encodedName
+ '</strong>: ' + encodedMsg + "Tremp:" + tremp_id + '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val('<%=returnName()%>');
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
</script>
The Code Behind function (When i debug neither the msg nor the chatMessage.Value has values):
protected String returnLiClass(String msg)
{
String test = chatMessage.Value;
return "redChat";
}
I'm not sure what am i doing wrong...
Hope you could help, Thank you!
Try using the jquery val() function.
I also feel that the control isn't being found, which is why it's not setting it.
Try this instead.
$("#<%=chatMessage.ClientID%>").val('value from javascript');

Adding an img HTML tag combined with a call to C# function to an ASP.NET page inside JavaScript script

Yeah, i know the title is a bit confusing but that's what it is...
Here is the piece of JavaScript code i have inside my ASP.NET Web app,
the line that troubles me is the 7th line from the bottom, after chat.server.send.
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (name, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div /> ').text(message).html();
var tremp_id = $('<div /> ').text("<%=Request.QueryString["tid"]%>").html();
var chatMessage = document.getElementById('<%= chatMessage.ClientID %>');
chatMessage.value = 'value from javascript';
// Add the message to the page.
$('#discussion').append('<li><strong>' + encodedName
+ '</strong>: ' + encodedMsg + '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val('<%=returnName()%>');
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('<div /> ').text('<img src="<%=getUserImage(Convert.ToInt32(Request.QueryString["uid"]))%>" height="50" width="50" border="1" bordercolor=black />').html() + $('#displayname').val(), $('#message').val() + $('<div /> ').text(" | Tremp: <%=Request.QueryString["tid"]%>").html());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
</script>
As you can see I'm trying to add an image that gets the URL from a function within my C# code behind.
It gets some number from the URL and sends it to the function, that returns an image URL.
It seems alright except it shows the following instead:
What am i doing wrong and how can i fix it?
I'm sure it should be pretty simple.. but i can' find the right way..
Thanks.
You're using jquery Text function which escape the string (intended for text).
What you're looking for it the jquery append function.
chat.server.send($('<div /> ').append(...
In fact, you have the same problem when you broadcast your message (chat.client.broadcastMessage). You're using text instead of append
var encodedMsg = $('<div /> ').append(message).html();
Also make sure that your message variable is not already encoded from the server.

Onblur,Onfocus javascript for TextMode="MultiLine" not working

I've got a multiline asp.textbox input control.
I don't know if my issue is with ASP.NET, the Multiline control, or something else, but the onblur and onfocus are not working.
<script type="text/javascript">
var defaultMsg = 'Write your message here or or call my voice at (xxx) xxx-xxxx.';
var controlMsg = doc.createElement("input");
controlMsg.id = "txtMessage";
controlMsg.type = "text";
controlMsg.value = defaultMsg;
controlMsg.onfocus=function jpFocus() { if (this.value == defaultMsg) this.value = ''; }
controlMsg.onblur=function jpBlur() { if (this.value == '') this.value = defaultMsg; }
</script>
And later....
<asp:TextBox ID="txtMessage" Columns="30" Rows="6" runat="Server" TextMode="MultiLine" />
Does anyone see a reason why this should not be working?
Actually, you're creating a html element and you are attaching an event to it.
In addition, ASP.NET controls does not use the server side id.
Here's what you should do :
var controlMsg = document.getElementById('<%= txtMessage.ClientID %>');
controlMsg.onfocus = // Some Code ...
controlMsg.onblur = // Some Code ...
Try using an anonymous function, like this:
controlMsg.onfocus=function() { if ( ...
Functions and function scope - MDN.
Also, you did call something like document.body.appendChild(controlMsg);, didn't you?
EDIT:
You are using doc.createElement. Make sure that doc definitely points to document.
Also, look at the page in Firefox and see if there are any errors or warnings in the Error Console.
Not sure which version your are using.Please Try this:
protected void Page_Load(object sender, EventArgs e)
{
txtMessage. Attributes["onfocus"]="JavascriptMethod";
}
I'm not sure why this worked and other techniques did not, but this got my HTML to work:
<textarea name="txtMsg" rows="6" cols="30"
onfocus="if(this.value==this.defaultValue)this.value='';"
onblur="if(this.value==='')this.value=this.defaultValue;">[Write your message here or call my voice number at (555) 222-1234.]</textarea>
The text can be very long, and the control does not seem to care. Also, the text is only written in a single location.

Categories

Resources