Refactoring Javascript code from Aspx file - javascript

I am refactoring the web project,where java script and css code is written inside the .aspx file.Now I am removing java script and css code from the aspx files and maintaining that the code in respective css and js files with their reference in aspx files.
It is straight forward for me if java script code is written in one place and inside the funtion.Here in the example code not all java script code is inside the function and some of the script are inside the div block.I am not able to put these script in separate file.Moreover I am new bee in Java script and web development please help me on this.
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
-------code-----------
</script>
<% Html.EnableClientValidation(); %>
<% using (Html.BeginForm())
{%>
<%: Html.ValidationSummary(true) %>
<div class="formColWhole" style="width: 935px;">
<script type="text/javascript">
document.body.style.cursor = 'default';
document.forms[0].action = '<% = ViewData["RegisterPageUrl"].ToString() %>';
function IndicateProcessing() {
if (typeof (Page_ClientValidate) == 'function') {
if (Page_ClientValidate() == false) { return false; }
}
var cancelButton = document.getElementById("<% = buttonCancel.ClientID %>");
if (cancelButton != null) {
cancelButton.disabled = true;
}
document.body.style.cursor = 'wait';
return true;
}
function submitForm() {
IndicateProcessing();
// _gaq.push(['_trackEvent', 'Register', 'Register submit Click', 'Register submit']);
// avoid duplicate submission
var button = $("#buttonSend");
button.attr('disabled', true).html('');
document.forms[0].submit();
}
</script>
</div>
<div class="formColWhole" style="width: 100%;">
--------code----
</div>
<script type="text/javascript">
var selectCountryText = document.getElementById("<% = selectCountry.ClientID %>").value;
var regions = document.getElementById("region");
regions.firstChild.text = selectCountryText;
</script>
</asp:Content>

Related

Javascript - Share Variables over different <script> tags

I have one test.html file with two <script> tags. I need to share a variable from one to another..
Sample code:
<script type="text/javascript">
var test = false;
function testing() {
test = true;
alert('I am inside..');
}
testing();
</script>
...
<script type="text/javascript">
if (test == true) {
alert('working');
} else {
alert('failed');
}
</script>
The output is always:
I am inside..
failed
I also tried to use the window class but it doesn't matter.. (window.test)
What I have to do to get the 'working' alert?
Thanks if anyone can help me. I saw some similar questions, but the answers wasn't a solution for me.
EDIT:
The original code (simplified):
<head>
...
<script type="text/javascript" src="detectblocker.js"></script>
<!-- GitHub: https://github.com/sitexw/BlockAdBlock/ -->
...
</head>
<body>
<script type="text/javascript">
var blocker = false;
function adBlockDetected() {
blocker = true;
alert('inside');
}
if(typeof blockAdBlock === 'undefined') {
adBlockDetected();
} else {
blockAdBlock.onDetected(adBlockDetected);
}
blockAdBlock.setOption({
checkOnLoad: true,
resetOnEnd: true
});
</script>
<div class="header">
...
</div>
<div class="content_body">
<div class="requirs">
<ul>
...
<script type="text/javascript">
if (blocker == true) {
document.write("<li>enabled!</li>")
} else {
document.write("<li>disabled!</li>")
}
</script>
...
</ul>
</div>
</div>
...
</body>
The output is an alert() "inside" and the <li> "disabled".. (Blocker is enabled..).
The only difference I can see is on the end of the first <script> tag:
blockAdBlock.setOption({
checkOnLoad: true,
resetOnEnd: true
});
So why the snippet is working and my code not? Confusing...
If you do not use var before a variable it becomes a global variable like
test = true;
The variable test will be true during the page and also in your next scripts and functions.
Try this:
<script type="text/javascript">
var test = false;
function testing() {
var test = true;
alert('I am inside..');
}
testing();
</script>
...
<script type="text/javascript">
if (test == true) {
alert('working');
} else {
alert('failed');
}
</script>
There are two ways of doing it.
1) create a hidden element and set your variable from your first script to attribute of that element.
This is your hidden element
<input type="hidden" id="hiddenVar"/>
and can set it in javascript as
document.getElementById("hiddenVar").setAttribute("myAttr",test)
Now you can get it in next script as
document.getElementById("hiddenVar").getAttribute("myAttr")
2) By .data() you can read about it here

jquery inside User Control created dynamically

I've created an User Control where I have a button. And when this button is clicked a jquery function is executed. The jquery function is inside the User Control page.
Now i'm trying to add this User Control dynamically in my page, inside an UpdatePanel.
The problem is that my button is not working.
After i google it, i found out that maybe the problem is in using jquery inside ajax UpdatePanel. After every asynchronous postback the jquery script is lost. So the idea is to rebind my jquery function in every asyn postback. But in the all answers that i found, they kinda suppose that the script manager is in User control and it's not in my case.
Here my jquery fucntion
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#<%= idButtonLeft %>").bind("click", function () {
var options = $("#<%= idListDestinataire %> option:selected");
for (var i = 0; i < options.length; i++) {
var opt = $(options[i]).clone();
$(options[i]).remove();
$("#<%= idListSource %>").append(opt);
}
});
$("#<%= idButtonRight %>").bind("click", function () {
var options = $("#<%= idListSource %> option:selected");
for (var i = 0; i < options.length; i++) {
var opt = $(options[i]).clone();
$(options[i]).remove();
$("#<%= idListDestinataire %>").append(opt);
}
});
});
</script>
the code to add my User control dynamically
Dim CListBox As UserControl = LoadControl("DragDropList.ascx")
CListBox.ID = "CListBox" + i.ToString()
CType(CListBox, DragDropList).idListSource = "ListLeft" + i.ToString()
CType(CListBox, DragDropList).idListDestinataire = "ListRight" + i.ToString()
CType(CListBox, DragDropList).idButtonLeft = "idButtonLeft" + i.ToString()
CType(CListBox, DragDropList).idButtonRight = "idButtonRight" + i.ToString()
UpdatePanel1.ContentTemplateContainer.Controls.Add(CListBox)
Panel1.Controls.Add(CListBox)
in my page i have this
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:Panel ID="Panel1" runat="server">
</asp:Panel>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ImageButton1" />
</Triggers>
</asp:UpdatePanel>
<asp:ImageButton ID="ImageButton1" ImageAlign="Right" EnableViewState="false" ImageUrl=".\image\ajouter.png" runat="server" AlternateText="Ajouter" OnClick="AjouterC"/>
So please any ideas to help.
Thank you
When i changed the trigger on PostBackTrigger, it's working but i want it in asynchrone postback. and still don't know why it's not working!
Use This
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
if (args.get_error() == undefined) {
$(function () {
//Your script
});
}
}
</script>
This will work on post back that your update panel is giving to you.

Passing string variable in alert box

I have below script where im passing scriptlet variable to javascript function. But there is no alert box displaying.. Please let me what im missing here..
<script language="JavaScript">
window.onload = function(){
<%
String res = request.getParameter("Message");
%>
var Value = "<%=res%>";
alert(Value);
document.Form.submit();
};
</script>
Thanks in advance
try this....
<script type="text/javascript">
window.onload = function(){
<%
String res = request.getParameter("Message");
%>
var Value = <%=res%>;
windows.alert(Value);
document.Form.submit();
};
</script>
What you need to use is <%= ... %>. Try using this:
<script type="text/javascript">
window.onload = function(){
<%
String res = request.getParameter("Message");
%>
var Value = <%=res%>;
alert(Value);
document.Form.submit();
};
</script>
#John Why you creating scriptlet tag inside javascript. Instead try using this,
<%
String res = request.getParameter("Message");
%>
<script type="text/javaScript">
window.onload = function(){
var Value = "<%=res%>";
alert(Value);
document.Form.submit();
};
</script>
else try using jquery plugin for your purpose,
<%
String res = request.getParameter("Message");
%>
<script type="text/javaScript">
$(document).ready(function() {
var Value = "<%=res%>";
alert(Value);
$('form#myForm').submit();
});
</script>

How to use your js file in default.aspx page?

This is my JavaScript.js
function checkAllCheckBox() {
var all_checkboxes = $('input[type="checkbox"]');
if (all_checkboxes.length === all_checkboxes.filter(":checked").length) {
$('#' + '<%=btnSubmit.ClientID %>').css("display", "block");
$('#' + '<%=btnNextSection.ClientID %>').attr("disabled", "disabled");
}
else {
$('#' + '<%=btnSubmit.ClientID %>').css("display", "none");
$('#' + '<%=btnNextSection.ClientID %>').attr("disabled", "");
}
}
But when i call it to my Default.aspx file , it is not working
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="JavaScript.js" type="text/javascript"></script>
I even created that way but it is still not working..
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script language="javascript" src='<%# ResolveClientUrl("JavaScript.js")%>' type="text/javascript"></script>
Any Help appreciate
Thanks
Change your method signature and pass in the btnSubmitClientId and btnNextSectionClientId so it would look something like this:
chkList.Attributes.Add("onclick", "checkAllCheckBox('#' + '<%=btnSubmit.ClientID %>', '#' + '<%=btnNextSection.ClientID %>')");
And then your JavaScript function would look like this:
function checkAllCheckBox(btnSubmitClientId, btnNextSectionClientId) {
var all_checkboxes = $('input[type="checkbox"]');
if (all_checkboxes.length === all_checkboxes.filter(":checked").length) {
$(btnSubmitClientId).css("display", "block");
$(btnNextSectionClientId).attr("disabled", "disabled");
}
else {
$(btnSubmitClientId).css("display", "none");
$(btnNextSectionClientId).attr("disabled", "");
}
}
You can use <%= %> notation only when JavaScript code is inside of ASPX page markup inside of <script> ... </script> block

Disabling elements when deselecting a checkbox

I have a checkbox, a drop down list and a text box.
I want to disable the drop down and text box on deselecting the checkbox.
Following is what I have on my view -
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<%Html.CheckBox("chkCheckMe", new { enabled = Convert.ToBoolean(ViewData["ShowFlag"])}); %>>
<%Html.DropDownList("ddlModes", new SelectList(new string[]{"Auto", "Manual"}), new { enabled = Convert.ToBoolean(ViewData["ShowFlag"])}); %>
<%Html.TextBox("txtSample", new {enabled = Convert.ToBoolean(ViewData["ShowFlag"]) }); %>>
</asp:Content>
Can I do this using script?
Thanks,
Kapil
This should get you started
<script type="text/javascript">
window.onload = function() {
var c = document.getElementById("yourCheckboxID");
c.onclick = toggleElements;
}
function toggleElements() {
var c = document.getElementById("yourCheckboxID");
var d = document.getElementById("yourDropDownID");
var t = document.getElementById("yourTextBoxID");
d.disabled = t.disabled = c.checked;
}
</script>

Categories

Resources