clicking a button via javascript does not cause a post - javascript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.js"></script>
</head>
<body>
<form id="fooForm">
<script type="text/javascript">
function FooMethod() {
alert('hello');
}
var fooButton;
var fooForm;
var fooDialog;
$(document).ready(function() {
InitializeVariables();
InitiliazeDialog();
InitiliazeForm();
});
function InitializeVariables() {
fooButton = $('#fooButton');
fooForm = $('#fooForm');
fooDialog = $('#fooDialog');
}
function InitiliazeDialog() {
var dialogOpenMethod = function () {
fooDialog.dialog('open');
return false;
};
var submitMethod = function () {
fooButton.unbind('click', dialogOpenMethod);
fooButton.click();
};
fooDialog.dialog({
autoOpen: false,
modal: true,
buttons: {
'Ja': submitMethod,
'Nein': function () {
fooDialog.dialog('close');
}
}
});
fooButton.bind('click', dialogOpenMethod);
}
function InitiliazeForm() {
fooButton.button();
fooForm.submit(function () {
alert('doing a submit');
});
}
</script>
<input type="submit" id="fooButton" value="submit it!" onclick="FooMethod();"></input>
<div id="fooDialog">
Dialog info
</div>
</form>
</body>
</html>
what am i doing?
i want a modal-confirmation: user clicks on button, confirmation "do you really want to...?", user clicks "yes", this click unbinds the original click-handler and clicks the button again (which should cause a submit).
what/why is not working?
indeed you need a special case. this demo won't work, unless you set modal: false.
interesting to mention: the original handler (onclick="FooMethod();") is called in modal and non-modal dialog.
EDIT:
i adapted my sample due to graphicdivines answer, to the following:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.js"></script>
</head>
<body>
<form id="fooForm" method="POST" action="">
<script type="text/javascript">
var fooButton;
var fooForm;
var fooDialog;
$(document).ready(function() {
InitializeVariables();
InitiliazeDialog();
InitiliazeForm();
});
function InitializeVariables() {
fooButton = $('#fooButton');
fooForm = $('#fooForm');
fooDialog = $('#fooDialog');
}
function InitiliazeDialog() {
var dialogOpenMethod = function () {
fooDialog.dialog('open');
return false;
};
var submitMethod = function () {
fooButton.unbind('click', dialogOpenMethod);
fooButton.click();
};
fooDialog.dialog({
autoOpen: false,
modal: true,
buttons: {
'Ja': submitMethod,
'Nein': function () {
fooDialog.dialog('close');
}
}
});
var dialogZ = fooDialog.dialog('option', 'zIndex');
fooButton.bind('click', dialogOpenMethod);
}
function InitiliazeForm() {
fooForm.submit(function () {
alert('doing a submit');
});
}
</script>
<input type="submit" id="fooButton" value="submit it!" style="z-index: 9999;"></input>
<div id="fooDialog">
Dialog info
</div>
</form>
</body>
</html>
why?
as you can see here, there's a nasty z-index-checker which i tried to avoid. but it wont' work.

Seems to me that you need to close the dialog, before you re-click the submit. Since modal disables everything on the page, the dialogue must be closed or the submit is not clickable. So your submit method becomes:
var submitMethod = function () {
fooDialog.dialog('close'); // add this line ==============
fooButton.unbind('click', dialogOpenMethod);
fooButton.click();
};

Why are you not specifying HTML form method? The default form method is GET.
So you should have:
<form id="fooForm" method="post" action="">
Action can be something else, it depends on what URL your submission handling logic is.
Edit:
Also instead of clicking the submit button, just submit the form directly.
fooDialog.dialog({
autoOpen: false,
modal: true,
buttons: {
'Ja': function() { $('#fooForm').submit(); },
'Nein': function () {
fooDialog.dialog('close');
}
}
});

Related

Losing Button value on form submit with Confirm dialogue

I'm trying to pass a button value on a form submit in conjunction with a jquery confirm dialogue, but it's not going through. I understand it has something to do with the script using a "form.submit" function but I'm not familiar enough with JS to code a workaround to the problem.
Is there a way to maybe reassign the first button's value to a new JS variable and pass that instead?
I've simplified the form down to its basic elements to make it easy to follow. The data I'm trying to pass in this example is "123" using the button tied to the confirm dialogue script. A second "regular button" is added to demonstrate a successful form submission. Some PHP gathers in the POST data and displays it.
// Results:
// $regularbutton = '456';
// $alertbutton = '';
testpage.php:
<html>
<head>
<script type="text/javascript" src="//code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="//code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script type="text/javascript">
//<![CDATA[
$(function () {
'use strict';
function confirmDialog(title, message, success) {
var confirmdialog = $('<div></div>').appendTo('body')
.html('<div><h6>' + message + '</h6></div>')
.dialog({
modal: true,
title: title,
zIndex: 10000,
autoOpen: false,
width: 'auto',
resizable: false,
buttons: {
Yes: function () {
success();
$(this).dialog("close");
},
No: function () {
$(this).dialog("close");
}
},
close: function() {
$(this).remove();
}
});
return confirmdialog.dialog("open");
}
$('#submit_alert').on('click', function (e) {
e.preventDefault();
var form = document.getElementById('form_alert');
confirmDialog('Confirm', 'Are you sure you want to proceed?', function () {
form.submit();
});
});
});
//]]>
</script>
<link rel="stylesheet" type="text/css" href="//code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
</head>
<body>
<?php
extract($_POST);
echo "button1: $alertbutton <br>";
echo "button2: $regularbutton <br>";
?>
<form method="post" id="form_alert" action="testpage.php">
<button name="alertbutton" value="123" id="submit_alert">Alert Button</button>
<button name="regularbutton" value="456">Regular Button</button>
</form>
</body>
</html>
The value of the button is not commited.
You could inject a hidden field before calling the form.submit():
confirmDialog('Confirm', 'Are you sure you want to proceed?', function () {
$('#form_alert').append('<input type="hidden" name="alertbutton" id="submit_alert_hidden" value="' + $('#submit_alert').val() + '" />');
form.submit();
});
You can use the attribute data-* to pass some datas :
$(function()
{
$(".MyButton").on('click', function(e)
{
// note that some-value is camelCased to someValue
console.log(e.target.dataset.someValue);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="MyButton" name="alertbutton" data-some-value="123" id="submit_alert">Alert Button</button>
<button class="MyButton" name="regularbutton" data-some-value="456">Regular Button</button>

HTML input & button to pass to function using jquery

this is my first question on StackOverflow and my first time working with Chrome Extensions.
I am trying to get user input from an html popup and use jquery to pass that input to a javascript function. The openNewPopup function works here, and the removeATab function works only if I hard code a specific tab index within the function (not passing in the index).
My background.js
function openNewPopup() {
chrome.tabs.create({
index: 0,
url: "http://google.com"
}, function(tab) {
console.log(tab);
});
}
function removeATab(removeTab) {
chrome.tabs.query({currentWindow: true}, function(tabs) {
lastTabId = tabs[removeTab].id;
chrome.tabs.remove(lastTabId);
});
}
My popup_script.js
document.addEventListener("DOMContentLoaded", function() {
var backgroundPage = chrome.extension.getBackgroundPage();
document.querySelector('#newTabButton').addEventListener('click',
function() {
backgroundPage.openNewPopup();
});
document.querySelector('#btnRemove').addEventListener('click',
function() {
var indexRemove = document.querySelector('#tabRemove');
backgroundPage.removeATab(indexRemove);
});
});
And my popup.html
<!DOCTYPE html>
<html>
<head>
<title>Work with tabs</title>
<script src="popup_script.js"></script>
</head>
<body>
<h3>"Open new tab"</h3>
<button id="newTabButton">Make a new tab!</button>
<div class="remove">
Remove tab:<br>
<input type="number" name="tabRemove" id="tabRemove">
<br>
<input type="button" id="btnRemove" value="Remove">
</div>
</body>
</html>

Can a user control be rendered on the click event of a button?

I have created a user control which actually creates an empty dialog box for application form. I wanted to render this user control on the click event of a button(like we render partial views). I have an .aspx page that contains a button. On clicking the button the user control that creates a dialog, opens up. Below is the jquery code written to open the dialog in a user control:
Jquery
createAliasPopUpForm: function (rowNumberId) {
// debugger;
var self = this;
var dat = $("input[id*='hdnAliasRecordmetaData']").val();
self.metaDataColumns = JSON.parse(dat);
//debugger;
// now bind update data to pop up
if (self.metaDataColumns.length > 0) {
if (rowNumberId != 'undefined' && rowNumberId != null) {
self.rowNumber = rowNumberId;
// fill alias record to meta data
var listdata = $("input[id*='hdnAliasRecordList']").val();
var aliasList = JSON.parse(listdata);
if (aliasList.Rows.length > 0) {
$.each(aliasList.Rows, function (i, val) {
if (this.RowNumber == rowNumberId) {
self.fillAliasRecord(self.metaDataColumns, this.Columns);
return false;
}
});
}
}
else {
// right now cloumn list has MDM record value so need to clear that value only
$.each(self.metaDataColumns, function (i, val) {
this.Value = '';
});
}
// sort array
//self.metaDataColumns.sort(common.dynamicSortMultiple("GroupOrder", "MetadataId"));
self.metaDataColumns.sort(common.dynamicSortMultiple("GroupOrder", "ColumnNumber"));
self.createPopupHtml(self.metaDataColumns, rowNumberId);
self.init();
$('#popUpHeader').find('h4').remove();
$('#popUpHeader').append(' <h4 class="modal-title" >Alias Record</h4>');
$("#updateConfirmPopUp").dialog({
autoOpen: true,
width: 600,
resizable: false,
draggable: false,
modal: true,
show: { effect: 'blind' }
});
}
},
userControl
<%# Control Language="C#" AutoEventWireup="true" CodeFile="AddAlias.ascx.cs" Inherits="OCM.Phoenix.WebToolsFramework.Server.Modules.MDMAdmin.AddAlias" %>
<script language="javascript" type="text/javascript" src='<%= ResolveClientUrl("~/scripts/jquery-1.4.2.min.js") %>'></script>
<script language="javascript" src="../Scripts/jquery.js" type="text/javascript"></script>
<script language="javascript" src="../Scripts/jquery-ui.js" type="text/javascript"></script>
<script language="javascript" src="../Scripts/bootstrap.min.js" type="text/javascript"></script>
<script language="javascript" src="../Scripts/Common.js" type="text/javascript"></script>
<script language="javascript" src="../Scripts/AdminEdit.js" type="text/javascript"></script>
<asp:HiddenField ID="hdnAliasRecordmetaData" runat="server" />
<asp:HiddenField ID="hdnAliasRecordList" runat="server" />
<script>
$(function () {
adminEditForm.createAliasPopUpForm();
});
</script>
code behind file just contains the load event
aspx page
<%# Page Language="C#" AutoEventWireup="true" CodeFile="AddAliasPage.aspx.cs" Inherits="Modules_MDMDataHub_AddAliasPage" %>
<%# Register Src="UserControls/AddAlias.ascx" TagPrefix="uc" TagName="alias" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<script src="Scripts/jquery.js"></script>
<script src="Scripts/jquery-ui.js"></script>
<script src="Scripts/AdminEdit.js"></script>
<body>
<form id="form1" runat="server">
<div>
<uc:alias ID="alias" runat="server" />
<br />
<asp:button ID="btn1" OnClick="btn1_Click" runat="server"> </asp:button>
</div>
</form>
</body>
</html>
Although, I have created the click event of the button, that calls the below function to render the html of the user control. but its actuaaly not working as it keeps giving me an errer as the hdnmetadatavalue must be inside the form tag. I did it but still i get the error. Am i doing something wrong here? Please help
private string RenderControl()
{
var sb = new System.Text.StringBuilder();
using (var stWriter = new System.IO.StringWriter(sb))
using (var htmlWriter = new HtmlTextWriter(stWriter))
{
var p = new Page();
var ctrl = (AddAlias)p.LoadControl("~/Modules/MDMDataHub/UserControls/AddAlias.ascx");
ctrl.Visible = true;
// do your own init logic if needed
p.Controls.Add(ctrl);
ctrl.RenderControl(htmlWriter);
return sb.ToString();
}
}
By reviewing your code:
var ctrl = (AddAlias)p.LoadControl("~/Modules/MDMDataHub/UserControls/AddAlias.ascx");
// ... other lines
ctrl.RenderControl(htmlWriter);
I assume you are trying to call RenderControl method for user control to HTML rendering, where the page will raise form tag exception if the user control was rendered outside defined form tag with runat="server".
Use Page.VerifyRenderingInServerForm method on page code behind to ensure all user controls render properly:
public override void VerifyRenderingInServerForm(Control control) {
// nothing to override here
}
public override boolean EnableEventValidation {
get { return false; }
}
Reference: UserControl's RenderControl is asking for a form tag in (C# .NET)

How to pass parameters to javascript function that are defined outside the form tag?

i am trying to pass a parameter to a javascript function thats been defined outside the tag.but when i try to use it in the javascript function it shows undefined.i am using alert to print the value both in the jsp page and in javascipt function...please help
<html>
<script type="text/javascript">
js_valueDate = '<%=valueDate%>';
alert(js_valueDate) **//displays correct value here**
</script>
<body>
<form>
....some html...
<td width=27%><input type=text name="ValDate"
onchange = "javascript:validateDate(document.f1.ValDate,js_valueDate);"></td>
......some html....
</form>
</body>
</html>
and this is my javascript function:
function validateDate(ValDate,origValDate) {
var valueDate=ValDate.value;
var OrigvalueDate=origValDate.value;
confirm(valueDate);
confirm(OrigvalueDate); **//displays undefined here**
var hh=replaceAll(valueDate,'-','');
confirm(hh);
if (replaceAll(valueDate,"-","")<=valueDate<=replaceAll(OrigvalueDate,"-","")) {
return true;
} else {
alertPopup("Please enter a valid value date");
document.f1.ValDate.focus();
return false;
}
}
Since you are passing the value itself there is no need of the statement var OrigvalueDate=origValDate.value;
Here is a small example which i have written which explains both the situation
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Check </title>
<script>
function display(v)
{
var d=v.value;
alert(v);
alert(d);
}
jval="qwerty";
</script>
</head>
<body>
<input type="button" value="check" onclick="javascript:display(jval)"/>
</body>
</html>
Try something like this. This 'll help you
<html>
<script type="text/javascript">
js_valueDate = '<%=valueDate%>';
alert(js_valueDate) **//displays correct value here**
var ValidationHandler = {
validateDate:function(ValDate,origValDate){
var valueDate=ValDate.value;
var OrigvalueDate=origValDate.value;
confirm(valueDate);
confirm(OrigvalueDate); **//displays undefined here**
var hh=replaceAll(valueDate,'-','');
confirm(hh);
if (replaceAll(valueDate,"-","")<=valueDate<=replaceAll(OrigvalueDate,"-",""))
{
return true;
}
else
{
alertPopup("Please enter a valid value date");
document.f1.ValDate.focus();
return false;
}
}
};
</script>
<body>
<form>
....some html...
<td width=27%><input type=text name="ValDate"
onchange = "javascript:ValidationHandler.validateDate(document.f1.ValDate,js_valueDate);"></td>
......some html....
</form>
</body>
</html>

Dialog Box with Input Element

I want to have a dialog window with an input. I could use the default jQuery-ui one, but I am using one that incorporate bootstrap. However, the input only appears the first time that it is opened, any subsequent times the dialog is opened, the input is missing. How would this be remedied?
Here is the HTML:
<!DOCTYPE html>
<html>
<head lang="en">
<link rel="stylesheet" href="../bower_components/jquery-ui/themes/base/jquery.ui.all.css">
<link rel="stylesheet" href="../bower_components/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="../bower_components/bootstrap3-dialog/css/bootstrap-dialog.min.css">
<link rel="stylesheet" href="../bower_components/bootstrap-datepicker/css/datepicker3.css">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h3>Hello!</h3>
<div>
<span>Enter a Zip Code: </span>
<input type="text" id="zip">
<button id="getEvents" class="btn btn-primary">Get events!</button>
</div>
<div class="datepicker"></div>
<div id="events"></div>
<button id="addItemButton">Add an item</button>
<div id="addItemDialog"><input type="text" id="newItem"></div>
<script src="../bower_components/jquery/jquery.min.js"></script>
<script src="../bower_components/jquery-ui/ui/jquery-ui.js"></script>
<script src="../bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="../bower_components/bootstrap3-dialog/js/bootstrap-dialog.js"></script>
<script src="../bower_components/bootstrap-datepicker/js/bootstrap-datepicker.js"></script>
<script src="js/calendar.js"></script>
</body>
</html>
Here is the JS:
$(function () {
"use strict";
var url,
year,
month,
zip,
date,
events = [],
newItem;
$("#addItemDialog").hide();
$(".datepicker").datepicker({dateFormat: "yy-mm-dd"}).click(function(){
$("#events").empty();
date = $(".datepicker").datepicker("getDate");
//console.dir(date.toISOString().substr(0, 10));
$(events).each(function(i, event){
//console.log(event);
if(event.date.substr(0, 10) === date.toISOString().substr(0, 10)){
console.log(event.title);
$("#events").append("<h4 class='event'>" + event.title + "</h4>");
}
});
});
$("#getEvents").on("click", function () {
zip = $("#zip").val();
if(isValidUSZip(zip)){
zip = zip.substr(0, 5);
getCalendar();
}else{
BootstrapDialog.show({
message: "You must enter a valid zip code!",
buttons: [{label:"OK", action: function(dialog){dialog.close();}}],
draggable: true
});
}
});
function isValidUSZip(sZip) {
return /^[0-9]{5}(?:-[0-9]{4})?$/.test(sZip);
}
function getCalendar() {
$.ajax({
type: "GET",
url: "http://www.hebcal.com/hebcal/?v=1&cfg=json&nh=on&nx=on&year=now&month=x&ss=on&mf=on&c=on&zip=" + zip +"&m=72&s=on",
success: function (data) {
console.dir(data);
$(data.items).each(function(index, item){
//console.dir(item.date.substr(0, 10));
events.push(item);
});
}
});
}
$("#addItemButton").on("click", function(){
BootstrapDialog.show({
message: $("#newItem"),
buttons: [{
label: "Enter",
action: function(dialog){
newItem = $("#newItem").val();
events.push({date: new Date(date).toISOString(), title: newItem});
dialog.close();
}
}]
});
});
});
I took a time and make this fiddle, aparently everything is working fine:
I doubt about this line for a moment, but still uncommented is going right:
$(function () {
//"use strict";
var url,
year,
month,
zip,
date,
events = [],
newItem;
http://jsfiddle.net/r2FyC/3/

Categories