How to change value of element - javascript

Im kinda new to js, trying to change value of "email" input field
<div class="input-group type-email">
<div class="input-label has-placeholder-label">
<label for="">Your Email Address</label>
</div>
<div class="inputs">
<input name="email" value="" placeholder="" type="email">
</div>
</div>
I've found a bunch of articles saying how to find an element by id. How can I do it without id, by type maybe?
Thank you.

You can use query selectors, for example:
var input = document.querySelector("input[name=email]");
input.value = "Your new value";
More on query selectors here and also here.
Hope it helps!

Related

How to use input field value attribute while using formControlName? [Angular]

What I want to achieve: I want pre-populated data in my form and I also want to use formControlName as I want the data too.
My html file -
<div class="container">
<p class="h4 my-5">Add New Result</p>
<div class="row">
<div class="col">
<form (ngSubmit)="editStudent()" [formGroup]="studentEditForm" name="myForm">
<div class="mb-3">
<label for="roll-no" class="form-label">Roll No.</label>
<input type="number" class="form-control" id="roll-no" name="rollno" formControlName="rollno" value="{{student.rollNo}}" placeholder="{{student.rollNo}}" autocomplete="off" required>
</div>
<div class="mb-3">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" id="name" name="name" formControlName="name" value={{student.name}} required>
</div>
<div class="mb-3">
<label for="email" class="form-label">Email address</label>
<input type="email" class="form-control" id="email" name="email" formControlName="email" value={{student.email}} required>
</div>
<div class="mb-3">
<label for="score" class="form-label">Score</label>
<input type="number" class="form-control" id="score" name="score" formControlName="score" value={{student.score}} required>
</div>
<button type="submit" class="btn btn-primary" ng-click="submitForm(myForm.$valid)">Submit</button><button type="submit" class="btn btn-dark mx-4">Clear</button>
</form>
</div>
<div class="col"></div>
<div class="col"></div>
</div>
</div>
In Input Tag, I want to use value attribute so I can get a default value but I get Empty fields and I think it is because formControlName is controlling the data in my form. Is there a way to get pre-populated data using value attribute along with formControlName attribute?
Placeholder attribute works fine but I want a default value.
if you want a default value simply initialize the form with values, for example:
form = new FormGroup({
name: new FormControl('defaultNameValue'),
email: new FormControl('defaultEmailValue')
})
You should be doing it in you component instead of using value attribute. While defining the form example
studentEditForm= new FormGroup({
rollNo: new FormControl(this.student.rollNo)
})
or if student data is not available at the time of definition then use formcontrol.setValue after you initialize the student data something like
this.studentEditForm.controls.rollNo.setValue(this.student.rollNo)
Using the value and the CVA (Control Value Accessor: formControlName, formControl, and ngModel) to control the value of the input will override each other each time you change anyone of them.
Instead, it's better to rely only on one of them. If the CVA is used, then you can pass an initial value (default value) to the form-control while defining it:
studentEditForm = new FormGroup({
score: new FormControl(YOUR_INITIAL_VALUE),
});
For more info, check here how Angular passes the value from CVA to the value property when using both of them:
default_value_accessor.ts
Used value and CVA to control value
try this :
studentEditForm = new FormGroup({
score: new FormControl(VALUE),
});

I want to append error message on div element

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>

Form in HTML with button assigns the value of the last button, no matter which one was selected

I want to create a form with HTML with different types of inputs (such as name, surname, dates, and radio-button options), and when I want to print the object with the data inputted in the form on the console, the value from the radio-buttons is not stored correctly.
First of all, this is my first project on this area and also my first posted question on stackoverflow, so I would appreciate some suggestions on how to pose the question better if I'm forgetting some crucial data.
I have been following help from different resources (mostly youtube videos such as: https://www.youtube.com/watch?v=GrycH6F-ksY ) to create this form and submit the data with AJAX, and the code of my javascript application comes mainly from that video.
All the data is stored correctly and I can see it in the console, except from the data comming from the radio-buttons. No matter what option is selected (either "male" or "female"), the console always shows the value of the last button, which in this case is "female". I suppose I am doing something wrong when defining these buttons, and why they are not being "selected" (I suppose that's what is happening since the data shown is always the last default value) but I haven't been able to find out where I am doing something wrong.
I'm including the part of the code that I think might be relevant
<form action="ajax/contact.php" method="post" class="ajax">
<div class="form-row">
<div class="form-group col-md-6">
<label>Name</label>
<input type="text" class="form-control" name="inputName" required>
</div>
<div class="form-group col-md-6">
<label>Surname</label>
<input type="text" class="form-control" name="inputSurname" required>
</div>
</div>
<div class="form-group">
<label>Date of birth</label>
<input type="date" class="form-control" name="inputDate">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" name="inputEmail" required>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<label>Gender</label>
</div>
<div class="form-group col-md-4">
<div class="radio-inline"><input type="radio" name="inputGender"
value="male">Male</div>
</div>
<div class="form-group col-md-4">
<div class="radio-inline"><input type="radio" name="inputGender"
value="female">Female</div>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Number of children</label>
</div>
<div class="form-group col-md-6">
<input type="number" class="form-control" name="inputNumber">
</div>
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
Javascript function
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
console.log(data);
return false;
});
PHP file
<?php
if (isset($_POST['inputName'],$_POST['inputSurname'],$_POST['inputDate'],$_POST['inputEmail'],$_POST['inputGender'],$_POST['inputNumber'])) {
print_r($_POST);
}
In the console I'm getting this:
${inputName: "myName", inputSurname: "mySurname", inputDate: "2019-12-13",
$inputEmail: "myMail#gmail.com", inputGender: "female", …}
$inputDate: "2019-12-13"
$inputEmail: "myMail#gmail.com"
$inputGender: "female"
$inputName: "myName"
$inputNumber: "1"
$inputSurname: "mySurname"
$_proto_: Object
but I thought it would be showing:
$...
$inputGender: "male"
$...
when the male option is selected.
Thank you very much
The problem is in your JS. You're looping through everything with a name attribute, in order, and adding its value to your submit data. In the case of radio buttons, you have to check if they're selected and only add if so, otherwise, the last one always wins, as you're seeing.
And since you appear to be using jQuery, you can probably just let its serialize helper do this work for you.

Add a placeholder to several input fields (with the same class) using javascript

I have an HTML form with 4 inputs fields inside it. All these input fields have the same class and ID, the only differences are the "divs" surounding the inputs.
One form is in the header the other one in the content, and inside each of them, one field is a username field to login, and the other one to register.
<div class=theheader>
<h1> The Header</h1>
<div class="fullform">
<div class="container register">
<div class="form_group required">
<input class="input_text" id="username_field" name="username" size="30" value="" type="text">
</div>
</div>
<div class="container login">
<div class="form_group">
<input class="input_text" id="username_field" name="username" size="30" type="text" >
</div>
</div>
</div>
</div>
<div class=thecontent>
<h1> Form Content</h1>
<div class="fullform">
<div class="container register">
<div class="form_group required">
<input class="input_text" id="username_field" name="username" size="30" value="" type="text">
</div>
</div>
<div class="container login">
<div class="form_group">
<input class="input_text" id="username_field" name="username" size="30" type="text" >
</div>
</div>
</div>
</div>
Here is an example of what it looks like : http://jsfiddle.net/M6R7K/78/.
I need to add a placeholder inside each of these fields, but the tricky thing is, I don't have any direct access to this HTML code, because this one is automatically generated by a third party plugin. So I can only add javascript or css, using the existing classes and ids.
So I used the javascript :
document.getElementById("username_field").setAttribute("placeholder", "Username");
And it has indeed add the correct placeholder in the correct field. The problem is, it only add the placeholder in the 1st field found, not all of them. Even if I add several lines of javascript.
So the question : How to fill up all these field with a placeholder without touching the HTML code ? (With javascript or anything else) And at the best possible, having a different placeholder for each field ? (One needs to be "username and email", and the other one "username" only). We should be able to use the classes of the div's, just like we can do in CSS. But I wasn't able to figure it out.
Thanks !
Your code set placeholder one of them. Standard don't define which of them will get the placeholder because standard forces you tou use ID only once per page. You need to set placeholders for all elements with input_text class. You can do it by array with placeholders and iterating fields: In each iteration set i-th placeholder from array by this code
var placeholders = ["Username", "Email", "Phone", "Credit card"]
var elements = document.getElementsByClassName("input_text");
for (var i = 0; i < elements.length; i++) {
elements[i].setAttribute("placeholder", placeholders[i]);
}
Example: http://jsfiddle.net/M6R7K/81/
The best practice is set placeholders normally in HTML.
First of all you cannot use the same id for more then one element.
Second: try to use as input name attribute meaningful values. If you cannot touch the HTML you can always use the index parameter inside the forEach loop, this could be an idea. Another idea could be to look for the root element in order to distinguish the input fields.
I tried to do for you, right to give you an idea on how to solve your problem:
window.onload = function() {
Array.prototype.slice.call(document.getElementsByClassName("input_text")).forEach(function(currentValue, index) {
currentValue.setAttribute("placeholder", currentValue.getAttribute('name'));
});
}
<div class=theheader>
<h1> The Header</h1>
<div class="fullform">
<div class="container register">
<div class="form_group required">
<input class="input_text" id="username_field1" name="username" size="30" value="" type="text">
</div>
</div>
<div class="container login">
<div class="form_group">
<input class="input_text" id="username_field2" name="password" size="30" type="text" >
</div>
</div>
</div>
</div>
<div class=thecontent>
<h1> Form Content</h1>
<div class="fullform">
<div class="container register">
<div class="form_group required">
<input class="input_text" id="username_field3" name="email" size="30" value="" type="text">
</div>
</div>
<div class="container login">
<div class="form_group">
<input class="input_text" id="username_field4" name="other" size="30" type="text" >
</div>
</div>
</div>
</div>
I have been able to find the solution, using the "attr" function, and the Jquery framework.
This is the function that I applied to each of the inputs, in order to create a unique placeholder (example for the 1st field) :
$(".theheader .register input").attr('placeholder', 'Username Header')
This code allows to retrieve the DIV CLASS of each input field, and apply a customized field.
So for my example, it would be this :
$(".theheader .register input").attr('placeholder', 'Username Header')
$(".theheader .login input").attr('placeholder', 'Username or Email Header');
$(".thecontent .register input").attr('placeholder', 'Username Content');
$(".thecontent .login input").attr('placeholder', 'Username or Email Content');
And each field has his customized placeholder !
Here is the result : https://jsfiddle.net/3ddo465n/9/
Thank you all for the contribution !

How to create an HTML5 custom validation that check if the value inserted into 2 email inout field is the same?

I am pretty new in HTML 5 and I have the following doubt.
I have a form like this:
<form class="form-horizontal" action="/IDES/salvaRegistrazione" method="POST" name="formRegistrazione">
<div class="form-group">
<label class="control-label col-sm-2" for="inputNome">Nome</label>
<div class="col-sm-10">
<input id="inputNome" class="form-control" type="text" value="" required="required" placeholder="Nome" name="nome">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="inputEmail">E-mail</label>
<div class="col-sm-10">
<input id="inputEmail" class="form-control" type="email" value="" required="required" placeholder="E-mail" name="email">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="inputEmail2">E-mail</label>
<div class="col-sm-10">
<input id="inputEmail2" class="form-control" type="email" placeholder="Inserisci nuovamente E-mail" name="inputEmail2">
</div>
</div>
<input id="submitRegistrazione" class="btn btn-default pull-right" type="submit" value="Registrati" name="submitRegistrazione">
</form>
As you can see the input tag have setted the required="required" attribute and as you can see in this JSFiddle if you don't insert the value into the input tag it is automatically shown an HTML error message popup:
https://jsfiddle.net/fntwyn9j/
Now my problem is that into my form I have also 2 field having type="email".
My problem is that I want that if the second email value (the one inserted in the field having id="inputEmail2") is not equal to the first email value (the one inserted into the field having id="inputEmail") appear a custom message (in the same HTML5 style) that say to me that the 2 fields have not the same value and the form is not submitted.
Searching on the web I found this example that use event listener to add custom message: http://jsfiddle.net/B4hYG/9/
But is seems to me that don't work and I have no idea about how to implement the previous requirement.
How can I solve this issue and implement this kind of HTML5 custom validation?
Solved by myself:
$(document).ready(function() {
document.getElementById("inputEmail2").addEventListener("input", function (e) {
valoreInpitEmail = $('#inputEmail').val();
valoreInpitEmail2 = $('#inputEmail2').val();
//alert("value inputEmail: " + valoreInpitEmail + " value inputEmail2: " + valoreInpitEmail2);
//if (e.target.value != "") {
if(valoreInpitEmail != valoreInpitEmail2) {
alert("EMAIL DIVERSE");
//alert("BLABLABLA");
e.target.setCustomValidity("Le E-mail inserite non corrispondono, per favore inserirle nuovamente");
}
else {
// Let the browser decide whether this is a valid email address
// This actually prevents that the call of setCustomValidity()
// in the IF doesn't get removed thus the user cannot submit the form
//alert("ELSE");
e.target.setCustomValidity("");
}
});
});

Categories

Resources