there is a piece of my html code:
<!-- STEP 1: class .active is switching steps -->
<div data-step="1" class="">
<h3>Załóż fundację:</h3>
<div class="form-group form-group--inline">
<label> Nazwa <input type="text" name="name" id="name" /> </label>
<label> Opis <input type="text" name="description" id="description" /> </label>
</div>
<div class="form-group form-group--buttons">
<button type="button" class="btn next-step">Dalej</button>
</div>
</div>
<!-- STEP 2 -->
<div data-step="2">
<h3>Podaj typ fundacji</h3>
<div class="form-group form-group">
{{form1}}
</div>
<div class="form-group form-group--buttons">
<button type="button" class="btn prev-step">Wstecz</button>
<button type="button" class="btn next-step">Dalej</button>
</div>
</div>
In the step1, i am able to get the values from inputs by id, like:
var name = document.getElementById('name').value;
How can i do such a thing with the {{form1}}, it is kind of select field:
class AddFundationTypeForm(forms.Form):
type = forms.ChoiceField(choices=type_of_organization)
type_of_organization is a a dict, with 3 key-value pairs.
you can do this with any form field by adding prefix id_
so for your type field:
var type = document.getElementById('id_type').value;
django by default makes id for each field by using 'id_'+ your_field_name
and you want to obtain whole form then you should do this in your template.html
Template
<form id="myForm" action="" method="post">
{{form1}}
</form>
and then in javascript:
var form = document.getElementById('myForm')
Thanks, however, i've added new field to my form:
class AddFundationForm(forms.Form):
type = forms.ChoiceField(choices=type_of_organization)
categories = forms.MultipleChoiceField(choices=category_choices, widget=forms.CheckboxSelectMultiple)
JS:
var type = document.getElementById('id_type').value; (that works)
var category = document.getElementById('id_categories').value; (it doesn't)
Could you tell me what's the difference between defining two variables above?
Related
I am creating a sign-in page. I am currently busy with validation part in JS.
What I wan to know, if this is the correct way in doing it.
I did a logic that says if username is not entered error message should appear below the username stating Please add your username.
This is how I did the HTML element and js logic
HTML
<div class="container">
<form action="" class="form">
<div class="heading">
<h1>Log In</h1>
<p>Welcome to your finacial smart decision making</p>
</div>
<div class="row mb-3 align-item-center">
<label for="formGroupEampleInput" class="form-label" id="username">Username</label>
<input type="text" class="form-control" id="formGroupExampleInput" placeholder="User Name" required>
<div class="username-error"></div>
</div>
<div class="row mb-3 align-item-center">
<label for="formGroupEampleInput" class="form-label" id="password">Password</label>
<input type="text" class="form-control" id="formGroupExampleInput" placeholder="Password" required>
<div class="password-error"></div>
</div>
<button type="button" class="btn btn-primary" onclick ="validate()">Login</button>
</form>
<div class="side-image-container">
</div>
JS
function validate(){
let username = document.querySelector("#username");
let password = document.querySelector("#username");
let usernameError = document.querySelector(".username-error");;
const createdEl = document.createElement("div");
createdEl = document.createTextNode("Please add your username");
if(!username){
createdEl.appendChild(usernameError);
}
}
First of all I would recommend you using id instead of class to get querySelector, because, with id you will get a single element. but with class you may get list of elements.
After, I think you are appending in wrong way the child, you should do next:
usernameError.appendChild(usernameError);
Or you can use innerHtml.
The best way to do that:
Normally, if you have a fixed text to show or hide, you don’t need to create it dynamically and append to a div.
You can create a class to hide it.
html:
<div class="username-error hide">
Please add your username
</div>
css:
.hide{
display:none;
}
So, when you want to show the error just remove this class from your error element (div), otherwise add it.
js:
if(!username){
element.classList.remove("hide");
}
let username = document.querySelector("#username");
let password = document.querySelector("#username");
let usernameError = document.querySelector(".username-error");;
let createdEl = document.createElement("div");
let createdE2 = document.createTextNode("Please add your username");
createdEl.appendChild(createdE2);
if(!username.value){
usernameError.appendChild(createdEl);
}
}
Use this instead
There are multiple issues with your code:
username and password id is set on <label> element, not <input>
validate() function is trying assign a textNode element to a constant
you are trying to append existing .username-error element to a newly created textElement instead of vise-versa
when error printed there is no way remove the error
since your error placeholder element contains just text, you don't need create textNode, you can simply change the text via textContent property.
Here is simplified version that fixes all the above:
function validate(){
let username = document.querySelector("#username");
let password = document.querySelector("#password");
let usernameError = document.querySelector(".username-error");;
let passwordError = document.querySelector(".password-error");;
usernameError.textContent = username.value == "" ? "Please add your username" : "";
passwordError.textContent = password.value == "" ? "Please add your password" : "";
}
<div class="container">
<form action="" class="form">
<div class="heading">
<h1>Log In</h1>
<p>Welcome to your finacial smart decision making</p>
</div>
<div class="row mb-3 align-item-center">
<label for="formGroupEampleInput" class="form-label">Username</label>
<input type="text" class="form-control" id="username" placeholder="User Name" required>
<div class="username-error"></div>
</div>
<div class="row mb-3 align-item-center">
<label for="formGroupEampleInput" class="form-label" >Password</label>
<input type="text" class="form-control" id="password" placeholder="Password" required>
<div class="password-error"></div>
</div>
<button type="button" class="btn btn-primary" onclick ="validate()">Login</button>
</form>
<div class="side-image-container">
</div>
I'm having a problem in getting the value of input tag with a type of date which is place inside a modal. I'm trying to get this value using javascript. Here's my code:
HTML:
<form method="POST" action="{% url 'single_collection' %}">
{% csrf_token %}
<div class="modal-body form-horizontal">
<div class="form-group">
<label for="inputSQAID" class="col-sm-3 control-label">SQA Name</label>
<div class="col-sm-8">
<input type="hidden" name="sqa_name" id="sqa_name" value="{{ collectionlist.sqa_name }}">
</div>
</div>
<div class="form-group">
<label for="fromdate2" class="col-sm-3 control-label">From:</label>
<div class="col-sm-8">
<input type="date" class="form-control" name="fromdate2" id="fromdate2" max="{% now 'Y-m-d' %}" required>
<div class="modal-footer">
<button type="button" class="btn btn-primary pull-left" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-success" name="s_dl" id="s_dl" onclick="single_c()">Download</button>
</div>
</form>
Here's my javascript code, I'm just trying to display the value of the date from the input [type=date]:
<script type="text/javascript">
function single_c(){
var dates2 = document.getElementById('fromdate2').value;
document.write(dates2)
}
</script>
I tried to place the input tag outside the modal then it is working but when I put it back inside the modal it is not working. Any work around in here.
Your input does not have "value" property.
So you need to add "value" property to input,
And you need to call function single_c()
this function after how you type some text in input
Maybe something like this?
var date = "please enter a date";
dates.addEventListener('input',(e) => {
date = e.target.value
})
function single_c(){
document.write(date)
}
I had this problem too.
The main issue here is that if you have an id to target the value, the id must have the same name as the name attribute. I.e if you have an id="CheckingDate", your name="CheckingDate" else it won't work.
I have set of input boxes to add names and designaions.and iwant to print those in a <p> tag when user click print button. how to proceed.
<div class="form-group">
<label for="inputRegNo" >Name & Designation<span style="color:#c0392b;padding-left:5px;">*</span></label>
<div class="form-group">
<input required type="text" name="fname[]" class="fname" onkeyUp="document.getElementById('refa5').innerHTML = this.value" placeholder="Name" />
<input required type="text" name="lname[]" placeholder="Designation" />
</div>
</div>
<div class="form-group">
<label for="inputRegNo" ></label>
<div class="form-group">
<input type="text" name="fname[]" placeholder="Name" class="fname" onkeyUp="document.getElementById('refa5').innerHTML = this.value" />
<input type="text" name="lname[]" placeholder="Designation" />
</div>
</div>
print
<div>
<label>Name & Designation</label>
<p id="refa5"> - </p>
</div>
its looks you are new in javascript.. it's simple give the name to all the input field like
<input type="text/checkbox" name="txtName">
and in javascript you can access this field value by
<script type="text/javascript">
var name = document.getElementsByName("txtName");
</script>
if you wish to print the element on button click simply specify their click event on javascript like
function onClick() {
alert("helo from click function");
}
and then on button ..
<input type="button" onclick="onClick()">
w3schools is a great resource for this. Here is some example code on how to do this :
<button onclick="myFunction()">Click me</button>
<input id="inputID"></input>
<p id="demo"></p>
<script>
function myFunction() {
var inputID = document.getElementById("inputID").value;
document.getElementById("demo").innerHTML = inputID;
}
</script>
What the code above does is it takes the value of an input, then it sets the innerHTML of a <p> element to it. You can obviously do this with other things like <h1> elements as well.
My problem is pretty simple but elusive in nature. When you will load the index.php, (as localhost using xampp) you will be presented with a simple form. Now there are multiple elements on this form, and it's still a work in progress, so the possibility of multiple bugs is plausible. However, there's this one bug that's really annoying.
THE PROBLEM:
On changing the Due Date element, the content of the following input
boxes changes due to the fact that they're bind with it. Now it won't
matter how many times you change the due date, because every time the
value in the fields will change accordingly, Thanks to angularjs.
The BUG creeps in when you change the value of an input field. Say
originally it was 27 and then you changed it to , idk say 10.* NOW
IF YOU CHANGE THE DUE DATE, THE ALTERED INPUT FIELD REMAINS THE SAME
* I.E. WITH VALUE 10, WHEREAS I WANT IT TO CHANGE NEVERTHELESS.
Moreover, if one of you guys is the apotheosis of angularjs coders,
and he got some tips for me, I would just like to say..... "I APPRECIATE
THAT".
index.php
<!-- addService.html -->
<?php
$version = time();
?>
<!DOCTYPE html>
<html>
<head>
<!-- CSS (load bootstrap and our custon css files) -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<!-- JS (load angular, ui-router and our custom js file) -->
<script src="http://code.angularjs.org/1.2.13/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
<script src="ctrl-add-service.js"></script>
<script src="services.js"></script>
</head>
<body>
<div ng-app="mainApp" ng-controller="ctrl-add-service">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
<h1 align="center">SERVICE FORM</h1>
<form role="form" ng-submit="createService()">
<div>
<label>Service Name</label>
<input type="text" class="form-control" placeholder="Enter service name here" ng-pattern="/^[a-zA-Z0-9_]*$/" required>
</div>
<div class="row">
<div class="col-md-6">
<label>Due Date</label>
<input type="date" class="form-control" ng-model='dueDate' ng-change="setFields()" required>
</div>
<div class="col-md-6">
<label>Task Date</label>
<input type="date" class="form-control" required>
</div>
</div>
<div style="margin-top: 20px;margin-bottom: 20px;" align="center">
<label>Period</label>
<label class="radio-inline"><input type="radio" ng-model="value" value='12' ng-change="setFields()">Annually</label>
<label class="radio-inline"><input type="radio" ng-model="value" value='6' ng-change="setFields()">Semi-Annually</label>
<label class="radio-inline"><input type="radio" ng-model="value" value='4' ng-change="setFields()">Quarterly</label>
<label class="radio-inline"><input type="radio" ng-model="value" value='1' ng-change="setFields()">Monthly</label>
</div>
<div align="center">
<div>
<div style="display:inline-block;"><label>Jan</label><input type="number" class="form-control" ng-value='date' ng-disabled='fields[0]' ng-required='!fields[0]'></div>
<div style="display:inline-block;"><label>Feb</label><input type="number" class="form-control" ng-value='date' ng-disabled='fields[1]' ng-required='!fields[1]'></div>
<div style="display:inline-block;"><label>Mar</label><input type="number" class="form-control" ng-value='date' ng-disabled='fields[2]' ng-required='!fields[2]'></div>
<div style="display:inline-block;"><label>Apr</label><input type="number" class="form-control" ng-value='date' ng-disabled='fields[3]' ng-required='!fields[3]'></div>
</div>
<div style="display:inline-block;"><label>May</label><input type="number" class="form-control" ng-value='date' ng-disabled='fields[4]' ng-required='!fields[4]'></div>
<div style="display:inline-block;"><label>Jun</label><input type="number" class="form-control" ng-value='date' ng-disabled='fields[5]' ng-required='!fields[5]'></div>
<div style="display:inline-block;"><label>Jul</label><input type="number" class="form-control" ng-value='date' ng-disabled='fields[6]' ng-required='!fields[6]'></div>
<div style="display:inline-block;"><label>Aug</label><input type="number" class="form-control" ng-value='date' ng-disabled='fields[7]' ng-required='!fields[7]'></div>
<div>
<div style="display:inline-block;"><label>Sep</label><input type="number" class="form-control" ng-value='date' ng-disabled='fields[8]' ng-required='!fields[8]'></div>
<div style="display:inline-block;"><label>Oct</label><input type="number" class="form-control" ng-value='date' ng-disabled='fields[9]' ng-required='!fields[9]'></div>
<div style="display:inline-block;"><label>Nov</label><input type="number" class="form-control" ng-value='date' ng-disabled='fields[10]' ng-required='!fields[10]'></div>
<div style="display:inline-block;"><label>Dec</label><input type="number" class="form-control" ng-value='date' ng-disabled='fields[11]' ng-required='!fields[11]'></div>
</div>
</div>
<div align="center" style="margin-top: 20px;">
<button type="submit" class="btn btn-primary">Create</button>
<button type="reset" class="btn btn-danger">Reset</button>
</div>
</form>
</div>
<div class="col-md-2"></div>
</div>
</div>
</body>
</html>
ctrl-add-service.js (controller)
// ctrl-add-service.js Controller for the add service option in the nav bar of the home screen.
var mainApp = angular.module("mainApp",[]);
mainApp.controller('ctrl-add-service',function($scope, DueDateService){
$scope.value ='1';
$scope.setFields = function() {
$scope.date = DueDateService.date($scope.dueDate);
$scope.fields = DueDateService.fields( DueDateService.month($scope.dueDate), $scope.value); // first parameter passes month in int, second parameter passes period value in int.
};
});
services.js (services for the app)
// services.js services.js of the account direcotry of the project. It is used by the mainApp.
//DueDateService
mainApp.service('DueDateService', function(){
this.month = function(date) {
var temp = new Date(date);
month = temp.getMonth();
console.log(month+1+" is the month");
return (month+1);
};
this.date = function(date) {
var temp = new Date(date);
date = temp.getDate();
console.log(date+" is the date");
return (date);
};
this.fields = function(month,period) {
var lap = parseInt(period); // possible values of lap can be [12,6,4,1]
var iteration = 12/lap; // possible values of iteration can be [1,2,3,12]
var selectedFields = [true,true,true,true,true,true,true,true,true,true,true,true];
for (var i=1; i<=iteration; i++) {
if(month>12) {
month = month - 12;
}
selectedFields[month-1]= false;
month = month + lap;
}
return selectedFields;
};
});
I think you need to change the ng-value to ng-model and create an Array of your dates, like this:
ng-model='dates[0]'
ng-model='dates[1]'
ng-model='dates[2]'
...
And your controller would be like this:
var date = DueDateService.date($scope.dueDate);
$scope.dates = Array(12).fill(date);
See at this plunker: https://plnkr.co/edit/p8O14Y80hCWyNmxnYxbF
In following lines why are you taking ng-value, As far as I think you will have to take ng-model="date" And this will work fine.
see the ng-value usages
https://docs.angularjs.org/api/ng/directive/ngValue
<div style="display:inline-block;"><label>Jan</label><input type="number" class="form-control" ng-value='date' ng-model="date" ng-disabled='fields[0]' ng-required='!fields[0]'></div>
This is my first real-world JavaScript project. Please be kind...
I'm creating a form with required fields. With JavaScript, I am collecting the required fields as objects in an Array, each object having the properties "object" (the HTML objects themselves, from which I can get object.id and object.value) "description" (to display to users) and "error" (the HTML objects beneath each input field where corresponding validation errors appear).
Then I have a function (to be used onBlur, for instant feedback) that checks to see if the value of the field is null, and if so, it displays the validation error beneath the corresponding field.
I'm trying to set the onblur attribute for each input field using a FOR loop that runs through the array of required fields. I have a setAttribute statement that works perfectly if I create an individual statement for each object in the Array, individually. But as soon as I change it to a FOR loop, the onblur event for ANY field pops up the validation error for the FIRST input field, only. This has got to be a freshman mistake, but I've searched high and low and rewritten this thing ten different ways and can't make it work with a loop...
I put my code in a Fiddle so you can see it -- but it doesn't actually work in the fiddle, only in my local dev environment (maybe that indicates another problem?). Here's the code:
//create array with constructor to identify all required fields
var allRequired = [];
function RequiredField(theID, theDescription) {
this.object = document.getElementById(theID);
this.description = theDescription;
this.error = document.getElementById("error-" + theID);
allRequired.push(this);
}
var fieldFname = new RequiredField("fname", "First Name");
var fieldLname = new RequiredField("lname", "Last Name");
var fieldEmail = new RequiredField("email", "Email");
var fieldPhone = new RequiredField("phone", "Phone");
var fieldRole = new RequiredField("role", "Desired Role");
var fieldPortfolio = new RequiredField("portfolio", "Portfolio/Website URL");
function requireField(theDescription, theValue, theError) {
if (theValue === "") {
theError.innerHTML = "<p>" + theDescription + " is required.</p>";
} else {
theError.innerHTML = "";
}
} //end function
for (i = 0; i < allRequired.length; i++) {
allRequired[i].object.setAttribute("onBlur", "requireField(allRequired[i].description, allRequired[i].object.value, allRequired[i].error);");
}
/* THIS WORKS IN MY LOCAL DEV ENVIRONMENT...
allRequired[0].object.setAttribute("onBlur", "requireField(allRequired[0].description, allRequired[0].object.value, allRequired[0].error);");
allRequired[1].object.setAttribute("onBlur", "requireField(allRequired[1].description, allRequired[1].object.value, allRequired[1].error);");
allRequired[2].object.setAttribute("onBlur", "requireField(allRequired[2].description, allRequired[2].object.value, allRequired[2].error);");
allRequired[3].object.setAttribute("onBlur", "requireField(allRequired[3].description, allRequired[3].object.value, allRequired[3].error);");
allRequired[4].object.setAttribute("onBlur", "requireField(allRequired[4].description, allRequired[4].object.value, allRequired[4].error);");
allRequired[5].object.setAttribute("onBlur", "requireField(allRequired[5].description, allRequired[5].object.value, allRequired[5].error);");
*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form-careers" id="form-careers" action="form-process.php" enctype="multipart/form-data" onsubmit="return validateForm()" method="post">
<div class="form_labels">
<p>
<label for="fname">First Name:</label>
</p>
</div>
<div class="form_inputs">
<p>
<input type="text" name="fname" id="fname" required />
</p>
<div class="error" id="error-fname"></div>
</div>
<div class="form_labels">
<p>
<label for="lname">Last Name:</label>
</p>
</div>
<div class="form_inputs">
<p>
<input type="text" name="lname" id="lname" required />
</p>
<div class="error" id="error-lname"></div>
</div>
<div class="form_labels">
<p>
<label for="email">Email:</label>
</p>
</div>
<div class="form_inputs">
<p>
<input type="email" name="email" id="email" required />
</p>
<div class="error" id="error-email"></div>
</div>
<div class="form_labels">
<p>
<label for="phone">Phone:</label>
</p>
</div>
<div class="form_inputs">
<p>
<input type="tel" name="phone" id="phone" placeholder="###-###-####" pattern="\d{3}[\-]\d{3}[\-]\d{4}" required />
</p>
<div class="error" id="error-phone"></div>
</div>
<div class="form_labels">
<p>
<label for="role">Desired Role:</label>
</p>
</div>
<div class="form_inputs">
<p>
<input type="text" name="role" id="role" required />
</p>
<div class="error" id="error-role"></div>
</div>
<div class="form_labels">
<p>
<label for="portfolio">Portfolio/Website:</label>
</p>
</div>
<div class="form_inputs">
<p>
<input type="url" name="portfolio" id="portfolio" placeholder="http://" pattern="[a-z0-9.-]+\.[a-z]{2,63}$" required />
</p>
<div class="error" id="error-portfolio"></div>
</div>
<div class="clearboth"></div>
<input type="hidden" name="formtype" id="formtype" value="careers">
<div class="form_labels">
<p> </p>
</div>
<div class="form_inputs">
<a href="#">
<input type="submit" value="Submit" class="btn-red">
</a>
</div>
</form>
If someone would help point me in the right direction I would really appreciate it.
Code
for (i = 0; i < allRequired.length; i++) {
allRequired[i].object.setAttribute("onBlur", "requireField(allRequired[i].description, allRequired[i].object.value, allRequired[i].error);");
}
sets onblur event with value like requireField(allRequired[i].description.
So - what is it - i? No one knows.
Proper code is:
for (i = 0; i < allRequired.length; i++) {
allRequired[i].object.setAttribute("onBlur", "requireField(allRequired[" +i + "].description, allRequired[" + i + "].object.value, allRequired[" + i + "].error);");
}
See? I get real i value for each iteration.
As u_mulder said concat problem.
As for code I suggest to look up factory functions. It's more natural javascript then constructor.