how have a server side click of a div? - html

i have a div..inside the div i have an image and name..now when i will click on the div the div will have a server side click that means it will have a codebehind function..how to do it?? or how to make my div a button where i don't have to change my div...
my code
<div class="tutorial" style="margin-left:5px;">
TUTORIAL<div class="firstico" style="margin-left:70px;margin-top:-17px;">
</div>
</div>
how can i have a server side onclick function of this div???
i have used like that but it didn't work for me..don't know why??
<div class="tutorial" style="margin-left:5px;"
runat="server" id="tutorial" onClick="tutorial_Click">
TUTORIAL<div class="firstico" style="margin-left:70px;margin-top:-17px;">
</div>
</div>
private void tutorial_Click(object sender, System.EventArgs e){
// do stuff
}
i have tried like that also but it also didn't work for me...
<div class="tutorial" style="margin-left:5px;"
onclick="__doPostBack('tutorial', 'click');">
TUTORIAL<div class="firstico" style="margin-left:70px;margin-top:-17px;">
</div>
</div>
private void PageLoad(object sender, System.EventArgs e){
// sttufs
[...]
// my stuff for tutorial click
if (Request["__EVENTTARGET"] == "tutorial" && Request["__EVENTARGUMENT"] == "click"){
TutorialClicked();
}
}
private void TutorialClicked(){
iframestyle.Attributes["src"] = "userpage.aspx";
}

You will have to handle the click in the div using the Jquery and call server-side methods through JQuery.
Try it.
Source Code :-
<div class="tutorial" style="margin-left:5px;"
runat="server" id="tutorial" onClick="javascript:tutorial_Click('peram1')">click me
</div>
Javascript Code :-
<script type="text/javascript">
function tutorial_Click(parameter)
{
__doPostBack('tutorial', parameter)
}
</script>
Code :-
public void Page_Load(object sender, EventArgs e)
{
string parameter = Request["__EVENTARGUMENT"]; // parameter
// Request["__EVENTTARGET"]; // btnSave
if (parameter == "peram1")
TutorialClicked();
}
private void TutorialClicked(){
//write your code.
}
For more information refer __doPostBack

Lets say you want the page "tutorial.aspx" to be displayed.
Then make your div look like this:
<div class="tutorial" style="margin-left:5px;" onclick="location.href='tutorial.aspx';">
TUTORIAL
</div>
Lets say you have an iframe on your main page; (referring to this part of your code above)
private void TutorialClicked(){ iframestyle.Attributes["src"] = "userpage.aspx"; }
Wrap an anchor around a text like this
User Page

You can try this stuff-
Add a button to your html markup, and set it's style="display: none". so it won't be visible to anyone.
Now add a click event to this button.
When click on div call click event of the button
it may be like below
function tutorial_Click(){
// call here the button click which will do a postback
document.getElementById('<%= btn.ClientID %>').click();
}
4 . Do your code behind stuff at button click event at server side.
Hope this helps.

You can't listen for a click event from the server side. After the server has sent you the required files, the server is no longer involved.
You need a client side listener, jquery is very easy to use.
Index (or whatever html page u got):
<div id="clickme" class="tutorial" style="margin-left:5px;">
<div class="firstico" style="margin-left:70px;margin-top:-17px;">
TUTORIAL
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
$('#clickme').on('click', function () {//can replace '#clickme' for '.tutorial' if you want to be able to click multiple divs
//do stuff
$.ajax({//with ajax you can send a request to the server, and make it do somthing.
url: '/path/to/file',
type: 'post',
data: {variable: 'data'},
success: function(data) {//data is what you echo on from php
//do something on the site
alert(data);//just alert what you echo
}
});
});
</script>
And php (for example) a little but like this:
<?php
function doMe() {
//your function
}
if(isset($_POST['variable'])) {
if($_POST['variable'] === 'data') {
doMe();
}
}
?>

Related

Element not getting deleted even after I have used even delegation

I made this form using jQuery.
The jQuery code which I wrote to add this is as follows :
formView:function(){
var htmlStr = '<form><input class = "name"/><input class = "imageUrl"/><input class = "counter"/></form><button class="cancel">Cancel</button>'
$('#form').html(htmlStr);
// octopus.changeFlag();
}
and the code to collapse this form, I used jQuery as event delegation as below :
$('#form').on('click','cancel',function(e){
console.log("Hello world");
$('#form').html('');
// e.preventDefault();
});
My HTML code is as below:
<body>
<ul class = "list">
</ul>
<img class="image" src="images/Vaibhav.jpg">
<div id="count"></div>
<div id="admin">
<button class="admin">Admin</button>
<div id = "form"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
Whenever I click on cancel, it should collapse the form, but its not happening. Thanks in advance.
p.s. I am a beginner to jQuery.
You need to add . to your selector for class cancel
$('#form').on('click','.cancel',function(e){
console.log("Hello world");
$('#form').remove();
// e.preventDefault();
});

HTMLService won't display return value

I created a sidebar to have a basic UI for searching my Google sheet. I'm following this tutorial exactly to make sure the first step works, except that it doesn't! I even took out the userObject part to make it simpler (honestly, because I don't know what that part does).
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
function updateButton(email, button) {
button.value = 'Clicked by ' + email;
}
</script>
</head>
<body>
<input type="button" value="Not Clicked"
onclick="google.script.run
.withSuccessHandler(updateButton)
//.withUserObject(this)
.testMe()" />
<input type="button" value="Not Clicked"
onclick="google.script.run
.withSuccessHandler(updateButton)
//.withUserObject(this)
.testMe()" />
</body>
</html>
It calls this function:
function testMe() {
Logger.log("Test log.");
return ContentService.createTextOutput("Jackpot!");
}
If it matters, the HTML runs in a sidebar via onOpen as follows:
function showGradingSidebar() {
var html = HtmlService.createHtmlOutputFromFile('testSidebar')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setTitle('Testing Module')
.setWidth(300);
SpreadsheetApp.getUi()
.showSidebar(html);
}
When I click the button, it does nothing (that I can see). By changing various aspects, I can get it to Logger.log() a simple message but even that doesn't work reliably if I change the HTML side.
I was reading about the security restrictions that require sanitizing what the function returns, but both HtmlService.createHtmlOutput() and ContentService.createTextOutput() were also unsuccessful. Please advise.
UPDATE: Thanks to #Bryan P, I got it to work. The testMe() is simply:
return "Jackpot";
...and the HTML page looks like this:
[html, head, etc.]<body>
<input type="button" value="Ready"
onclick="google.script.run
.withSuccessHandler(updateButton)
.withUserObject(this)
.testMe()" --->
<br><div id="output">Output goes here: </div>
<br><div id="papa">Papa goes here: </div>
<br><p></p>
<script>
function updateButton(result) {
var div = document.getElementById('output')
div.innerHTML = 'It finally works!' + result;
}
</script>
</body>
</html>
I don't know how much it helped, but I did move the script tag down to the bottom of the body, fwiw, after reading this SO post.
In Chrome, if you right-click in the sidebar area >> Inspect >> in the Console it should show a message that there wasn't a valid return type after clicking on one of the buttons.
.createTextOutput(content) returns a TextOutput type (which isn't the same as just plain text type)
It's only used when you've deployed a the web app URL and some external service calls that URL. It only gets handled with doGet() too.
Did you try just return "Jackpot"; instead?
.withUserObject(this) - this refers to button element and the whole method passes it on to the successHandler(). So you can consider keeping it. Otherwise you'd have to reference the button from within the successHandler another way:
function updateButton(email) {
document.getElementById('myButton').value = 'Clicked by ' + email;
}
...which requires you add an ID attribute into the button.
You can always do:
function updateButton(email, button) {
console.log('Success hit');
button.value = 'Clicked by ' + email;
}
...to check whether the successHandler was even called in that Chrome dev console too.

Prevent HTML Page Refresh

At this stage I'm mostly used to backend Javascript and server side Java, so my HTML is not as savvy as it needs to be.
I've built several applications that require user input with Apps script, but I was using the now deprecated UI service, as I'm not a designer and this provided an easy way to design simple pages to pass data back and forth. With the UI service having been deprecated for some time, I'm begging the arduous task of migrating these services to the HTML service, and I'm noticing some difference in behavior.
For example, when submitting a form, the entire page refreshes to a blank page, and I can't seem to prevent that. The UI service would remain static for information re-entry, and I can't find a working method to get the HTML service to either stop refreshing or reload the form.
Simple code to reproduce my issue:
function doGet() {
return HtmlService.createHtmlOutputFromFile('test')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function logValues(value){
Logger.log('Something worked....');
}
With the index file being:
<form>
<input type="submit" value="Book Meeting" onclick="google.script.run
.logValues()">
</form>
Some things I've tried:
1) Adding a callback to the 'doGet' function, to attempt to get the page to load again.
2) Adding a whole new function to try and call a NEW HTML page.
The issue here is my poor understanding of the HTML service, but is there a simple way for me to just clear the form for re-submission, or alternatively just reload the page? None of the other questions I've found on SO adequately answer this question in a way I can understand.
Since you're technically submitting your form by clicking the submit button, then that creates the page refresh. You need to cancel the submit event with the preventDefault function, which "Cancels the event if it is cancelable, without stopping further propagation of the event."
See the docs here: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
So maybe you can try something along these lines (straight from the docs):
function stopDefAction(evt) {
evt.preventDefault();
}
document.getElementById('my-checkbox').addEventListener('click', stopDefAction, false);
Another option is to remove the form/input elements and simply use a button element instead, which doesn't trigger a page refresh on click.
It's an interesting ride switching old UI services across, I just did that with one of my applications and it has really improved the readability of the code. I posted a copy of a basic version of what I was doing in another question
Once you get your head around it all it becomes a lot simpler. This is a really basic example of using multiple HTML files similar to your example using the HTMLService when submitting forms (you can pass in parameters instead)
Code.gs
function doGet() {
return HtmlService.createTemplateFromFile('Main')
.evaluate()
.setSandboxMode(HtmlService.SandboxMode.NATIVE);
}
function onLogin(form) {
if (form.username == "fuzzyjulz") {
var template = HtmlService.createTemplateFromFile('Response');
//Setup any variables that should be used in the page
template.firstName = "Fuzzy";
template.username = form.username;
return template.evaluate()
.setSandboxMode(HtmlService.SandboxMode.NATIVE)
.getContent();
} else {
throw "You could not be found in the database please try again.";
}
}
function include(filename) {
return HtmlService.createTemplateFromFile(filename)
.evaluate()
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.getContent();
}
Main.html
<?!= include('CSS'); ?>
<script>
function loadPage(htmlOut) {
var div = document.getElementById('content');
div.innerHTML = htmlOut;
document.getElementById('errors').innerHTML = "";
}
function onFailure(error) {
var errors = document.getElementById('errors');
errors.innerHTML = error.message;
}
</script>
<div id="errors"></div>
<div id="content">
<?!= include('Login'); ?>
</div>
CSS.html
<style>
p b {
width: 100px;
display: inline-block;
}
</style>
Login.html
<script>
function onLoginFailure(error) {
var loginBtn = document.getElementById('loginBtn');
loginBtn.disabled = false;
loginBtn.value = 'Login';
onFailure(error);
}
</script>
<div class="loginPanel">
<form>
<p>
<b>Username: </b>
<input type="text" name="username"/>
</p>
<input type="button" id="loginBtn" value="Login" onclick="this.disabled = true; this.value = 'Loading...';google.script.run
.withSuccessHandler(loadPage)
.withFailureHandler(onLoginFailure)
.onLogin(this.parentNode)"/>
</form>
</div>
Response.html
<div class="text">
Hi <?= firstName ?>,<br/>
Thanks for logging in as <?= username ?>
</div>

How can i Have a Server side onClick function of a div?

i have a div..inside the div i have an image and name..now when i will click on the div the div will have a server side click that means it will have a codebehind function..how to do it?? or how to make my div a button where i don't have to change my div...
my code
<div class="tutorial" style="margin-left:5px;">
TUTORIAL<div class="firstico" style="margin-left:70px;margin-top:-17px;">
</div>
</div>
how can i have a server side onclick function of this div???
Not a direct answer. But you can make a button and hide it. Handle the click event of div via Jquery and then on click of div, make the button click.
Here is the answer:
http://forums.asp.net/t/1090438.aspx
You should implement IPostBackEventHandler for your page and register div.
Option 1:
You can make div runat="server":
C#
<div class="tutorial" style="margin-left:5px;"
runat="server" id="tutorial" onClick="tutorial_Click">
TUTORIAL<div class="firstico" style="margin-left:70px;margin-top:-17px;">
</div>
</div>
private void tutorial_Click(object sender, System.EventArgs e){
// do stuff
}
VB.NET
<div class="tutorial" style="margin-left:5px;"
runat="server" id="tutorial">
TUTORIAL<div class="firstico" style="margin-left:70px;margin-top:-17px;">
</div>
</div>
Private Sub tutorial_Click(object sender, System.EventArgs e) handles tutorial.Click Then
// do stuff
End Sub
Option 2:
OR call __doPostBack() via client (Javascript)
<div class="tutorial" style="margin-left:5px;"
onclick="__doPostBack('tutorial', 'click');">
TUTORIAL<div class="firstico" style="margin-left:70px;margin-top:-17px;">
</div>
</div>
private void PageLoad(object sender, System.EventArgs e){
// sttufs
[...]
// my stuff for tutorial click
if (Request["__EVENTTARGET"] == "tutorial" && Request["__EVENTARGUMENT"] == "click"){
TutorialClicked();
}
}
private void TutorialClicked(){
// do stuff
}

Different behaviours for two different submit buttons?

I am trying to have two submit buttons in my form - one accepts meetings; the other declines them. They will both have different behaviours. How can I do is in my C# code?
The functionality I want is essentially
if(isPost) {
if(//accept button pressed(Request.Form[???]))
{
}
else
{
}
}
Here is my HTML :
<button name="accept" type="submit">Accept</button>
<div class="spacer"></div>
<button name="decline" type="submit">Decline</button>
<div class="spacer"></div>
Simple enough, but I cannot find a test for this on the Internet or in any documentation. Does anyone know what I would have for this ?
Give each button element the same name (in this example, 'SubmitButton') but a different value, then do a check for the different values in your server code, ie:
<button type="submit" name="SubmitButton" value="Accept">Accept</button>
<button type="submit" name="SubmitButton" value="Decline">Decline</button>
Then in your server code:
string buttonClicked = Request.Form["SubmitButton"]
if(buttonClicked == "Accept")
{
// Accept code
}
else if(buttonClicked == "Decline")
{
// Decline code
}
Be aware that this won't work on some earlier versions of IE though, and you may have to do a little javascript on the client prior to the post request being made.
As far as I remember, you have a controller action looking like this:
public ActionResult MyAction(string accept, string decline)
{
if (!string.IsNullOrEmpty(accept))
{
//do something
}
else
{
//do something else
}
}
Presuming you are using MVC3 you would do something like
#using (Html.BeginForm("Accept","Meeting"))
{
<input type="submit" value="Accept" />
}
#using (Html.BeginForm("Decline","Meeting"))
{
<input type="submit" value="Decline" />
}
You would then just have your accept and decline code in your Accept and Decline actions of your meeting controller respectively. No need for an if statement at all.
Example controller
public class MeetingController : Controller
{
[HttpPost]
public ActionResult Accept()
{
//Do accept stuff
return View();
}
[HttpPost]
public ActionResult Decline()
{
//Do decline stuff
return View();
}
}
Generally in the codebehind in c# you'd be looking for which button was clicked. You'd have an event handler for each button, and you code would react according to which button was clicked.
this.btnRejectAppointment.Click += new System.EventHandler(this.btnRejectAppointment_Click);
And then your method
private void btnRejectAppointment_Click(object sender, System.EventArgs e)
{
//code to reject appt.
}
And you'd have the SAME set for the other button.
ASP.NET Button control has OnClick event, so add different handler to every your button:
<asp:Button OnClick="MyHandler1" ... />
in code behind:
protected void MyHandler1(object sender, EventArgs args)
{ /* do stuff */ }
One of the possible solutions - use two buttons of type LinkButton but specify slightly different PostBackUrl:
<!-- Accept meeting button -->
<asp:LinkButton ID="acceptMeeting" runat="server"
PostBackUrl="MeetingsManager.aspx?Mode=Accept" />
<!-- Decline meeting button -->
<asp:LinkButton ID="declineMeeting" runat="server"
PostBackUrl="MeetingsManager.aspx?Mode=Decline" />
And in code behind:
public enum Mode
{
Unknown,
Accept,
Decline
}
protected void Page_Load(object sender, EventArgs args)
{
Mode currentMode = Mode.Unknown;
var rawMode = Request.QueryString["Mode"];
if (rawMode != null)
{
currentMode = (Mode)Enum.Parse(
typeof(Mode),
rawMode.ToString())
}
}