In the given code i have create a dynamic textarea, now when i try to get insert value from that textarea. It gives me null value.
<form name="myForm">
<textarea name="fname" <%#!((GPNS.BusinessLayer.SpecialItems.SpecialItem)Container.DataItem).Code.Equals("OTH", StringComparison.InvariantCultureIgnoreCase) ? "style='display: none;'" : string.Empty%> id="text<%#((GPNS.BusinessLayer.SpecialItems.SpecialItem)Container.DataItem).ID%>" maxlength="50" placeholder="Enter other item details"></textarea>
</form>
Given is my function to get value from textarea box:
function ValidateData() {
if ($("textarea").is(":visible")) {
//var x = document.forms["myForm"]["fname"].value;
var x = document.getElementsByName("fname").value;
if (x == null || x == "") {
alert("Please Enter Other Item Details");
return false;
}
}
else return true
}
Your textarea was dynamic so you can used textarea change event. You can use given code on load, so whenever you input text it sets on OtherItemValue:
var OtherItemValue;
$("textarea").on('input change keyup', function () {
if (this.value.length) {
OtherItemValue = this.value;
} else {
OtherItemValue = "";
}
});
And then you can used below code:
function ValidateData() {
if ($("textarea").is(":visible")) {
if (OtherItemValue == null || OtherItemValue == "") {
alert("Please Enter Other Item Details");
return false;
}
}
else return true
}
Since you are using jQuery already, why don't you use it to achieve the desired result?
Your code would look like this:
function ValidateData() {
if ($("textarea").is(":visible")) {
var x = $("textarea").val();
if (x == null || x == "") {
alert("Please Enter Other Item Details");
return false;
}
}
return true
}
If you really need to use standard library, #Rachit Gupta's answer should solve the problem.
<form name="myForm">
<textarea name="fname" <%#!((GPNS.BusinessLayer.SpecialItems.SpecialItem)Container.DataItem).Code.Equals("OTH", StringComparison.InvariantCultureIgnoreCase) ? "style='display: none;'" : string.Empty%> id="text<%#((GPNS.BusinessLayer.SpecialItems.SpecialItem)Container.DataItem).ID%>" maxlength="50" placeholder="Enter other item details"></textarea>
</form>
Your function should now look like this
function ValidateData() {
if ($("textarea").is(":visible")) {
//var x = document.forms["myForm"]["fname"].value;
var x = document.getElementsByName("fname")[0].value;
if (x == null || x == "") {
alert("Please Enter Other Item Details");
return false;
}
}
else return true
}
The problem with your code is that getElementsByName will get a list of elements, which don't have a value property. You need to get only a particular element and get its value. This solution may solve your problem, but will work if you don't have any other element with name as fname above the textarea.
Use jquery .val() method to retrieve the value of the text area.
you need to initialise textarea to empty at document ready function.
$(document).ready(function(){
$("textarea[name='fname']").val("");
});
function ValidateData() {
if ($("textarea").is(":visible")) {
var x = $("textarea[name='fname']").val();
if (x == null || x == "") {
alert("In if " + x);
return false;
}
else {
alert("In else" + x);
}
}
else {
return true
}
}
Related
I have a form myForm and I want to check if specific input field are filled out before sending the form. I'm very new to JavaScript so I don't really know what I did wrong. Any help is welcomed.
function validateForm() {
var validate = true;
var alert_string = "";
var children = $("#myForm").children("input");
console.log(children.size());
for(var i = 0; i < children.length ; i++){
if(children[i].attr(id).substring(0,8) != "ABC_FLAT"){
if(children[i].attr(id) == null || children[i].attr(id) == ""){
validate = false;
alert_string = alert_string.concat(childrern[i].attr(id)).concat(", ");
}
}
}
alert_string = alert_string.concat("must be filled out !");
if(validate == false){
alert(alert_string);
return false;
}
return true;
}
children[i].attr(id) == "" // wrong
You don't have to check whether their ids are null, you have to check whether their values are empty :)
if(children[i].value == "")
Since you are already using jQuery, you can simplify that code to a great extent. For example a simple "all fields filled" check can be
var flag=0;
$('#myForm').each(function() {
if ( $(this).val() === '' )
flag=1;
});
if you'll use jQuery, you can check the input fields if empty AND trap also white space/s. Add a class to all input fields , e.g. class="required" and add attribute fieldname with respective value for each input field.
var requiredFields = "";
$("#myForm").find('.required').each(function () {
if ($(this).val().trim().length == 0) {
requiredFields += " - " + $(this).attr("fieldname") + "\n";
}
});
if (requiredFields != "") {
alert("Please enter the following required field(s): \n" + requiredFields);
} else {
//save here
}
You can use required like <input required type="text" name="email" id="log" /> or use jQuery like
$("form").submit(function() {
var has_empty = false;
$(this).find('input').each(function() {
if(! $(this).val()) {
has_empty = true;
return false;
}
});
if(has_empty){return false;}
});
I have a page that I need to disable the email field on. It needs to be readonly and dimmed. I've never worked with PHP before, and I assume that's what this code is, but, I'm not sure where I would disable the email field. Here's the code I have so far:
/**
* Validate our form fields
*/
var emailField, passwordField, confirmField, formfields = FormField.GetValues(%%GLOBAL_EditAccountAccountFormFieldID%%);
for (var i=0; i<formfields.length; i++) {
var rtn = FormField.Validate(formfields[i].field);
if (!rtn.status) {
alert(rtn.msg);
FormField.Focus(formfields[i].field);
return false;
}
if (formfields[i].privateId == 'EmailAddress') {
emailField = formfields[i];
} else if (formfields[i].privateId == 'Password') {
passwordField = formfields[i];
} else if (formfields[i].privateId == 'ConfirmPassword') {
confirmField = formfields[i];
}
}
if(emailField.value.indexOf("#") == -1 || emailField.value.indexOf(".") == -1) {
alert("%%LNG_AccountEnterValidEmail%%");
FormField.Focus(emailField.field);
return false;
}
if((passwordField.value != "" || confirmField.value != "") && (passwordField.value != confirmField.value)) {
alert("%%LNG_AccountPasswordsDontMatch%%");
FormField.Focus(confirmField.field);
return false;
}
return true;
}
%%GLOBAL_FormFieldRequiredJS%%
//]]>
To display a disabled texfield, you should output:
echo '<input type="email" name="name_of_field" value="email_to_display#gmail.com" disabled>';
Example:
See here (and have a look at the code):
Example
Perhaps if we had a link to the website we could have a look a it :)
I found several solutions to this using jquery and javascript, however, it has to declare all the fields in jquery, but its not efficient since I have 30+ asp textboxes on my form, how can i prompt the user to save the data or changes have been made on page unload.
I use this:
Be sure to set the default="" attribute on your fields!
function formIsDirty(form) {
var i, j, element, type;
if(typeof form === 'undefined') {
return false;
}
for (i = 0; i < form.elements.length; i += 1) {
element = form.elements[i];
type = element.type;
if (type === "checkbox" || type === "radio") {
if (element.checked !== element.defaultChecked) {
return true;
}
} else if (type === "hidden" || type === "password" || type === "text" || type === "textarea") {
if (element.value !== element.defaultValue) {
return true;
}
} else if (type === "select-one" || type === "select-multiple") {
for (j = 0; j < element.options.length; j += 1) {
if (element.options[j].selected !== element.options[j].defaultSelected) {
return true;
}
}
}
}
return false;
}
$( window ).unload(function() {
if(formIsDirty(document.forms["formName"])) {
return confirm("There are unsaved changes, leave this page?");
}
}
As an extra tip, when you generate the page in asp, if you set the default="" attribute to the current value in the database, you can detect not only if it's empty, but if the value has been changed.
This also allows proper use of the form.reset() button/method (w3Schools page here
Assuming that all text text boxes have the same style class ('inputField' is used below) you can use something like:
$( window ).unload(function() {
if ($('.inputField').is(':empty')){
alert('Please fill all text boxes');
}
});
In one of my textbox i need to enter only multiple url or multiple text at a time,not both.
So while i use the regular expression given below the domain name "google.com" will satisfy the condition of text.But i need to return false for this type of entry.Can anyone please suggest an idea?
jQuery.validator.addMethod("newway", function(value, element) {
var testarray = ['.....'];
var url_count = 0;
var text_count = 0;
for(var k in testarray){
if(/^(http:\/\/|https:\/\/)?((([\w-]+\.)+[\w-]+)|localhost)(\/[\w- .\/?%&=]*)?/i.test(testarray[k]))
{
console.log("url");
url_count++;
}
else{
if(/^[a-zA-Z+,:;%()]+$/.test(testarray[k])){
console.log("text");
text_count++;
}
}
}
if((url_count==0 && text_count > 0) || (url_count >0 && text_count == 0)){
if((url_count==testarray.length) || (text_count==testarray.length)){
return true
}
else{
return false
}
}else{
return false
}
}, "Please enter url or text");
I have the following form:
<form name="survey1" action="add5up.php" method="post" onsubmit="return validateForm()">
<div id="question">Q1) My programme meets my expectations</div><br />
Always<INPUT TYPE = 'Radio' Name ='q1' value= 'a'>
Usually<INPUT TYPE = 'Radio' Name ='q1' value= 'b'>
Rarely<INPUT TYPE = 'Radio' Name ='q1' value= 'c'>
Never<INPUT TYPE = 'Radio' Name ='q1' value= 'd'>
<input type="submit" value="addData" />
</form>
I am trying to validate whether a Radio button has been selected.
The code I am using:
<script type="text/javascript">
function validateForm()
{
if( document.forms["survey1"]["q1"].checked)
{
return true;
}
else
{
alert('Please answer all questions');
return false;
}
}
</script>
This is not working. Any ideas?
When using radiobuttons you have to go through to check if any of them is checked, because javascript threats them as an array:
<script type="text/javascript">
function validateRadio (radios)
{
for (i = 0; i < radios.length; ++ i)
{
if (radios [i].checked) return true;
}
return false;
}
function validateForm()
{
if(validateRadio (document.forms["survey1"]["q1"]))
{
return true;
}
else
{
alert('Please answer all questions');
return false;
}
}
</script>
Regards
My solution for validation complex forms include radios.
Usage is simple, function return TRUE/FALSE after validation.
var rs_target is ID of form
scTo is my custom func to scroll to ID, you can use own function to show/scroll errors
scTo("#"+err_target);
Error box will be like
<div class="rq_message_box rq_message_box_firstname display-none">err message</div>
Validation
var validation = validateForm(rs_target);
if(validation == false){
return false;
}
Function
function validateForm(rs_target) {
var radio_arr = [];
var my_form = $("#"+rs_target);
my_form = my_form[0];
$(".rq_message_box").hide(); //clear all errors
//console.log(my_form);
var err = false;
var err_target = "";
for (key in my_form) {
//console.log("do");
if(!my_form[key]||my_form[key]==null||err){
break;
}
//console.log(my_form[key].name);
var x = my_form[key].value;
//console.log(x);
if(my_form[key].type == "radio"){
//console.log("radio");
if(radio_arr[my_form[key].name] != true){
radio_arr[my_form[key].name] = null;
}
if(my_form[key].checked){
radio_arr[my_form[key].name] = true;
}
}else{
if (x == null || x == "") {
//console.log(form[key].name.toString() + " must be filled out");
err = true;
err_target = my_form[key].name;
//return false;
}
}
}
//console.log(radio_arr);
var rad_err = false;
for (key in radio_arr) {
if(rad_err){
break;
}
var x = radio_arr[key];
if (x == null || x == "") {
//console.log("RADIO> "+key + " must be filled out");
rad_err = true;
err_target = key;
}
}
if(err || rad_err){
// some error stuff, for me show prepared error/help box with class [".rq_message_box_"+err_target] / err_target is name of input like [.rq_message_box_firsname]
$(".rq_message_box_"+err_target).show(); //show error message for input
scTo("#"+err_target); //scroll to - custom func
return false;
}else{
return true;
}
}