I'm new to .NET and web development in general. I created a form to collect a user's comment and/or a file attachment. Everything works fine but I would like to add client side validation but it fails when I do so. Using Chrome's dev tools I can see the javascript is executed but the first statement fails saying "cannot read property value of undefined". If I remove the runat="server" properties, it works fine but I can no longer access the data from the code behind.
So what options do I have for making the javascript work? Or am I going about saving the data the wrong way?
aspx page:
<form id="commentForm" name="commentForm" runat="server" enctype="multipart/form-data" method="post" onsubmit="return validateCommentForm()">
<p>Add Comment</p>
<textarea id="Comment" name="Comment" rows="4" class="with-100" runat="server" />
<input id="FileAttachment" type="file" runat="server" />
<input type="submit" id="SaveComment" class="red-button" value="Submit" />
</form>
javascript:
function validateCommentForm()
{
var x = document.commentForm.Comment.value;
var y = document.commentForm.FileAttachment.value;
if (x == '' && y == '')
{
alert("Either a commment or file must be supplied.");
return false;
}
}
c#:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == true)
{
if (Comment.Value.Length > 0)
{
Insert.UserComment(Comment.Value);
}
HttpPostedFile UserFileAttachment = Request.Files[0];
if (UserFileAttachment.ContentLength > 0)
{
Insert.FileAttachment(UserFileAttachment);
}
}
}
Thanks in advance.
You can use jQuery, where you can call the form elements by the name as described in their API.
Retrieve the value:
$("input[name='Comment']").val();
To update the value (if needed) from JavaScript:
$("input[name='Comment']").val('some Comment');
You can also do it by ID (and based on your sample this should work) with the following jQuery:
$("#Comment").val();
So your final JavaScript would look like:
function validateCommentForm()
{
var x = $("#Comment").val();
var y = $("#FileAttachment").val();
if (x == '' && y == '')
{
alert("Either a commment or file must be supplied.");
return false;
}
}
I do think there's something odd in accessing the file name from a file input box. See the file selector jQuery documentation.
Related
I have a simple Window Forms application that opens up a webpage with set parameters.
The link send the user to a page with 2 text box fields and a submit button.
I am trying to automate this process so it grabs the parameter values and puts it into the text box then clicks submit .
This is my current code for my windows form:
using System;
using System.Windows.Forms;
using System.Diagnostics;
namespace WindowsFormsApplication1 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
libLink.Links.Remove(libLink.Links[0]);
libLink.Links.Add(0, libLink.Text.Length,
"http://www.example.com/?UserName=value1&FirstName=value2");
}
private void libLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
ProcessStartInfo sInfo = new ProcessStartInfo(e.Link.LinkData.ToString());
Process.Start(sInfo);
}
}
}
How can I create a script that that takes those parameters in the URL to populate two text box fields and then submit the form?
This is my HTML Page:
<form action="/send" method="post" novalidate="novalidate">
<input class="form-control" data-val="true" data-val-UserName="Wrong username" data-val-required="Enter a valid Username" id="Username" name="Username" placeholder="Username" type="text" value="">
<input class="form-control" id="FirstName" name="FirstName" placeholder="First Name" type="text" value="">
<button type="submit">Sign In</button>
</form>
Fairly new to coding so I tried to keep my code as simple as possible.
I looked at possible methods such as QueryStrings, JavaScript and Jquery, but I am not sure how to approach this problem.
There's a few ways of doing it really but i'll give you a basic walk through of how i would do it in javascript with a bit of JQuery.
we have variable with the URL we start by:
var url = "http://www.example.com/?UserName=value1&FirstName=value2"
var params_string = url.split("?")[1] //UserName=value1&FirstName=value2
so first we split the string into a list like above which returns a list of the items which are separated by the "?" character, but we only need the second item(at index 1) so we add the [1] to the end to only store that bit.
We then split this again to get the individual parameters.
var params_string_list = params_string.split("&")
["UserName=value1","FirstName=value2"]
which returns a list as above, again need to break that down i would make it into an object like so :
var params = {}
for(var i =0;i < params_string_list.length;i++ ){
var temp = params_string_list[i].split("=") // looks like ["UserName","value1"]
params[temp[0]]= temp[1]
} //params now looks like {"UserName":"value1","FirstName":"value2"}
as this makes it easy to access and use.
we can then do the following to set the values in the form:
if(params.UserName){
$('#Username').val( param.UserName );
}
if(params.FirstName){
$('#FirstName').val( param.FirstName );
}
if statments are there to check that the value exists in the object so we don't sent the value to "undefined" by accident.
Hope this helps.
Ok so I am running into a really weird bug on my Wordpress site that hope is just my ignorance because this just seems too weird.
So I am working with styling a couple of input tags as well as a ReCaptcha form. I found some documentation at https://developers.google.com/recaptcha/old/docs/customization that I have been following. Basically what I want is the clean theme listed at that link and to do some showing/hiding of the captcha based on certain events.
I do realize that the top of the article mentions this version of the api is old, but the plugin I am using has some recaptcha code entangled in their code, so I figured I would try this first instead of making major modifications to the plugin.
So here is the code I am using
<!-- Code added by me-->
<script type="text/javascript">
var RecaptchaOptions = {
theme : 'clean'
};
function toggleCaptcha(inputField)
{
alert('working');
}
</script>
<!-- End code added by me -->
<script>
function validateGoodNewsUser(frm, requireName) {
requireName = requireName || false;
if(requireName && frm.goodnews_name.value=="") {
alert("Please provide name");
frm.goodnews_name.focus();
return false;
}
if(frm.email.value=="" || frm.email.value.indexOf("#")<1 || frm.email.value.indexOf(".")<1) {
alert("Please provide a valid email address");
frm.email.focus();
return false;
}
// check custom fields
var req_cnt = frm.elements["required_fields[]"].length; // there's always at least 1
if(req_cnt > 1) {
for(i = 0; i<req_cnt; i++) {
var fieldName = frm.elements["required_fields[]"][i].value;
if(fieldName !='') {
var isFilled = false;
// ignore radios
if(frm.elements[fieldName].type == 'radio') continue;
// checkbox
if(frm.elements[fieldName].type == 'checkbox' && !frm.elements[fieldName].checked) {
alert("This field is required");
frm.elements[fieldName].focus();
return false;
}
// all other fields
if(frm.elements[fieldName].value=="") {
alert("This field is required");
frm.elements[fieldName].focus();
return false;
}
}
}
}
return true;
}
</script>
<form method="post" class="goodnews-front-form" onsubmit="return validateGoodNewsUser(this,false);">
<div><label>Your Name:</label> <input type="text" name="goodnews_name"></div>
<div><label>*Your Email:</label> <input type="text" name="email" onfocus="toggleCaptcha(this)"></div>
<p><script type="text/javascript" src="<!--Captcha api url here-->"></script>
<noscript>
<iframe src="<!--Captcha api url here-->" height="300" width="500" frameborder="0"></iframe><br/>
<textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
<input type="hidden" name="recaptcha_response_field" value="manual_challenge"/>
</noscript></p>
<div><br>
<input type="submit" value="Subscribe">
</div>
<input type="hidden" name="goodnews_subscribe" value="1">
<input type="hidden" name="list_id" value="1">
<input type="hidden" name="required_fields[]" value="">
</form>
So the problem I am running into is when I load the page, I see the clean theme for ReCaptcha and the alert shows up when I click inside the input box for the email. But if I change my added code by adding a single space like this
<!-- Code added by me-->
<script type="text/javascript">
var RecaptchaOptions = {
theme : 'clean'
};
<<<<<<<< Single new line space added.
function toggleCaptcha(inputField)
{
alert('working');
}
</script>
The whole thing breaks and the page loads with the standard red ReCaptcha and my functions don't get called.
I don't mind not using spaces, but that seems very odd that a space would make the difference. Am I missing something here? Is this caused by the outdated api?
Edit:
I was asked to try to get a jsfiddle working (or not working???). I stripped out everything except the form and the function call. Even the ReCaptcha was taken out and I still can not get it to call the function. This may be my lack of knowledge on jsfiddle or it may get closer to the real problem. https://jsfiddle.net/b257779t/
I was using this code fine on bothe IE9 and Firefox but now it works only on Firefox and it just doesn't execute Java validation part on IE9. Any idea what I may need to do to make it work on both type of browserss? Thanks
<?php
if(isset($_POST['submit'])) {
$first_name=$_POST['fname'];
echo 'Entered First Name = '.$first_name;
}
?>
<html>
<form method="post" enctype="multipart/form-data" action="">
<label for="fname"> First Name: </label> <input type="text" name="fname" /> <br /><br />
<label for="file"> Select File: </label> <input type="file" id="file" />
<input type="submit" name="submit" value="Submit" />
</form>
<script>
document.forms[0].addEventListener('submit', function( evt ) {
var file = document.getElementById('file').files[0];
if(file && file.size < 18000) {
//Submit form
alert('Size is valid');
} else {
alert('pic too big');
evt.preventDefault();
}
}, false);
</script>
</html>
The fact that the files array does not exist is not due to a code error. Internet Explorer 9 and below do not support the HTML5 File API, so you will have to use a workaround such as uploading with a Java applet or Adobe Flash.
Combined with what Alex W said, your code also needs some tweaking. getElementsByName requires a name attribute from where you are trying to select. It returns a NodeList of elements with the name given in the function. .
Change your input to have a name attribute, then you won't even need that function:
<input type="file" name="file" />
id works just fine. See below.
I stand corrected by my own research. All the above is true about getElementsByName, however to retrieve the File object, you have to call it from an array returned by selecting a file input form type. As such, document.getElementById('file').files[0] should work. So will the method below:
window.onload = (function () {
document.forms[0].addEventListener('submit', function (evt) {
//this works
var file = document.forms[0].file.files[0];
//as does this
file = document.getElementById('file').files[0];
if (file && file.size < 18000) {
//Submit form
alert('Size is valid');
} else {
alert('pic too big');
evt.preventDefault();
}
}, false);
});
jsFiddle
Even after all is said and done, it still will not work in browsers that do not support the HTML5 File API (looking at you IE).
Edit
Whoa, whoa, whoa hold the reigns? I just read that the id attribute was slated to replace the name attribute once IE6 gets nuked. Apparently this is old news1 2 3.
So I did some testing and it turns out id works just fine when calling the element the same way:
var file = document.forms[0].file;
Prove it? Ok
Looks like you have a script error.
The files property does not seems to be supported in IE9
document.forms[0].addEventListener('submit', function( evt ) {
var f = document.getElementById('file');
var file = f.files ? f.files[0] : f;
if(file && file.size < 18000) {
//Submit form
alert('Size is valid');
} else {
alert('pic too big');
evt.preventDefault();
}
}, false);
Demo: Fiddle
I've got a multiline asp.textbox input control.
I don't know if my issue is with ASP.NET, the Multiline control, or something else, but the onblur and onfocus are not working.
<script type="text/javascript">
var defaultMsg = 'Write your message here or or call my voice at (xxx) xxx-xxxx.';
var controlMsg = doc.createElement("input");
controlMsg.id = "txtMessage";
controlMsg.type = "text";
controlMsg.value = defaultMsg;
controlMsg.onfocus=function jpFocus() { if (this.value == defaultMsg) this.value = ''; }
controlMsg.onblur=function jpBlur() { if (this.value == '') this.value = defaultMsg; }
</script>
And later....
<asp:TextBox ID="txtMessage" Columns="30" Rows="6" runat="Server" TextMode="MultiLine" />
Does anyone see a reason why this should not be working?
Actually, you're creating a html element and you are attaching an event to it.
In addition, ASP.NET controls does not use the server side id.
Here's what you should do :
var controlMsg = document.getElementById('<%= txtMessage.ClientID %>');
controlMsg.onfocus = // Some Code ...
controlMsg.onblur = // Some Code ...
Try using an anonymous function, like this:
controlMsg.onfocus=function() { if ( ...
Functions and function scope - MDN.
Also, you did call something like document.body.appendChild(controlMsg);, didn't you?
EDIT:
You are using doc.createElement. Make sure that doc definitely points to document.
Also, look at the page in Firefox and see if there are any errors or warnings in the Error Console.
Not sure which version your are using.Please Try this:
protected void Page_Load(object sender, EventArgs e)
{
txtMessage. Attributes["onfocus"]="JavascriptMethod";
}
I'm not sure why this worked and other techniques did not, but this got my HTML to work:
<textarea name="txtMsg" rows="6" cols="30"
onfocus="if(this.value==this.defaultValue)this.value='';"
onblur="if(this.value==='')this.value=this.defaultValue;">[Write your message here or call my voice number at (555) 222-1234.]</textarea>
The text can be very long, and the control does not seem to care. Also, the text is only written in a single location.
I have a list of people that are being added via a search. Everything works, but there's one case where if you don't select a person from this list, you get an ugly 400 page. Obviously it's because I'm not handling the validation there.
My "remove from list" button is done this way:
<input type="button" value="Remove" onclick="delTeamNominee(document.f.teamList.value)"/>
Here's my function:
function delTeamNominee(id) {
document.dl.empId.value = id;
document.dl.submit();
}
dl is a hidden form that executes a Spring MVC method:
<form name="dl" action="teamDeleteEmployee" method="post">
<input type="hidden" name="empId">
</form>
Obviously I would like to do something like this:
function delTeamNominee(id) {
if (id == null) {
alert("You must select a person");
} else {
document.dl.empId.value = id;
document.dl.submit();
}
}
Which of course, doesn't work.
Perhaps you should also check to see if id is undefined. Something like the following will catch both null and undefined:
if (!id) {
....
}