Javascript click handlers - css

The task is :
I have done the form and the design bit for the web page but never came across this push: function() in javascript
I am confused on how to approach or do this task any help will be appreciated! Thank you :)
var _itq = {
push: function() {
console.log.apply(console, arguments);
}
};
_itq.push("_itq", "initialised", "ok");
<form id="commentForm" method="get" action="">
<div class="form-group">
<input class="form-control" type="email" placeholder="Enter Your Email" required>
</div>
<div class="form-group">
<div>
<input type="text" class="form-control" placeholder=" Enter Your Name" pattern=".{2,}" required title="2 characters minimum">
</div>
<div>
<input type="password" class="form-control" placeholder="Your Password" pattern=".{5,10}" required title="5 to 10 characters">
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-block btn-info">Sign Up</button>
</div>
</form>

Here is the second question, this should set you on the right path for question 1.
document.getElementById('commentForm').onsubmit = function() { // attach to form submit
var email = document.getElementById("email").value; // get the email value (add id="email" to the email input in the html)
var name = document.getElementById("name").value; // get the name (add id="name" to the name input in the html)
var initials = name.split(' ').map(function(v, i) { // get the initials by splitting
return v[0] // on space and taking the 1st char
}).join('');
_itq.push(email, initials); // pass into your push
return false; // return false to stop the submit (optional depending on requirements)
};
working snippet below
var _itq = {
push: function() {
console.log.apply(console, arguments);
}
};
_itq.push("_itq", "initialised", "ok");
document.getElementById('commentForm').onsubmit = function() {
var email = document.getElementById("email").value;
var name = document.getElementById("name").value;
var initials = name.split(' ').map(function(v, i) {
return v[0]
}).join('');
_itq.push(email, initials);
return false;
};
<form id="commentForm" method="get" action="">
<div class="form-group">
<input id="email" class="form-control" type="email" placeholder="Enter Your Email" required>
</div>
<div class="form-group">
<div>
<input id="name" type="text" class="form-control" placeholder=" Enter Your Name" pattern=".{2,}" required title="2 characters minimum">
</div>
<div>
<input type="password" class="form-control" placeholder="Your Password" pattern=".{5,10}" required title="5 to 10 characters">
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-block btn-info">Sign Up</button>
</div>
</form>

Try Something like this
Your HTML:
<button type="submit" class="btn btn-block btn-info" onclick="fillarr()">Sign Up</button>
JS:
function fillarr(){
_itq.push(document.getElementById("emailId").value, document.getElementById("nameId").value);
}
You still need to add an ID for your Email and Name field though

Related

ASP.NET Double validation, custom message for numbers only

I have a validation for Fueling property which is a double.
[Display(Name = "Tankolás")]
[DisplayFormat(DataFormatString = "{0} l", ApplyFormatInEditMode = false)]
public double? Fueling { get; set; }
If I type letters instead of number in the input I get the error message: The value 'test' is not valid for Tankolás.
How could I change the error message?
Here is the view:
<div class="form-group">
<label asp-for="Fueling" class="control-label"></label>
<input id="Fueling" asp-for="Fueling" class="form-control" placeholder="Tankolás" />
<span asp-validation-for="Fueling" class="text-danger"></span>
</div>
EDIT - Full View code
#model MainProject.Models.RoadRecord
#{
ViewData["Title"] = "Hozzáadás";
}
<head>
<link rel="stylesheet" href="~/css/RoadRecords/create.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<div class="container">
<div class="text-center">
<h2>Új Menetlevél hozzáadása</h2>
</div>
<div class="row justify-content-center">
<div class="col-8">
<form asp-action="Create">
<input type="hidden" asp-for="UserId" />
<input type="hidden" asp-for="LicencePlate" />
<div class="form-group">
<label asp-for="Mileage" class="control-label"></label>
<div class="input-group-sm">
<input asp-for="Mileage" class="form-control" placeholder="Kilométer" />
<div id="mileageContainer" class="input-group-append">
<partial name="_ShowMileagePartialView.cshtml" model="#Model" />
</div>
</div>
<span asp-validation-for="Mileage" class="text-danger"></span>
#if (!string.IsNullOrEmpty(ViewBag.Message))
{
<span class="text-danger">
#ViewBag.Message
</span>
}
</div>
#*
<div class="form-group">
<label asp-for="TimeStamp" class="control-label"></label>
<input type="datetime-local" asp-for="TimeStamp" class="form-control" value="#DateTime.Now.ToString("yyyy-MM-ddTHH:mm")" />
<span asp-validation-for="TimeStamp" class="text-danger"></span>
</div>
*#
<div class="form-group">
<label asp-for="Location" class="control-label"></label>
<div class="input-group">
<input id="varos" type="text" asp-for="Location" class="form-control" aria-describedby="getLocationButton" />
<div class="input-group-append">
<button type="button" class="btn btn-primary" id="getLocationButton">Pozícióm</button>
</div>
</div>
<span asp-validation-for="Location" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Type" class="control-label"></label>
<select id="selectType" asp-for="Type" class="form-control">
<option selected value="C">Céges</option>
<option value="M">Magán</option>
</select>
</div>
<div class="form-group">
<label asp-for="Fueling" class="control-label"></label>
<input id="Fueling" asp-for="Fueling" class="form-control" placeholder="Tankolás" />
<span asp-validation-for="Fueling" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Note" class="control-label"></label>
<input asp-for="Note" class="form-control" placeholder="Megjegyzés" />
<span asp-validation-for="Note" class="text-danger"></span>
</div>
<div class="form-group">
#Html.AntiForgeryToken()<input onclick="ConvertDouble()" type="submit" value="Hozzáadás" class="btn btn-primary w-100" />
</div>
</form>
<a class="add" asp-action="Index" asp-route-licencePlate="#ViewBag.LicencePlate">
<button type="button" class="btn btn-secondary w-100">
Vissza
</button>
</a>
</div>
</div>
</div>
#section Scripts {
<!--GEO Location-->
<script>
$(document).ready(function () {
$('#getLocationButton').click(function () {
$.getJSON('https://geolocation-db.com/json/')
.done(function (location) {
$('#country').html(location.country_name);
$('#state').html(location.state);
$('#city').html(location.city);
$('#latitude').html(location.latitude);
$('#longitude').html(location.longitude);
$('#ip').html(location.IPv4);
document.getElementById('varos').value = location.city;
});
});
});
$.getJSON('https://geolocation-db.com/json/')
.done(function (location) {
console.log("kint");
if (document.getElementById('varos').value == '') {
console.log("bent");
$('#country').html(location.country_name);
$('#state').html(location.state);
$('#city').html(location.city);
$('#latitude').html(location.latitude);
$('#longitude').html(location.longitude);
$('#ip').html(location.IPv4);
document.getElementById('varos').value = location.city;
}
});
</script>
<!--Get Milage-->
<script>
$(function () {
$.ajax({
type: "Get",
url: "../RoadRecords/ShowMileage?licencePlate=" + "#ViewBag.LicencePlate",
success: function (data) {
$("#mileageContainer").html(data);
},
error: function (response) {
console.log(response.responseText);
}
});
});
</script>
<script>
function ConvertDouble() {
var param = $("#Fueling").val();
if (param.indexOf(".") != -1) {
param = param.replace(".", ",");
}
$("#Fueling").val(param);
}
</script>
}
Here is my full view code. I had to remove validation js because the fueling input, if I type for example 12,5 or 12.5 I got error message, so I removed it, and because of the Culture thing it's work with commas (I am from Hungary), and in the javascript I replace the dot with comma if the user type dot instead of comma.
You can add RegularExpression and ErrorMessage in your property to add rules and custom ErrorMessage
[Display(Name = "Tankolás")]
[RegularExpression(#"^[0-9]*$",ErrorMessage = "You can use numbers only")]
public double? Fueling { get; set; }
View
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Using input tag helper "name" and getting input value empty. ASP.NET MVC (.NET 5)

I have simple form for creating items
<form asp-action="CreateItem" enctype="multipart/form-data">
<div class="form-group">
<label asp-for="#Model.ItemPhoto" class="control-label"></label>
<input type="file" asp-for="#Model.ItemPhoto" name="Photo" class="form-control-file" />
<span asp-validation-for="#Model.ItemPhoto" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.Name" class="control-label"></label>
<input asp-for="#Model.Name" class="form-control" />
<span asp-validation-for="#Model.Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.ItemType" class="control-label"></label>
<select asp-for="#Model.ItemType" class="form-control">
#foreach (var itemType in Enum.GetValues(typeof(RandApp.Enums.ItemType)))
{
<option value="#itemType.ToString()">#itemType</option>
}
</select>
<span asp-validation-for="#Model.ItemType" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.MaterialType" class="control-label"></label>
<select asp-for="#Model.MaterialType" class="form-control">
#foreach (var materialType in Enum.GetValues(typeof(RandApp.Enums.MaterialType)))
{
<option value="#materialType.ToString()">#materialType</option>
}
</select>
<span asp-validation-for="#Model.MaterialType" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.Color" class="control-label"></label>
<select asp-for="#Model.Color" class="form-control">
#foreach (var color in Enum.GetValues(typeof(RandApp.Enums.ItemColor)))
{
<option value="#color.ToString()">#color</option>
}
</select>
<span asp-validation-for="#Model.Color" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.Size" class="control-label"></label>
<select asp-for="#Model.Size" class="form-control">
#foreach (var size in Enum.GetValues(typeof(RandApp.Enums.ItemSize)))
{
<option value="#size.ToString()">#size</option>
}
</select>
<span asp-validation-for="#Model.Size" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.DesignedFor" class="control-label"></label>
<select asp-for="#Model.DesignedFor" class="form-control">
#foreach (var desigendFor in Enum.GetValues(typeof(RandApp.Enums.DesignedFor)))
{
<option value="#desigendFor.ToString()">#desigendFor</option>
}
</select>
<span asp-validation-for="#Model.DesignedFor" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.Price" class="control-label"></label>
<input asp-for="#Model.Price" class="form-control" />
<span asp-validation-for="#Model.Price" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.Description" class="control-label"></label>
<textarea asp-for="#Model.Description" class="form-control"></textarea>
<span asp-validation-for="#Model.Description" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
there is its controller
public async Task<IActionResult> CreateItem(Item item, IFormFile Photo)
{
if (ModelState.IsValid)
{
var path = Path.Combine(_webHostEnvironment.WebRootPath, "assets", Photo.FileName);
var stream = new FileStream(path, FileMode.Create);
await Photo.CopyToAsync(stream);
item.ItemPhoto = Photo.FileName;
await _itemRepo.CreateAsync(item);
ViewBag.Item = item;
return RedirectToAction("ReadItems");
}
return View();
}
my goal is to get the path of chosen photo and save it in folder called "assets"(located in "wwwroot" folder).
The problem is that when i fill the fields and submitting the values, i get item.ItemPhoto value null and i can't enter in if statement. (see the photo down below).
[1]: https://i.stack.imgur.com/H2aLt.png
one solution i have found is to remove "enctype="multipart/form-data" from form and "name="Photo" tag helper from input
<form asp-action="CreateItem" enctype="multipart/form-data">
<div class="form-group">
<label asp-for="#Model.ItemPhoto" class="control-label"></label>
<input type="file" asp-for="#Model.ItemPhoto" name="Photo" class="form-control-file" />
<span asp-validation-for="#Model.ItemPhoto" class="text-danger"></span>
</div>
but in this case i can't get the path properly.
what can i do to solve this problem, why am i getting empty value from input?
File and string type cannot be passed together with the same name automatically and cannot achieve this requirement by using just one input. You can set a hidden input for ItemPhoto and use js to set the value when the file changed:
#model Item
<form asp-action="CreateItem" enctype="multipart/form-data">
<div class="form-group">
<label asp-for="#Model.ItemPhoto" class="control-label"></label>
//change here...
<input type="file" name="ItemPhoto" class="form-control-file" onchange="SetValue(this)" />
//add hidden input......
<input asp-for="#Model.ItemPhoto" hidden/>
<span asp-validation-for="#Model.ItemPhoto" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.Name" class="control-label"></label>
<input asp-for="#Model.Name" class="form-control" />
<span asp-validation-for="#Model.Name" class="text-danger"></span>
</div>
<input type="submit" value="Create"/>
</form>
#section Scripts
{
<script>
function SetValue(input) {
var fileName = input.files[0].name;
//asp-for will generate the id and name
//so you can get the selector by using $("#ItemPhoto")
$("#ItemPhoto").val(fileName);
}
</script>
}
Backend (The name attribute should always match with the parameter/property name):
public async Task<IActionResult> CreateItem(Item item, IFormFile ItemPhoto)
{
//....
return View();
}

How to get id value from database using ajax? .net

I have a blog site and I made a comment panel under the article. example; user name, mail adress and comment...
I can add these fields using ajax but can't determine which article the comment is made on.
That's inputs..
<div class="form-group">
<%-- <label for="name" class="col-sm-2 control-label" style="color: #fff;">Name</label>--%>
<div class="col-sm-8">
<input type="text" class="form-control" id="t1" name="name" placeholder="Adınız" required tabindex="1">
</div>
</div>
<div class="form-group">
<%-- <label for="email" class="col-sm-2 control-label" style="color: #fff;">E-mail</label>--%>
<div class="col-sm-8">
<input type="email" class="form-control" id="t2" name="email" placeholder="E-mail Adresiniz" required>
</div>
</div>
<div class="form-group">
<%-- <label for="name" class="col-sm-2 control-label" style="color: #fff;">Message</label>--%>
<div class="col-sm-10">
<textarea id="t3" name="message" class="form-control" placeholder="Yorumunuz" rows="5" required></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-6">
<button type="submit" style="float: right;" class="btn btn-primary" onclick="ekle()">Gönder</button>
</div>
that's commentAjax.aspx code behind;
sqlBaglantisi baglan = new sqlBaglantisi();
string adsoyad, email, yorum, makaleID;
protected void Page_Load(object sender, EventArgs e)
{
makaleID = Request.QueryString["makaleID"];
adsoyad = Request.QueryString["adsyd"].ToString();
email = Request.QueryString["em"].ToString();
yorum = Request.QueryString["yrm"].ToString();
SqlCommand cmd = new SqlCommand("insert into Yorum (yorumAdSoyad, yorumEmail, yorumIcerik, yorumResim, makaleID) values('" + adsoyad.ToString() + "','" + email.ToString() + "','" + yorum.ToString() + "','/tema/yorumm.png')", baglan.baglan());
cmd.ExecuteNonQuery();
}
and js codes;
function ekle() {
var ad = document.getElementById("t1").value;
var mail = document.getElementById("t2").value;
var yorum = document.getElementById("t3").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "yorumAjax.aspx?adsyd=" + ad + "&em=" + mail + "&yrm="+yorum, false);
xmlhttp.send(null);
document.getElementById("t1").value = "";
document.getElementById("t2").value = "";
document.getElementById("t3").value = "";
alert("Mesaj Gönderildi");
I can't understand which comment has come to which article because I can't get the value of articleID.
You can put a hidden input in your form, containing the actual ID of your article. Something like:
<input type="hidden" id="articleID" name="articleID" value="<the id for this article>" />
If you are using an MVC architecture, you can define the ID for the article in your view and then pass it to the template when rendering.
<input type="hidden" id="articleID" name="articleID" value="{{ article.id }}" />
or
<input type="hidden" id="articleID" name="articleID" value="{{ id }}" />
This way, you can then obtain the value of the article id like you did with the other fields in the javascript function.

how to get data by finding all and finding one at the same time

In my project on the user edit page I would like to show the current role,wich i get by findOne byId,but I would also like to get all available roles so that I can choose, roles are in a separate collection, and I dont have a problem when displaying eather one...or all..
<div class="form-group col-lg-12">
<label>Email</label>
<input type="email" class="form-control" id="email" value="{{emails.[0].address}}">
</div>
<div class="form-group col-lg-12">
<label>Password</label>
<input type="password" name="" class="form-control" id="password" value="{{password}}">
</div>
<div class="form-group col-lg-6">
<label>Name</label>
<input type="text" name="" class="form-control" id="firstname" value="{{profile.name}}">
</div>
<div class="col-xs-12"><strong>Current role:</strong>
<label class="radio-inline">
<input type="radio" name="optradio" id="accountRole" value="{{roleName profile.role}}" checked>{{roleName profile.role}}
</label>
</div>
{{/with}}
<div class="col-xs-12">
<form>
<div class="col-xs-12"><strong>Roles:</strong>
{{#each rolesInformation}}
<label class="radio-inline">
<input type="radio" name="optradio" id="accountRole" value="{{_id}}">{{roleName}}
</label>
{{/each}}</div>`
helpers look like this:
Template.editUser2.helpers({
user: () => {
return Meteor.users.findOne({_id:Session.get('id')});
},
playerInformation: () => {
return Players.find().fetch();
},
roleName: (id)=>{
return Roles.findOne({_id:id}).roleName;
},
rolesInformation: () =>{
return Roles.find().fetch();
},
when i run roleName or rolesInformation separateli it works fine...
whet both included i get "roleName not defined"

Meteor - How to create a custom field validation for a form

I want to create a custom field validation for forms using Meteor. I don't want a packaged solution.
Here is my code so far.
JavaScript:
var errorState = new ReactiveVar;
Template.lottoForm.created = function() {
errorState.set('errors', {});
};
Template.lottoForm.events({
'blur input': function(e, t) {
e.preventDefault();
validate($(this));
}
});
Template.lottoForm.helpers({
errorClass: function (key) {
return errorState.get('errors')[key] ? 'has-error' : '';
}
});
Template.errorMsg.helpers({
errorMessages: function(key) {
return errorState.get('errors');
}
});
function throwError(message) {
errorState.set('errors', message)
return errorState.get('errors');
}
function validate(formField) {
$("input").each(function(index, element){
var fieldValue = $(element).val();
if(fieldValue){
if(isNaN(fieldValue) == true) {
throwError('Not a valid Number');
}
}
});
}
HTML:
<template name="lottoForm">
<form class="playslip form-inline" role="form">
<fieldset>
<div class="form-group {{errorClass 'ball0'}}">
<input type="text" class="input-block form-control" id="ball0" maxlength="2" name="ball0">
</div>
<div class="form-group {{errorClass 'ball1'}}">
<input type="text" class="input-block form-control" id="ball1" maxlength="2" name="ball1">
</div>
<div class="form-group {{errorClass 'ball2'}}">
<input type="text" class="input-block form-control" id="ball2" maxlength="2" name="ball2">
</div>
<div class="form-group {{errorClass 'ball3'}}">
<input type="text" class="input-block form-control" id="ball3" maxlength="2" name="ball3">
</div>
<div class="form-group {{errorClass 'ball4'}}">
<input type="text" class="input-block form-control" id="ball4" maxlength="2" name="ball4">
</div>
<div class="form-group {{errorClass 'ball5'}}">
<input type="text" class="input-block form-control" id="ball5" maxlength="2" name="ball5">
</div>
{{> errorMsg}}
<div class="play-btn">
<button type="submit" value="submit" class="btn btn-primary">Play Syndicate</button>
</div>
</fieldset>
</form>
</template
<template name="errorMsg">
<div class="errorMsg">
{{#if errorMessages}}
<div class="list-errors">
{{#each errorMessages}}
<div class="list-item">{{> fieldError}}</div>
{{/each}}
</div>
{{/if}}
</div>
</template>
<template name="fieldError">
<div class="alert alert-danger" role="alert">
{{errors}}
</div>
</template>
I'm also getting this error message in the console - "Uncaught Error: {{#each}} currently only accepts arrays, cursors or falsey values."
Why do I get this error and how would I implement the custom validation?
Just as the error says, #each template functions must be passed the proper type. Are you sure your errorMessages helper is returning an array? It looks like you are initializing it as a hash.

Resources