Unable to call javascript in CSHTML - javascript

I am pretty new to MVC. I am trying to call a javascript function from a view page (button click) but I am unable to call it .I have the javascript function in a seperate file .I have added the reference of the script file in the view page(CSHTML).
Code:
<input type="submit" value="enter" onclick="IsFirstNameEmpty();">
Javascript Function
function IsFirstNameEmpty() {
if (document.getElementById('TxtFName').value == "") {
return 'First Name should not be empty';
}
else { return ""; }
}

Simple example : https://jsfiddle.net/8mhuL839/
You do everything fine (I trust your words about You've correctly included js-file). But You just doesn't do anything with your returned string.
In my example I just put text into alert-dialog.
Maybe you want to show this text in some label, then just do next :
document.getElementById('LblValidation').value = returnedText;
where LblValidation is Id of some Label that will contains your string, and returnedText is string that you try to return from your function.
<input type="submit" value="enter" onclick="IsFirstNameEmpty();"/>
<input type="text" value="text" id="TxtFName" />
<script type="text/javascript" >
function IsFirstNameEmpty() {
if (document.getElementById('TxtFName').value == "") {
alert( 'First Name should not be empty');
}
else { alert(""); }
}
</script>

In general, there is no difference between what you did without the mvc paradigm. Pay only attention to the fact that if the script is inside a partial page it could be executed more than once or not in the moment you expect (for example you could call a function before it is defined because of the partial views loading order). In this simple scenario, I think you have just to be sure that the script containing the definition of the function is really included in the resulting web page. The simplest way to do this is by checking the page source in the browser.

Related

Comparing values with javaScript then redirect to another url if true

edit- the problem was in the redirection and Solved by Ahmed with the immediately invoked Function Expression aka IIFE
problem redirecting to another page, values are a string and the integer "CharFields" .. else statement works fine but the if statement when I type it correct the page just refreshes and nothing happens.
I made java function to get variables from a user input trcode
and made Django print the model in an input value those two works fine I tested them with printing,, the problem is in comparing the values and redirecting to the another URL
function readText () {
var value1 = document.getElementById("trcode").value;
var value2 = document.getElementById("trfcode").value;
if (value1 === value2) {
location.href="http://127.0.0.1:8000/myposts";}
else {
alert("You typed: " + "Wrong Password");}
}
<form onsubmit="return readText();">
<tr><td height="18" class="subheaderboldtext"> Enter Code:
<input id="trcode" maxlength="8" class="box">
<input class="submit" type="submit" value="SUBMIT">
<button id="trfcode" value="{{ user.profile.trf_code }}">z</button>
I have made some changes to your code. The button with id trfcode is being assigned a value already called user.profile.trf_code. If you replace it with the value you are trying to match it will work fine. For testing purposes I have changed your code a bit and have assigned it a value of z. Upon typing z in input and clicking submit gives me a +ve result.
I am guessing your main concern is reading the value of user-profile user.profile.trf_code. So you may wanna debug this and find out if you are getting a proper value back which you are expecting.
Few tips for debugging. When you are in such a situation, please first look at the values of each element and find out even if you are getting the values back. Then next step to find out if you are getting the same values or not and so on.
Putting value="z" makes this working. Please note that I have added extra logs and an alert. Please feel free to remove it.
EDIT:
If you see in the form, I have added a function wrapping your function. This is called immediately invoked Function Expression aka IIFE which basically is a function and can be called right there. Form creates an event, that event has a method called preventDefaults() which prevents the page from reloading or refreshing upon everytime you submit. I have wrapped your method under an IIFE to prevent the page from refreshing and then called your function. I would highly recommend you adding this as a part of your question though.
Your form,
<form onsubmit="return (function(event) { event.preventDefault(); readText()}) (event)">
<tr>
<td height="18" class="subheaderboldtext"> Enter Code:
<input id="trcode" maxlength="8" class="box">
<input class="submit" type="submit" value="SUBMIT">
<!-- <img src="/static/guest/images/querybutton.png" alt="Query Button" /> -->
</td>
</tr>
</form>
<button id="trfcode" value="z">z</button>
Javascript given below,
function readText() {
var value1 = document.getElementById("trcode").value;
var value2 = document.getElementById("trfcode").value;
console.log(`value1 = ${value1}`);
console.log(`value2 = ${value2}`);
if (value1 === value2) {
// location.href = "http://127.0.0.1:8000/myposts";
console.log(`I am good`);
alert(`You typed: ${value1}`);
} else {
console.log(`I am in else`);
alert("You typed: " + "Wrong Password");
}
}

PageMethods Not Working with VS2013 web application

I have spent all day struggling with this Error and have read almost every article and tried every hint I found but still not able to make it work.
Please Note: EnablePageMethod=true inside ScriptManager, Method is public and static and decorated with [WebMethods]
Same coding is working all perfect with VS2010 and with empty project in VS2013 but when using with New Project -> web -> web forms the output is attached here for your reference.
Here is my code.
Code Behind:
[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
JavaScript:
<script type="text/javascript">
function ShowCurrentTime() {
PageMethods.GetCurrentTime(document.getElementById("<%=txtUserName.ClientID%>").value, OnSuccess);
}
function OnSuccess(response, userContext, methodName) {
alert(response);
}
</script>
HTML:
<div>
Your Name :
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time" onclick="ShowCurrentTime()" />
</div>
Try adding both [System.Web.Services.WebMethod] and [System.Web.Script.Services.ScriptMethod] to the server side GetCurrentTime method.
Also make sure your script manager has EnablePageMethods="True". Your question states you set EnablePageMethod=true which is incorrectly spelled (should be plural).
You need to fail the click event handler to prevent the postback/page submit.
Just return false from your javascript function:
function ShowCurrentTime() {
PageMethods.GetCurrentTime(document.getElementById("<%=txtUserName.ClientID%>").value, OnSuccess);
return false; // added
}
You have to make sure that the button does not post back when calling a PageMethod from client-side. With your current markup, it will post back and cause unexpected effects.
You should be using the following markup for button, so it never posts back. Then the call to pagemethod should work. In markup below the button click event is returning a false value, so the page never gets submitted i.e. posted back.
Also, it would be best if you post your page markup in full, since there may be an issue with the markup.
<input id="btnGetTime" type="button" value="Show Current Time"
onclick="ShowCurrentTime();return false;" />

When clicked on a link, function value should be stores in a textbox

PHP, Javascript, HTML
I have a PHP function stored in page2.php
function pot()
{
does something;
returns a value;
}
in another page (page1.php), i have a link and a textbox
when i click, call the function pot
Calling pot() is simple, but I am not able to store the value returned by pot() into a textbox. This is my textbox
<input type="text" id="field" name="field" value="value the function returns">
Any suggestions??
Try to set the returned value to the textbox using javascript/jquery like
function pot()
{
// your code
document.getElementById("field").value="returnedvalue"; // set the result value to element with id as field
}
This will set the value of the textbox when you click on the link
when i click, call the function pot
Note: Make sure to include the function in the file, where you are calling the function. Otherwise it won't work. If needed you can create a js file with the function (if you want to use the same function in many places) and call the js file in your php file with
<script src="jsfilename.js">
by JavaScript
function pot()
{
document.getElementById("field").value="returnedvalue";
}
by jQuery
function pot()
{
$("#field").val(returnedvalue);
}
Besides using ajax (the preffered method) you can also use a hidden iframe on your page.
Your html would be:
<iframe src="about:blank" id="myhiddeniframe"></iframe>
<input type="text" id="field" name="field" value="">
<div onclick="pot();">when i click, call the function pot</div>
Javascript:
function pot(){
document.getElementsById('myhiddeniframe').src="page2.php";
}
And your php-function:
function pot(){
//get the $value
<script>
var ret='<?php echo rawurlencode($value) ?>';
window.top.window.document.getElementsById('field').value=decodeURIComponent(ret);
<script>
}
[edit]
added the rawurlencode() and decodeURIComponen() to make sure your value doesn't screw up the javascript :-)
I think you're having problem with the js? I'm assuming that you require page2.php on page 1.. in function pot you can add this..
function pot()
{
document.getElementById('field').value = 'what ever value you want';
}
That is a native javascript, but there is a javascript library called jQuery that will helps you a lot regarding on that. It seems that you are new in Javascript, you can visit this http://jquery.com/ to help you
Have external .js file and add it in page1.php
script.js
function pot()
{
does something;
returns a value;
}
In page1.php
<script src="script.js" language="javascript" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function()
{
var t=pot();
$("#field").text(t);
});

How to validate form fields in a facebox?

I need to validate my form fields displayed in facebox.
The problem is that i am unable to get the values of the fields by using javascript.
for ex: document.form.field_name.value doesnt return its value.
Code sample :
<script type="text/javascript">
function validate()
{
if (document.form1.field.value=='')
{
alert ("Field cannot be left blank");
}
}
</script>
<form name="form1" onsubmit="return validate()">
<input type="text" name="field" />
</form>
A way to do this would be to pass the value directly from the form to the validation code.
<form name="form" id="form" onsubmit="return validate(this.field.value)">
<input type="text" id="field" />
</form>
Or you could even use a text box without the form using:
<input type="text" id="field"
onkeydown="if (event.keyCode == 13) return validate(this.value)" />
Update the script to allow for the new value parameter:
<script type="text/javascript">
function validate(val) {
if (val.length < 1)
{
alert ("field cannot be left blank");
return false; //to stop the default action of submitting the form
} else {
alert ("Value: "+val);
return true; //allow to submit the page
}
}
</script>
This is actually a pretty easy and simple validation, but don't forget to set the return action based on whether you want the system to proceed with the submit or not.
I'm not sure where your pulling your page from whether from a remote html address or a locally stored div. So I'm not sure why your solution of pulling the value from the DOM does not work. I generally have no problems using jquery to get and set the values from the different fields in facebox windows.
NOTE: you have to be careful where you place your scripts. It depends on your application but sometimes you may want to place the script in the root document instead of the facebox page because if you load a remote facebox div you have a scope change and may need to refer to parent.document to access parent fields when the script is embedded in the remote facebox div.
Facebox copies the chunk of DOM displayed, effectively creating elements with duplicate ids. This is not allowed by HTML standard. Your javascript goes bonkers looking for a single element uniquely identified by its id, yet it finds 2 of them...
This is a huge bug in Facebox. Any code in a facebox should not have ids. All your bindings should be renewed when the facebox is revealed.

JavaScript form validation - to check for an empty textbox - using Python and CGI

I am developing a web application using Python and CGI. For form validation, I intend to use JavaScript. Here is the scenario -
There is a textbox where in user enters the name of the project and clicks the submit button.
I want to catch if nothing is entered in the textbox and throw an alert.
For the JavaScript function, I have used parameters, project_form (for the form) and project_name for the textbox. But what I am not clear about is where to put this function. As of now, I am trying to put it in the form tag itself. But it is not working. I somehow think that I have to pass the project_form and project_name parameters to the function and due to th e code structure, it is not possible for me to put the function in the 'head' section. I am pasting my code here. Thanks for the help.
<form action="create_project.py" method="POST" name="project_form">
<input type="text" name="project_name" size="40" onclick="javascript:document.project_form.submit.disabled=false"
id="acpro_inp0">
<br>
<script type="text/javascript">
function ValidateTextbox(project_form, project_name) {
var tb_value = project_form.project_name.value;
if (tb_value == null || tb_value.trim() == "") {
alert("Please enter something");
project_form.project_name.focus();
return false;
}
return true;
}
</script>
return ValidateTextbox('project_form','project_name')
<p>
</p>
<input type="submit" name="submit" value="Submit" onsubmit="return ValidateTextbox('project_form','project_name')"
disabled="">
</form>
Here is the related Python code -
import yate
import jshelper
print yate.start_response()
print yate.include_header("Create a new project.")
#Section to create a new project
print yate.start_form("create_project.py","project_form")
print yate.text_box("project_name",form_name="project_form")
jshelper.JSTextBoxValidate("project_form","project_name")
print yate.end_form("Submit",is_disabled = 'True', onsubmit_callback = "return ValidateTextbox('project_form','project_name')")
print yate.include_footer(({"Home": "../index.html"}))
Here is another piece of Python code, where I try to create the JS function on the fly.
def JSTextBoxValidate(form_name,tb_name):
print '<script type="text/javascript">'
print 'function ValidateTextbox' + '(' + form_name + ',' + tb_name + ')'
print '{'
print 'var tb_value = ' + form_name + '.' + tb_name + '.' + 'value;'
print 'if (tb_value==null || tb_value.trim()=="")'
print '{'
print 'alert("Please enter something");'
print form_name + '.' + tb_name + '.' + 'focus();'
print 'return false;'
print '}'
print 'return true;'
print '}'
print '</script>'
Somehow I have a feeling that I am probably not on the right track in this process and there has to be a better way. So I will be thankful for helping me to get this thing to work.
Note - The package yate is from Head First Python and I am using and extending the template from that code. I have put similar note in my project's documentation. This is my personal project.
Rewriting your HTML code the way it should work:
<script type="text/javascript">
function ValidateTextbox(input) { //we take an object representation of the HTML <input> tag (not just a string)
if (input.value.trim() == "") { //the attribute value is already defined in the tag now, so it couldn't be null
alert("Please enter something");
input.focus(); //move the cursor to the incriminated input
return false; //preventing from submitting the form (assuming the function is called as a return value)
}
return true; //allowing the form to be submitted (assuming the function is called as a return value)
}
//function added a you seemed to need something like that
function DisableFormSubmit(theForm, e) { //we take the form object as argument, and e may be the event object given from the keypress event
var submitButton=theForm.submit; //to ease typing this code, the submit button is assigned to a local variable
if(theForm.project_name.value.trim()=='') { //if we have no value for the project_name input of the form
submitButton.disabled=true; //we disable the submit button
submitButton.value="Submit - enter a name first"; //and we give a hint why it is disabled in the text printed on the button
} else { //in this case project_name has a valid value
submitButton.disabled=false; //the submit button is enabled
submitButton.value="Submit"; //we remove the hint we gave
}
//processing the event now, to know what to return (key 13 is Enter, returning false on it will prevent the form from being submitted by pressing Enter)
if(window.event) //MSIE compatibility
return window.event.keyCode!=13;
else if(e) //web browser's behavior
return e.which!=13;
}
}
</script>
<form action="create_project.py" method="POST" name="project_form" onsubmit="return ValidateTextBox(this.project_name);">
<input type="text" name="project_name" value="" size="40" onkeypress="return DisableFormSubmit(this.form, event);" id="acpro_inp0">
<br>
<input type="submit" name="submit" value="">
</form>
<script type='text/javascript'>
DisableFormSubmit(document.forms['project_form']); //we call this function once after the <form> has loaded so that we init the submit button with a standard way
</script>
For the Python code, I can't tell as I don't know this language, but you don't need to create as JS function "on the fly" to do a client-side check of the form's validity. Mind the client-side thing, meaning not secure, meaning if you absolutely need a value in that field, do a second check server-side (with Python apparently). Your problem is that:
you try to make a Javascript instruction out of <script></script> tags
you give strings as arguments while you actually need object representations of HTML tags: instead of giving 'project_form' and 'project_name' - notice the quotes - you needed something like document.project_form or document.forms['project_form'] and one of the previous with .project_name appended. Notice the lack of quotes here.
you used the attribute onsubmit in an <input> while its place should be in the <form> (this point may not be a cause of error though)
Hope this helps ;)

Categories

Resources