I am doing simple validation of inputs in meteorjs, after first tour it works, and every next time it doesn't work (until I reload the page) – it means error messages are not displayed.
//main.js//
Template.addMealForm.events({
'click #submitNewMeal': function (ev) {
ev.preventDefault();
var query = {
name: $("#name").val().trim(),
price: $("#price").val(),
calories: $("#calories").val(),
category: $("#category").val()
};
areInputsValid(query);
}
});
var areInputsValid = function (query) {
if ((query.name.length === 0) || (query.price.length === 0) || (query.calories.length === 0)) {
$("#warningLabel").addClass("di")
$(".warningLabel").text("All fields are required");
}
else if ((isNaN(query.price) === true) || (isNaN(query.calories) === true)) {
$("#warningLabel").addClass("di")
$(".warningLabel").text("To Price and Calories fields please enter a number");
}
else {
console.log('it works');
$('.dn').hide();
}
};
//main.html//
<template name="addMealForm">
<form role="form">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control input_form" id="name" placeholder="Name of the meal">
</div>
<div class="form-group">
<label for="price">Price</label>
<input class="form-control input_form" id="price" placeholder="Price">
</div>
<div class="form-group">
<label for="calories">Calories</label>
<input class="form-control input_form" id="calories" placeholder="Calories">
</div>
<div id="warningLabel" class="form-group has-error dn">
<label class="control-label warningLabel"></label>
</div>
<button id="submitNewMeal" type="submit" class="btn btn-rimary">Add</button>
</form>
</template>
The problem is that you are calling $('.dn').hide() in the success case. Because #warningLabel has a class of dn it will not be displayed again on subsequent errors.
One solution is to add $('.dn').show() to the top of areInputsValid.
You already have Tracker as part of Meteor, so I put a little tutorial and JSfiddle together on how to use it to implement a typical form validation scenario.
http://bit.ly/meteor-form-validation-video
http://bit.ly/meteor-form-validation-fiddle
Related
I have 2 fields that I need to required based on another field in my model. The first field is functioning as desired, however the second field (similar logic) doesn't honor the required attribute. I have verified that the onlyif code is firing when the observable is changed. However the form allows submission if the required fields are not filled in.
JS Code
//Works As Expected
self.model.RecentLocations.LastDayOnSite.extend({
required: {
onlyIf: function () {
return ((!self.model.RecentLocations.IsLastDayOnSiteNA()) && (self.model.CaseType() != 'Quarantine'));
}
}
});
//Not Requiring Field as expected.
self.model.ContactTracingStartDate.extend = ko.observable().extend({
required: {
onlyIf: function () {
return (self.model.IsContactTracingRequired() == "Y");
}
}
});
HTML Code
//Works As Expected
<div class="col-md-2 form-group">
<i id="lastDayOnSite-asterisk" class="fas fa-asterisk fa-fw" style="font-size: 7px; color:red; vertical-align:super" data-bind="hidden: (model.RecentLocations.IsLastDayOnSiteNA() || model.CaseType() === 'Quarantine')"></i>
<label for="lastDayOnSite-datepicker_nfd">Last Day on Site</label>
<input type="text" class="form-control datepicker_nfd" id="lastDayOnSite-datepicker_nfd" data-bind="value: model.RecentLocations.LastDayOnSite, preventFutureDate: model.RecentLocations.LastDayOnSite, disable: model.RecentLocations.IsLastDayOnSiteNA()" data-emessage="Last Day on Site" placeholder="Date">
</div>
//Not Requiring Field as expected.
<div class="col-md-2 form-group">
<i id="contactTracingStartDate-asterisk" class="fas fa-asterisk fa-fw" style="font-size: 7px; color:red; vertical-align:super" data-bind="visible: (model.IsContactTracingRequired() === 'Y')"></i>
<label for="contactTracingStartDate-datepicker_nfd">Contact Tracing Start Date</label>
<input type="text" class="form-control datepicker_nfd" id="contactTracingStartDate-datepicker_nfd"
data-bind="value: model.ContactTracingStartDate,
preventFutureDate: model.ContactTracingStartDate, enable: (model.IsContactTracingRequired() === 'Y')" data-emessage="Contract Tracing Start Date" placeholder="Date">
</div>
Not Sure what I am missing here but I am fairly new to KnockoutJS but I can't see where the disconnect is. Any Help or suggestions would be appreciated.
The answer is change the line of code
self.model.ContactTracingStartDate.extend = ko.observable().extend({
TO:
self.model.ContactTracingStartDate.extend({
The problem was the observerable was reset by the ko.observable().extend instead of just extending the existing observable.
I am new in SilverStripe. I want to create a custom HTML form in SilverStripe.
<form class="form-inline" $HelloForm.FormAttributes>
<p id="{$HelloForm.FormName}_success" class="message" style="">$HelloForm.Message</p>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" id="email" placeholder="Enter email" name="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pwd">
</div>
<div class="checkbox">
</div>
$HelloForm.fields
<input type="hidden" value="{$AbsoluteLink}" name="redirectURL" class="action" id="{$HelloForm.FormName}_action_doSayHello"/>
And in my controller
public function HelloForm()
{
$form = Form::create(
$this,
'HelloForm'
);
$actions = new FieldList(
FormAction::create('doSayHello', 'Submit')->setAttribute('class', 'btn btn-success')
);
$form = new Form($this, 'HelloForm',$actions);
return $form;
}
public function doSayHello($data,$form)
{
$form->sessionMessage('thanks for contact us','good');
return $this->redirectBack();
//i am not getting success message after submit
}
Can I get a success message after submitting in this case?
When I use standard SilverStripe form it's working but when using custom HTML form like above I am stuck
You could submit the form via ajax, which would have many advantages.
The page does not have to refresh itself
You can animate the form after submitting, by sliding up or some kind of similar animation.
You can handle form states like success or error
Some example code (in jQuery):
let form = $('.form-inline');
$(form).ajaxSubmit({
success: function() {
$(form).slideUp();
$('#form-state').text("Successfully submitted form.");
}
})
i am using ajax to post data from asp (as front) to Django rest api (as backend)
First, I had a problem in Accessing to different domain but it solved using CORS
then i had another error which is related to CSRF
and the error like above :Forbidden (CSRF cookie not set.)
i've used #csrf_exempt to pass this validation but i want a solution for use it without csrf exmption
i tried more than one solution but it's not working or maybe i dont understand the way
Is there any clearly solution to solve it in ajax
In Error 403 ,
'''
JQuery sends " xhr.send( options.hasContent && options.data || null );
'''
i'll include code of my .cshtml file bellow
'''
form id="std_form" class="mx-auto form-horizontal" method="POST" asp-antiforgery="false">
#Html.AntiForgeryToken()
<div class="box-body">
<div class=" form-group">
<label for="inputEmail3" class="col-sm-3">ID</label>
<div class="col-md-8">
<input type="number" id="first">
</div>
</div>
<div class=" form-group">
<label for="inputEmail3" class="col-sm-3">ID</label>
<div class="col-md-8">
<input type="number" id="second">
</div>
</div>
<div class=" form-group">
<label for="inputEmail3" class="col-sm-3">ID</label>
<div class="col-md-8">
<input type="number" id="third">
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer d-flex">
<button type="submit" id="save_btn" class="btn-success btn">Save</button>
</div>
<!-- /.box-footer -->
</form>
</div>
'''
'''
window.CSRF_TOKEN = "{% csrf_token %}";
function getCookie(c_name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) c_end = document.cookie.length;
return unescape(document.cookie.substring(c_start, c_end));
}
}
return "";
}
'''
and this is ajax request
'''
$(document).on('submit', '#std_form', function (e) {
e.preventDefault();
let val1 = parseInt($('#first').val());
let val2 = parseInt($('#second').val());
let val3 = parseInt($('#third').val());
let x={val1,val2,val3};
$.ajax({
type: 'POST',
url: ('http://127.0.0.1:8000/Callfun/processdata/'),
data:{
First: val1,
Second:val2,
Third:val3,
csrfmiddlewaretoken: window.CSRF_TOKEN,
},
success: function (context) {
alert("Wooooooooowwwww");
$('#first').val(context.Max);
$('#second').val(context.Min);
$('#third').val(context.Avg);
},
error: function (context) {
alert("So Bad");
}
})
})
'''
i am trying to implement a contact us page using bootstrap template. I am a really beginner in asp.net and its my first time using a template.
I cant really get it where is the problem that is causing the above error.
I want to when the user click the send Message button to send emails to a current business email.
Can anyone help me?
contact.cshtml
<div class="row">
<div class="col-lg-8 mb-4">
<h3>Send us a Message</h3>
<form name="sentMessage" id="contactForm" novalidate>
<div class="control-group form-group">
<div class="controls">
<label>Full Name:</label>
<input type="text" class="form-control" id="name" required data-validation-required-message="Please enter your name.">
<p class="help-block"></p>
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Phone Number:</label>
<input type="tel" class="form-control" id="phone" required data-validation-required-message="Please enter your phone number.">
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Email Address:</label>
<input type="email" class="form-control" id="email" required data-validation-required-message="Please enter your email address.">
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Message:</label>
<textarea rows="10" cols="100" class="form-control" id="message" required data-validation-required-message="Please enter your message" maxlength="999" style="resize:none"></textarea>
</div>
</div>
<div id="success"></div>
<!-- For success/fail messages -->
<button type="submit" class="btn btn-primary" id="sendMessageButton">Send Message</button>
</form>
</div>
</div>
</div>
<script src="~/Content/vendor/jquery/jquery.min.js"></script>
<script src="~/Scripts/contact_me.js"></script>
<script src="~/Scripts/jqBootstrapValidation.js"></script>
<script src="~/Content/vendor/bootstrap/js/bootstrap.min.js"></script>
contact_me.js
$(function () {
$('#contactForm input,#contactForm textarea').jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var message = $("textarea#message").val();
var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
if (firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
$this = $("#sendMessageButton");
$this.prop("disabled", true); // Disable submit button until AJAX call is complete to prevent duplicate messages
$.ajax({
url: "mail/contact_me.php",
type: "POST",
data: {
name: name,
phone: phone,
email: email,
message: message
},
cache: false,
success: function() {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Your message has been sent. </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
error: function() {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append($("<strong>").text("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!"));
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
complete: function() {
setTimeout(function() {
$this.prop("disabled", false); // Re-enable submit button when AJAX call is complete
}, 1000);
}
});
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
$('#success').html('');
});
As my answer morphed through the comments:
the answer was that the OP added Jquery twice making a conflict in
file jqBootstrapValidation.js
Also, to help others based on the OP's post, this next part could be helpful as well:
Javascript files need to be loaded in the order of their dependence. Since your custom javascript file, contact_me.js depends on functions contained in the javascript file, jqBootstrapValidation.js, you need to load jqBootstrapValidation.js before contact_me.js, to fix this switch the order in which these files are loaded:
<script src="~/Content/vendor/bootstrap/js/bootstrap.min.js"></script>
<script src="~/Scripts/jqBootstrapValidation.js"></script>
<script src="~/Content/vendor/jquery/jquery.min.js"></script>
<script src="~/Scripts/contact_me.js"></script>
I'm stumped as to why part of my code isn't displaying when the session variable is set to true. When the user selects a certain option from the dropdown, based on the value, it changes the warmerselected to TRUE. I have tracked this in the console, and it works just fine.
Here is my code:
HTML:
<div class="item">
<div class="ui label">Product Type:</div>
<select id="ProductType" name="ProductType">
{{#each ProductTypes}}
<option value="{{ProductTypeAbbrev}}">{{ProductTypeName}}</option>
{{/each}}
</select>
</div>
{{#if warmerselected}}
<div class="item">
<div class="ui label">Name:</div>
<input type="text" name="ProductName" placeholder="Enter Product Name">
</div>
{{/if}}
JS:
Session.setDefault("warmerselected", false);
Template.addProduct.events({
'change #ProductType': function (e) {
var selitem = $("#ProductType").val();
if(selitem == "WA") {
Session.set("warmerselected",true)
}else {
Session.set("warmerselected",false);
}
}
});
Template.addProduct.helpers({
warmerselected: function(){
return Session.get("warmerselected");
}
});
Session isn't meant to be helper in HTML, you have to create one