How do you get a value from a text field? - html

I suppose this should be straightforward, but I'm stuck to get that "cpsc" value. I tried to google this, and almost all of the search results told me to use ".value". But this particular class "control term" doesn't seem to work, and only returned "undefined".
<div class="control term">
<input type="text" value="cpsc">
</div>
My code:
document.getElementsByClassName("control term")[0].value;

You are reading from the div. You should read from input instead.
<div class="control term">
<input id="inputTag" type="text" value="cpsc">
</div>
document.getElementsBYId("inputTag").value;

The problem is that the class "control term" is on the div element and not your input. Also as a note, a class should be only one word (ie. controlTerm), having a space between them assigns two different classes to the div: control, and, term.
You have two options:
Add a class to your input
Get the child of document.getElementsByClassName("control term") and then extract its value.
Hope this helps
<div class="control">
<input class="term" type="text" value="cpsc">
</div>
document.getElementsByClassName("term")[0].value;

<div>
<input type="text" value="cpsc" class="control term">
</div>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
alert(document.getElementsByClassName("control term")[0].value);
}
</script>
You have to put class attribute in input tag

You need to add class to your input and then you can get the value of input using the following code.
<div class="control term">
<input type="text" class = "test" value="cpsc">
</div>
<button onclick = "myFunction()">Click me</button>
<script>
function myFunction(){
alert(document.getElementsByClassName("test")[0].value);
}
</script>
If you have multiple input box with same class name inside "control term" div, you can access their values using following code.
<div class="control term">
<input type="text" class = "test" value="cpsc">
<input type="text" class = "test" value="cpsc1">
</div>
<button onclick = "myFunction()">Click me</button>
<script>
function myFunction(){
alert(document.getElementsByClassName("test")[0].value);
alert(document.getElementsByClassName("test")[1].value);
}
</script>
Or if you want to get all values of input box inside "control term" div, you can do something like this.
<div class="control term">
<input type="text" class = "test" value="cpsc">
<input type="text" class = "test" value="cpsc1">
</div>
<button onclick = "myFunction()">Click me</button>
<script>
function myFunction(){
var x = document.getElementsByClassName("control term");
for(var i = 0;i<=x.length;i++){
alert(x[0].getElementsByClassName("test")[i].value);
}
</script>
Hope this will help you.

Related

Is it possible to use a variable in form action? Html

Code is the variable with the URL in it.
That's how it is supposed to work: User enters code (ex: 123342) in Textbox and the Text inside the text box is saved inside variable Code. Then, its goes to the website page 123342.
<form for="Code" action='https://website.com/ + Code'>
//makes a label
<label for="Answer" >URL:</label>
<input type="Answer" id="Code" Answer="Answer"><br><br>
<input type="submit" value="Join" class="Join">
</form>
You can set it at onload:
window.onload = function(){
var id = 789
document.getElementById("form").action = "https://test.com/"+id
};
<form for="Code" id="form">
<label for="Answer" >URL:</label>
<input type="Answer" id="Code" Answer="Answer">
<input type="submit" value="Join" class="Join">
</form>

Form not taking data from dynamically added fields

I am attempting to create an expandable form to create on/off instructions that a user can submit times for in pairings, so my HTML defaults with one pair and the user can use a button to add additional pairs, but when i submit the form angular is only reading the first pairing, can someone point out what I am missing here? Am I appending in the extra fields improperly?
HTML
<div class="timing">
<form class="timingSelect" action="index.html" method="post">
<div class="inputField">
<div class="form-group">
On: <input type="number" ng-model="recipe.on1" value="" step=".1">
</div>
<div class="form-group">
oz: <input type="number" ng-model="recipe.oz1" value="" readonly="readonly">
</div>
<div class="form-group">
Off: <input type="number" ng-model="recipe.off1" value="" step='.1'>
</div>
</div>
<!-- <input type="submit" ng-click="createRecipe(recipe)" value="Generate Recipe"> -->
</form>
<button type="submit" ng-click="createRecipe(recipe)">Submit</button>
</div>
<button type="button" class="next" name="button" ng-click="addColumn()">+</button>
JS:
app.controller('CreateRecipeController', ['$scope', '$location', '$routeParams', 'DashFactory', function($scope, $location, $routeParams, DashFactory){
console.log("entered Create Recipe controller");
var columnCount = 1;
$scope.addColumn = function addColumn(){
columnCount++;
console.log('attempting to create column');
var d = document.createElement("div");
d.className = "inputField";
var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('action',"submit.php");
var d2 = document.createElement("div");
d2.className = "form-group"
var i = document.createElement("input"); //input element, text
i.setAttribute('type',"number");
i.setAttribute('ng-model',"recipe.on"+columnCount);
i.setAttribute('value',"");
var d3 = document.createElement("div");
d3.className = "form-group"
var s = document.createElement("input"); //input element, Submit button
s.setAttribute('type',"number");
s.setAttribute('ng-model',"recipe.oz"+columnCount);
s.setAttribute('value',"");
s.setAttribute('readonly','readonly')
var d4 = document.createElement("div");
d4.className = "form-group"
var t = document.createElement("input"); //input element, Submit button
t.setAttribute('type',"number");
t.setAttribute('ng-model',"recipe.off"+columnCount);
t.setAttribute('value',"");
d.appendChild(f);
f.appendChild(d2);
f.appendChild(d3);
f.appendChild(d4);
d2.appendChild(i);
d3.appendChild(s);
d4.appendChild(t)
document.getElementsByClassName('timingSelect')[0].appendChild(d);
}
$scope.createRecipe = function(recipe){
console.log('recieved recipe data', recipe);
DashFactory.createRecipe(recipe)
}
}
]);
Great - Just move all your buttons inside your form tag like the code below
<div class="timing">
<form class="timingSelect" action="index.html" method="post">
<div class="inputField">
<div class="form-group">
On: <input type="number" ng-model="recipe.on1" value="" step=".1">
</div>
<div class="form-group">
oz: <input type="number" ng-model="recipe.oz1" value="" readonly="readonly">
</div>
<div class="form-group">
Off: <input type="number" ng-model="recipe.off1" value="" step='.1'>
</div>
</div>
<button type="submit" ng-click="createRecipe(recipe)">Submit</button>
<button type="button" class="next" name="button" ng-click="addColumn()">+</button>
</form>
</div>
And don't add another form when you append a new input field just add all your new inputs inside the existing form and try to submit it again - This might work
Thanks - Happy Coding !!

input field or help text doesn't turn red when field is invalid

I used to implement an Angular 2/4 application with Bootstrap 3 and used the Reactive Forms approach. I had a field-validation where the border of the input-field turned red and an error message appeared under the field in red font color.
it looks like this:
<div class="form-group row"
[ngClass]="{'has-error': (sourcesForm.get('sourceName').touched ||
sourcesForm.get('sourceName').dirty) &&
!sourcesForm.get('sourceName').valid }">
<label class="col-md-2 col-form-label"
for="sourceNameId">Source Name</label>
<div class="col-md-8">
<input class="form-control"
id="sourceNameId"
type="text"
placeholder="Source Name (required)"
formControlName="sourceName" />
<span class="help-block" *ngIf="(sourcesForm.get('sourceName').touched ||
sourcesForm.get('sourceName').dirty) &&
sourcesForm.get('sourceName').errors">
<span *ngIf="sourcesForm.get('sourceName').errors.required">
Please enter the Source Name.
</span>
<span *ngIf="sourcesForm.get('sourceName').errors.minlength">
The Source Name must be longer than 3 characters.
</span>
<span *ngIf="sourcesForm.get('sourceName').errors.maxlength">
The Source Name is too long.
</span>
</span>
</div>
</div>
Now i have to use Bootstrap 4 and neither the error message or the input-field turns red. How do i realise this? I tried to change the class of the parent span-block to "form-text" but it didn't work.
For beta version of Bootstrap v4, you can check out Form validation docs. There you can read about the new way, supported by all modern browsers for HTML5 way of form-validation with valid/invalid css classes. There Bootstrap uses the .was-validated and .invalid-feedback classes for what you want to achieve (see code snippet).
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet"/>
<form class="container" id="needs-validation" novalidate>
<label for="validationCustom02">Last name</label>
<input type="text" class="form-control" id="validationCustom02" placeholder="Last name" value="Otto" required>
<label for="validationCustom03">City</label>
<input type="text" class="form-control" id="validationCustom03" placeholder="City" required>
<div class="invalid-feedback">
Please provide a valid city.
</div>
<button class="btn btn-primary" type="submit">Submit form</button>
</form>
<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
"use strict";
window.addEventListener("load", function() {
var form = document.getElementById("needs-validation");
form.addEventListener("submit", function(event) {
if (form.checkValidity() == false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add("was-validated");
}, false);
}, false);
}());
</script>
If you want something more similar to Bootstrap 3, you can use what they call server-side validation, as it is written:
As a fallback, .is-invalid and .is-valid classes may be used instead of the pseudo-classes for server side validation. They do not require a .was-validated parent class.
Previous answer for alpha version of Bootstrap V4 (if you must use this).
On Bootstrap V4 Form Validation Docs there is the following example:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="form-group has-danger">
<label class="form-control-label" for="inputDanger1">Input with danger</label>
<input type="text" class="form-control form-control-danger" id="inputDanger1">
<div class="form-control-feedback">Sorry, that username's taken. Try another?</div>
<small class="form-text text-muted">Example help text that remains unchanged.</small>
</div>
So i think you just need to change the has-error class to has-danger
This is the solution:
<div class="form-group row">
<label class="col-md-2 col-form-label"
for="sourceNameId">Source Name</label>
<div class="col-md-8">
<input class="form-control"
[ngClass]="{'is-invalid': (sourcesForm.get('sourceName').touched ||
sourcesForm.get('sourceName').dirty) &&
!sourcesForm.get('sourceName').valid }"
id="sourceNameId"
type="text"
placeholder="Source Name (required)"
formControlName="sourceName" >
<span class="invalid-feedback" *ngIf="(sourcesForm.get('sourceName').touched ||
sourcesForm.get('sourceName').dirty) &&
sourcesForm.get('sourceName').errors">
<span *ngIf="sourcesForm.get('sourceName').errors.required">
Please enter the Source Name.
</span>
<span *ngIf="sourcesForm.get('sourceName').errors.minlength">
The Source Name must be longer than 3 characters.
</span>
<span *ngIf="sourcesForm.get('sourceName').errors.maxlength">
The Source Name is too long.
</span>
</span>
</div>
</div>
i needed to put the [ngClass]into the input-tag. Then i had to define the class as is-invalid and set the parent span-class to invalid-feedback
i know that your question is for long time ago, but it is the best way to validate the form-control input field by reactive form technique and bootstrap 4 to display the validation. first you need to write some code for your form :
in html section:
<form [formGroup]="myForm">
<div class="form-group">
<label for="name">first Name: </label>
<input type="text" class="form-control" formControlName="firstName" id="name">
<div *ngIf="firstName.touched && firstName.invalid" class="alert alert-danger">
<div *ngIf="firstName.errors.required">filling name is required!</div>
</div>
</div>
in ts file, you should implement the logic to conduct the validation.
in ts file:
myForm = new FormGroup({
'firstName':new FormControl('',Validators.required)
})
//getter method
get firstName(){
this.myForm.get('firstName');
}
now you can see that the validation is working. now to give style to input field to show the red border around the invalid input, just go to css file of component and add this class to the css file:
.form-control.ng-touched.ng-invalid{border:2px solid red;}
and simply you can see the result.

how to access element in directive?

I have a html page in which there is a directive(child html) inside as below. I want to do input validation of input1 and input2 in directive(child html) for the button in parent html, but I don't know how I can access the input1 and input2 in child (directive). I would like to know what is the right way to access input1 and input2? Thanks in advance!!
Parent html:
<div>
<child></child>
<button name="myButton" ng-disabled="????.myForm.input1.$invalid"><button>
</div>
Directive: child
<form name="myForm">
<input name="input1" required/>
<input name="input2" required/>
</form>
Try this:
Parent controller:
vm.myForm = {};
Parent Html:
<child my-form="vm.myForm"></child>
<button name="myButton" ng-disabled="vm.myForm.input1.$invalid"><button>
Child directive:
scope: {
myForm: "="
}
Child HTML:
<form name="myForm">
<input name="input1" required/>
<input name="input2" required/>
</form>
You can $emit event to your parent controller and pass needed data.
Directive:
$scope.$emit('yourCustomEvent', 'Data to send');
And catch the event in you parent controller.
Parent controller:
$scope.$on('yourCustomEvent', function (event, data) {
console.log(data); // will print "Data to send"
});
And in your case I advice you to include the button in your directive, it will be much easier to work with it.

HTML 5 pattern not working for onclick event of button

In a page, for getting field values I didn't use form tag, instead used Anchor tag's click event to get the values and used AJAX call to pass it to server.
Later tried out the HTML 5 pattern validation, it didn't work out; after so much try added form tag and then modified "anchor" to "button", then it worked.
Old
<div id="div1">
<input type="text" id="message" pattern="[a-zA-Z]{3}" required title="Enter valid Station" />
<a id="add" onclick="addMessage();">Add</a>
</div>
New
<form id="addMessage">
<div id="div1">
<input type="text" id="message" pattern="[a-zA-Z]{3}" required title="Enter valid Station" />
<button id="add">Add</button>
</div>
</form>
Is using a form tag and form submission the only way to trigger Pattern validation or are there any workarounds?
There's a nice overview of constraint validation in HTML5 on HTML5Rocks.
You can manually validate fields by calling the checkValidity() method on the DOM element in JavaScript:
document.getElementById('add').addEventListener('click', function() {
if (document.getElementById('message').checkValidity()) {
window.alert('valid station name');
// addMessage();
} else {
window.alert('invalid station name!');
}
});
<div id="div1">
<label>
Station
<input type="text" id="message" pattern="[a-zA-Z]{3}" required title="Enter valid Station" maxlength="3">
</label>
<a id="add" role="button">Add</a>
</div>
And also for reference: HTMLInputElement