I am trying to call a javascript modal that says 'no units selected' if the user clicks a 'remove' button without clicking at least one checkbox next to a unit on a webpage. If no units are present, and the user clicks the 'remove' button, the script successfully executes and the 'not units selected' modal appears. However, if units are present, an error is thrown and occurs at the sixth line of the script (if (document.units('Select...etc) ) ). The error states the object (in this case, units) is not a function.
The script:
<SCRIPT>
function CheckTheForm()
{
var found = false;
var PersonsIDs = "";
for (i=1;i<=document.units.add_counter.value;i++)
if (document.units('SelectUnit' + i).checked == true)
{
if (PersonsIDs != "")
PersonsIDs += ",";
= PersonsIDs += document.units('SelectUnit' + i).value;
document.units.action = "UnitsRemove.asp?ID=" + PersonsIDs + "&RA=Units.asp";
found = true;
}
if (found==false)
{
alert("No units have been selected.");
return false;
}
//alert(document.units.action);
}
</SCRIPT>
The form that calls the script:
The button pressed to remove the units:
Any help would be greatly appreciated!
I'm guessing you're trying to do this
document.units['SelectUnit' + i].checked
which is how you'd access an objects properties with a dynamic key
Related
I have multiple radio buttons when I open these radio button reports in different tabs and after that I comes to any random tab report and click on next page button or previous page button it renders the last open tab's reports data. It is due to reason it goes to server side ReportViewer.aspx.cs and at there I had created switch case on the bases of radio buttons and that code maintains last value of radio button which opened in last tab. So here I'm stuck how to refresh the radio button value on tab change, It should detect now which radio button reports request came. Below Image shows the radio buttons and code also given below
if (reportFilterParams != null)
{
if (reportFilterParams.SelectedReportName == PurchaseSheetChildReport.PurcaseDepotReceievedSheet)
{
errorMessage.Text = "Report Not Found";
}
else if (reportFilterParams.SelectedReportName == PurchaseSheetChildReport.PurcaseSummaryCircleAndGrowerWise)
{
errorMessage.Text = "Report Not Found";
}
else if (reportFilterParams.SelectedReportName == PurchaseSheetChildReport.PurcaseSummaryCircleAndGrowerWiseDetail)
{
reportPath = Server.MapPath("../../Reports/Grower/PurchaseSummaryCricleAndGrowerWiseDetail.rpt");
ReportDocument.Load(reportPath);
ReportDocument.DataDefinition.FormulaFields["ReportName"].Text = "'Purchase Summary Circle And Grower Wise Detail'";
PurchaseSheetSummaryCPWiseAndCenterWise();
}
}
Image for radio button display
I resolved it in this way, I just set the tab title with radio button value on client side when give submit call and get the current tab's value via c# code that is given below and then make session with each radio button when click on next or previous page button it goes to the server with tab value and get the session value with the tab title value.
[Set title with radio button value in browser tab see in image][1]
[1]: https://i.stack.imgur.com/0YOpT.jpg
//client side code in javascript
if (reportValueForName != undefined)
window.document.title = $("input:checked + label").text() + "_" + reportValueForName;
else
window.document.title = $("#reportNameMaster").text() + " Report";
//Server side code
string curentTabReportName = GetTabTitle();
string resultString = Regex.Match(curentTabReportName, #"\d+").Value;
if (resultString != "")
{
reportFilterParams.SelectedReportName = Convert.ToInt32(resultString);
}
public string GetTabTitle()
{
string currentReportTabTitle = "";
Process[] procsChrome = Process.GetProcessesByName("chrome");
if (procsChrome.Length <= 0)
{
Console.WriteLine("Chrome is not running");
}
else
{
foreach (Process proc in procsChrome)
{
//the chrome process must have a window
if (proc.MainWindowHandle == IntPtr.Zero)
{
continue;
}
currentReportTabTitle = proc.MainWindowTitle;
}
}
return currentReportTabTitle;
}
//Set the session value
Session["reportFilterParams" + reportFilterModel.UserName + reportFilterModel.MenueId + reportFilterModel.SelectedReportName] = reportFilterModel;
//Get the session value
if (Session["reportFilterParams" + Session["UserName"] + int.Parse(Request.QueryString["id"] + reportFilterParams.SelectedReportName)] as ReportFilterModel != null)
{
reportFilterParams = Session["reportFilterParams" + Session["UserName"] + int.Parse(Request.QueryString["id"] + reportFilterParams.SelectedReportName)] as ReportFilterModel;
}
I am trying to get a data from a password protected webpage using webbrowser , which uses a div container with 3 JQuery data fields. The 2nd field depends on the 1st one, and the 3rd one of the 2nd one.I need to set those 3 comboboxes and hit submit in order to get the data I want to scrape. The problem is that once the 1st combobox changes, it invokes a function which populates the 2nd and 3rd boxes. I can't figure out how to invoke this function...
This is how the first combobox looks like:
Select s[DCOM1] Selection1
I managed to set the 1st combobox, however the big problem that I have is to invoke viewStep.onSChanged() , which supposed to populate the 2nd box, I just can't make it work.
The onSChanged function is located in a Jquery js. file
self.onsChanged = function(selectadj) {
self.viewBasicsUpdated = true;
log.debug('onsChanged');
if (self.s) {
self.adjEnabled = false;
self.adj = null;
self.auctionType = 'S';
controller.ds.getadjList(self.s.id, function(response) {
controller.applyUpdates(function() {
self.adjList = response.data;
// Add "Add adj" option (as first in array).
self.adjList.unshift({
id : ADD_adj_ID,
fullName : controller.locale.getMessage('app.label.add.adj')
});
self.adjEnabled = true;
self.standardEnabled = true;
self.vixEnabled = (StringUtils.trimWS(self.s.vixFlag) === 'Y') ? true : false;
self.offsiteEnabled = (StringUtils.trimWS(self.s.offsiteFlag) === 'Y') ? true : false;
self.titOnlyEnabled = (StringUtils.trimWS(self.s.titOnlyFlag) === 'Y') ? true : false;
self.salType = self.s.salType;
self.titProcurementFlag = (StringUtils.trimWS(self.s.titProcurmentFlag) === 'Y') ? true : false;
//Selects the adj when a new adj is added.
if(selectadj){
angular.forEach(self.adjList, function(object, index) {
log.debug("object.id++"+object.id);
if(object.id===self.newadjId){
self.adj=object;
log.debug("self.newadjId++"+object.id);
}
});
}
});
});
}else{
controller.applyUpdates(function() {
self.adj = null;
self.adjEnabled = false;
self.auctionType = 'S';
self.standardEnabled = false;
self.vixEnabled = false;
self.offsiteEnabled = false;
self.titOnlyEnabled = false;
self.salType = null;
self.titProcurementFlag = false;
});`
}
};
I have tried to invoke the function in many different options including invokescript, posting an identical post request as the one I see with Fiddler (I guess it fails since the cookie is different) but everything fails. Is there a way to execute this function?
When setting values on input controls with Javascript the DOM events might not fire, depending on how the values are set.
Instead of trying to execute the very same function that the webpage would normally trigger, in this case self.onsChanged, fire the event on the control that you updated.
$("#selectBox1").val("Value A");
$("#selectBox1").change();
https://api.jquery.com/change/
I have button called sales and it have a JavaScript popup when I click on cancel it postback and the values in the form are inserted but when i click on ok it does not post back and the values in the form does not go in the database ( the JavaScript button is actually print call and when button is clicked it asks for print when print dialog box is open it does not post back and data is not inserted in the database)
here is the javascript code
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
__doPostBack();
}
else {
__doPostBack();
}
}
here is the code for button click
<asp:Button ID="btnaddsale" runat="server" Text="Sale" OnClick="btnaddsale_Click" OnClientClick="javascript:confirmAction('printable')"/>
Ok, couple of notes for you:
You want a postback in either case.
Your <asp:Button> will automatically do a postback either way, so you don't need to call __doPoskBack(); in this scenario.
Major issue here is that, if you want a postback, it will happen immediately when the function exits, effectively canceling out the print dialog too soon. To avoid this, we will use a JavaScript trick that will check if the document has focus, and only when it does (when user exits print dialog in the browser) will we return and allow the postback to occur.
To fix the issue,
First: Make the function return true; when user cancels, and wait for focus and then return true if the user wants to print:
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
// Check focus after user exits print dialog and then return true for the postback
var document_focus = false;
$(document).focus(function () { document_focus = true; });
setInterval(function () { if (document_focus === true) { return true; } }, 500);
}
else {
return true;
}
}
Then, change the JavaScript code to use the return statement in the OnClientClick event:
<asp:Button ID="btnaddsale" runat="server" Text="Sale"
OnClick="btnaddsale_Click"
OnClientClick="javascript:return confirmAction('printable')"/>
Update based on comments and your changed requirement:
Here's a snippet to make the script pop up after the postback. So you will insert values to database, and then add the print script / confirm dialog on page load using Page.ClientScript.RegisterStartupScript()
Note I don't recommend to embed the script in your C# code, so I'd suggest to take your confirmAction() function and place it (if not already) into a separate "yourScripts.js" file and then just call the function name when the page is loaded using jQuery. Here's an example:
In your master page or page header: This file should contain the confirmAction() function
<script type="text/javascript src="path/to/yourScriptsFile.js">
Then, in code-behind:
protected void Page_Load(object sender, EventArgs e)
{
// Only display script on PostBack, not initial page load
if (IsPostBack)
{
Page.ClientScript.RegisterStartupScript(
this.GetType(),
"confirmAction",
#"<script type=""Text/Javascript"">$(document).ready(function() { confirmAction('printable'); });</script>");
}
}
Also note, since you will NOT want a postback now, the confirmAction function should no longer return true; or use the trick code I posted above, and will just return false:
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
return false;
}
I'm facing some issue with returning value back to the parent page.
Please kindly help.
I have a gridview that allow users to add new record at the row, but users also can click on the Search button on the row, and I will show a pop up with the below code.
TextBox txtCarNo = gvLookup.FooterRow.FindControl("txtNo") as TextBox;
System.Text.StringBuilder s = new System.Text.StringBuilder();
s.Append("<script language='javascript' id='SearchResult'> " );
s.Append("var WinSettings = 'dialogHeight:400px ; dialogWidth: 550px ;center: Yes ;resizable: No;status: no'; ");
s.Append("javascript: window.showModalDialog('Search.aspx?no=" + txtNo.Text.Trim().ToUpper() + "','',WinSettings); ");
s.Append("</script > ");
if ((!ClientScript.IsStartupScriptRegistered("SearchResult")))
{
ClientScript.RegisterStartupScript(this.GetType(), "SearchResult", s.ToString());
}
At the child page, there will be another gridview that shows the search result, and users can click on one of the row to return the number back to the parent page.
I thought of using Session to pass the value back, but when showing the ShowModalDialog, the code at the parent page already went through, meaning Session won't work on this scenario.
Please advise how do I return a value to the parent page.
Appreciate very much.
Example from Wrox
When you call showModalDialog you do this:
var oReturnValue = showModalDialog(....);
Within showModalDialog, assuming your textboxes have IDs of "txtForename" and "txtSurname":
<body onbeforeunload="terminate();">
function terminate()
{
var o = new Object();
o.forename = document.getElementById("txtForename").value;
o.surname = document.getElementById("txtSurname").value;
window.returnValue = o;
}
Then continuing in your main window:
alert(oReturnValue.forename + "\n" + oReturnValue.surname);
We are using Sharepoint 2007 In which on master page we have Asp Image button. We want to set this image button as default button for enter key press. We tried some ways but not getting success.
Turned out more complicated than I thought but possible nonetheless. First of all, make sure the ID of your control is static:
<asp:ImageButton runat="server" ID="MyImageButton" ClientIDMode="Static" ImageUrl="pic.gif" OnClick="ImageButtonClicked" />
Now what you need is the following JavaScript code in your .aspx or .master page:
<script type="text/javascript">
var DEFAULT_BUTTON_ID = "MyImageButton";
// Mozilla, Opera and webkit nightlies currently support this event
if (document.addEventListener) {
// A fallback to window.onload, that will always work
window.addEventListener("load", HandleDefaultButton, false);
// If IE event model is used
} else if (document.attachEvent) {
// A fallback to window.onload, that will always work
window.attachEvent("onload", HandleDefaultButton);
}
function HandleDefaultButton() {
var inputs = document.getElementsByTagName("input");
//attach event for all inputs
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
//maybe already got handler so add instead of override
if (document.addEventListener)
input.addEventListener("keypress", InputElement_KeyPressed, false);
else if (document.attachEvent)
input.attachEvent("onkeypress", InputElement_KeyPressed);
}
}
function InputElement_KeyPressed(evt) {
if (DEFAULT_BUTTON_ID && DEFAULT_BUTTON_ID.length > 0) {
//old IE event module
if (typeof evt == "undefined" || !evt)
evt = window.event;
var keyCode = evt.keyCode || evt.which;
if (keyCode === 13) {
var oButton = document.getElementById(DEFAULT_BUTTON_ID);
if (oButton) {
oButton.click();
return false;
} else {
alert("---DEBUG--- default button is defined but does not exist (" + DEFAULT_BUTTON_ID + ")");
}
}
}
return true;
}
</script>
You just need to define the real ID as the value of DEFAULT_BUTTON_ID and the code will automatically attach keypress event to all inputs (text, checkbox and radio) and when Enter is pressed, the button defined as default will get clicked.
As you're using SharePoint is means window.onload is already in use so we must add our own event not override it.
You can set the DefaultButton property to the id of the button you want to be default in the form tag.