Add <br> in HTML with the help of JavaScript - javascript

I am trying to add two "br" after each of my form fields that are not hidden because otherwise, it uses some space in my form and it doesn't look good.
But for some reason it doesn't appear.
<legend>Ética y Cumplimiento:</legend>
<fieldset style="border: 1px solid #000;">
<br>
<div id="formulario3">
{% for field in form3 %}
{% if field.flags.required %}
{{ field.label(text='*' + field.label.text) }}
{% else %}
{{ field.label }}
{% endif %}
{% if field.errors %}
{{ field(class="is-invalid") }}
<div class="invalid-feedback">
{% for error in field.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ field(class="form-control") }}
{% endif %}
<script>
let elementoseleccionado = document.getElementById({{ field.id }});
if ((document.getElementById('{{ field.id }}')).type === 'hidden') {
$('label[for="{{ field.id }}"]').css('display', 'none');
}
else{
let linebreak = document.createElement("br");
elementoseleccionado.appendChild(linebreak);
elementoseleccionado.appendChild(linebreak);
}
</script>
{% endfor %}
<input type="button" class="btn btn-primary" id="morecumplimiento" value="Más">
<br>
<br>
</div>
The error generated by my code is this one:
The HTML generated is this one:
<legend>Ética y Cumplimiento:</legend>
<fieldset style="border: 1px solid #000;">
<br>
<div id="formulario3">
<label for="exposicion_politica">* Indique si alguna persona mencionada en el presente formulario es/fue una Persona Expuesta Políticamente (PEP)</label>
<select class="form-control" id="exposicion_politica" name="exposicion_politica" required><option value="0">---</option><option value="SI">SI</option><option value="NO">NO</option></select>
<script>
if ((document.getElementById('exposicion_politica')).type === 'hidden') {
$('label[for="exposicion_politica"]').css('display', 'none');
}
else{
let linebreak = document.createElement("br");
if ((document.getElementById('exposicion_politica')) !== null && (document.getElementById('exposicion_politica')).value === ''){
document.getElementById(exposicion_politica).appendChild(linebreak);
document.getElementById(exposicion_politica).appendChild(linebreak);
}
}
</script>
<label for="ap_nom_etica1">*Apellidos y Nombres 1</label>
<input class="form-control" id="ap_nom_etica1" name="ap_nom_etica1" required type="text" value="">
<script>
if ((document.getElementById('ap_nom_etica1')).type === 'hidden') {
$('label[for="ap_nom_etica1"]').css('display', 'none');
}
else{
let linebreak = document.createElement("br");
if ((document.getElementById('ap_nom_etica1')) !== null && (document.getElementById('ap_nom_etica1')).value === ''){
document.getElementById(ap_nom_etica1).appendChild(linebreak);
document.getElementById(ap_nom_etica1).appendChild(linebreak);
}
}
</script>
As you can see the br is not generated and some error apears.

You can use each loop to iterate through your inputs and check if it is visible if yes then use .after to add <br> tag
Demo Code:
$("select , input").each(function() {
//check if visible
if ($(this).is(":visible")) {
//add br after that elements
$(this).after("<br/><br/>")
} else {
//hide label
$(this).prev().css('display', 'none');
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<legend>Ética y Cumplimiento:</legend>
<fieldset style="border: 1px solid #000;">
<br>
<div id="formulario3">
<label for="exposicion_politica">* Indique si alguna persona mencionada en el presente formulario es/fue una Persona Expuesta Políticamente (PEP)</label>
<select class="form-control" id="exposicion_politica" name="exposicion_politica" required>
<option value="0">---</option>
<option value="SI">SI</option>
<option value="NO">NO</option>
</select>
<label for="ap_nom_etica1">*Apellidos y Nombres 1</label>
<input class="form-control" id="ap_nom_etica1" name="ap_nom_etica1" required type="text" value="">
<label for="">*Apellidos y Nom</label>
<input class="form-control" name="ap_nom_etica1" required type="hidden" value="">
<label for="">*Apellidos y Nom</label>
<input class="form-control" name="ap_nom_etica1" required type="text" value="">
</div>
</fieldset>
Other way would be to directly select the inputs & select and add br tag instead of using each loop .
Demo Code :
$("input:visible ,select:visible").after("<br/><br/>")
$("input:hidden ,select:hidden").prev().css('display', 'none');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<legend>Ética y Cumplimiento:</legend>
<fieldset style="border: 1px solid #000;">
<br>
<div id="formulario3">
<label for="exposicion_politica">* Indique si alguna persona mencionada en el presente formulario es/fue una Persona Expuesta Políticamente (PEP)</label>
<select class="form-control" id="exposicion_politica" name="exposicion_politica" required>
<option value="0">---</option>
<option value="SI">SI</option>
<option value="NO">NO</option>
</select>
<label for="ap_nom_etica1">*Apellidos y Nombres 1</label>
<input class="form-control" id="ap_nom_etica1" name="ap_nom_etica1" required type="text" value="">
<label for="">*Apellidos y Nom</label>
<input class="form-control" name="ap_nom_etica1" required type="hidden" value="">
<label for="">*Apellidos y Nom</label>
<input class="form-control" name="ap_nom_etica1" required type="text" value="">
</div>
</fieldset>

Related

fastapi form not getting jquery cloned elements

I am using jquery to clone elements in a form and send all the data to a fastapi app. The problem I am finding is fastapi is not picking up the extra elements in the form.
Here is the code:
<button id="{{x.employee_id}}" class="btn btn-success eventBtn">Add Subject</button>
<form action="/cxc?id={{x.employee_id}}" method="POST">
<div id="cxc_form{{x.employee_id}}">
<div id="add_form{{x.employee_id}}">
<div class="row">
<div class="col">
<label class="form-label" for="area">Area of study:</label><br>
<select class="form-control" name="area0" id="area0">
{% for area in areas %}
<option value="{{area.qualification_area_id}}">{{area}}</option>
{% endfor %}
</select>
</div>
<div class="col">
<label class="form-label" for="deg">Grades:</label><br>
<select class="form-control" name="deg0" id="deg0">
{% for weight in weight %}
<option value="{{weight.weight_id}}">{{weight}}</option>
{% endfor %}
</select>
</div>
</div>
<div class="row">
<div class="col">
<label class="form-label" for="country">Country:</label><br>
<select class="form-control" name="country0" id="country0">
{% for country in countries %}
{% if country.country_id == 186 %}
<option value="{{country.country_id}}" selected>{{country.name}}</option>
{% else %}
<option value="{{country.country_id}}">{{country.name}}</option>
{% endif %}
{% endfor %}
</select>
</div>
<div class="col">
<label class="form-label" for="yr">Year obtained:</label><br>
<input class="form-control" type="date" id="yr0" name="yr0" placeholder="Year received">
</div>
</div>
<hr>
</div>
</div>
<input class="btn btn-primary" type="submit" value="Add">
</form>
And the jquery:
let i = 1
$(document).ready(function() {
$(".eventBtn").click(function(e){
let id = e.target.id;
let f = "#add_form" + id
let c = "#cxc_form" + id
let old = $(f).clone()
old.find("select").each(function() {
this.name = this.name.replace('0', i)
this.id = this.id.replace('0', i)
})
old.find("input").each(function() {
this.name = this.name.replace('0', i)
this.id = this.id.replace('0', i)
})
$(old).appendTo(c);
i = i+1
});
});
And fastapi:
#app.post("/cxc")
async def add_cxc(id: int, request: Request, db: Session = Depends(get_db)):
form = await request.form()
print(form)
Does any one know why it is not giving me the data from the cloned elements. All I am getting in my request is
FormData([('area0', '1'), ('deg0', '1'), ('country0', '186'), ('yr0', '')])

How to change required = false to an input that is required

My html file has a select, with three different options. If you select one it will display different inputs depending on what option you choose, but these inputs are required by default, and I can't send the form if I don't fill all the inputs.
function yesnoCheck(that) {
if (that.value == "1") {
document.getElementById("ifStudent").style.display = "block";
} else {
document.getElementById("ifStudent").style.display = "none";
}
if (that.value == "2") {
document.getElementById("ifAcademic").style.display = "block";
} else {
document.getElementById("ifAcademic").style.display = "none";
}
if (that.value == "3") {
document.getElementById("ifWorker").style.display = "block";
} else {
document.getElementById("ifWorker").style.display = "none";
}
}
<div class="select">
<select onchange="yesnoCheck(this);" name="school_role" required>
<option value="">--------</option>
<option value="1">Student</option>
<option value="2">Academic</option>
<option value="3">Employee</option>
</select>
</div>
<div id="ifStudent" style="display: none;">
<label class="label">Account number</label>
<input class="input" type="text" name="account_number" value="{{ studentform.account_number.value }}" placeholder="Account number">
<div class="help is-danger">
{% for error in studentForm.account_number.errors %}{{ error }}{% endfor %}
</div>
<div id="ifEmployee" style="display: none;">
<label class="label">Employee Number</label>
<input class="input" type="text" name="employee_number" value="{{ employeeForm.employee_number.value }}" placeholder="Employee number">
<div class="help is-danger">
{% for error in employeeForm.employee_number.errors %}{{ error }}{% endfor %}
</div>
<div id="ifAcademic" style="display: none;">
<label class="label">Academic number</label>
<input class="input" type="text" name="academic_number" value="{{ academicForm.academic_number.value }}" placeholder="Academic number">
<div class="help is-danger">
{% for error in academicForm.academic_number.errors %}{{ error }}{% endfor %}
</div>
Add required attribute to all inputs. I'm not confident in code style, but as a logical example:
<input ... name="account_number" required="{{school_role === 1}}" ... />
Add </div> to each section
Give each div a class of hide
Toggle the hide on change of the select
toggle the required
const ifs = [...document.querySelectorAll("[id^=if]")];
document.getElementById("school_role").addEventListener("change", function() {
const val = this.options[this.selectedIndex].textContent;
ifs.forEach(ifDiv => {
ifDiv.classList.toggle("hide", !ifDiv.id.includes(val))
const input = ifDiv.querySelector("input");
if (ifDiv.classList.contains("hide")) input.removeAttribute("required")
else input.setAttribute("required", true)
});
})
.hide {
display: none;
}
<div class="select">
<select name="school_role" id="school_role" required>
<option value="">--------</option>
<option value="1">Student</option>
<option value="2">Academic</option>
<option value="3">Employee</option>
</select>
</div>
<form>
<div id="ifStudent" class="hide">
<label class="label">Account number</label>
<input class="input" type="text" name="account_number" value="" placeholder="Account number">
<div class="help is-danger">
{% for error in studentForm.account_number.errors %}{{ error }}{% endfor %}
</div>
</div>
<div id="ifEmployee" class="hide">
<label class="label">Employee Number</label>
<input class="input" type="text" name="employee_number" value="" placeholder="Employee number">
<div class="help is-danger">
{% for error in employeeForm.employee_number.errors %}{{ error }}{% endfor %}
</div>
</div>
<div id="ifAcademic" class="hide">
<label class="label">Academic number</label>
<input class="input" type="text" name="academic_number" value="" placeholder="Academic number">
<div class="help is-danger">
{% for error in academicForm.academic_number.errors %}{{ error }}{% endfor %}
</div>
</div>
<input type="submit">
</form>

Sync inputs elements in ejs template

I have a ejs template rendered with an array (called "operaciones") result of a sql request.
How can I implement that when the user select a register ("unidad de obra") the other inputs show the fields "unidad de medida" and "precio unitario"?
This is my code:
<div class="col-md-6">
<label for="via">Unidad de obra:</label>
<select class="form-control" id="operacion" name="operacion" value="<%= medicion.idope %>" id="medicion">
<% for(var i=0; i < operaciones.length; i++) { %>
<option value=<%= operaciones[i].gid %>><%= operaciones[i].codigo %>-<%= operaciones[i].descr %></option>
<% }%>
</select>
</div>
<div class="col-md-3">
<label>Unidad de medida:</label>
<input type="text" class="form-control" id="unidad" name="unidad" value="" disabled/>
</div>
<div class="col-md-3">
<label>Precio unitario (€):</label>
<input type="text" class="form-control" id="preciou" name="preciou" value="" disabled/>
</div>
You could output these values into the data attribute of the options. Then add some jquery to handle the select and update the values. (Ive replaces ejs with object literals to make it work in a Snippet):
//serverside
var operaciones = [
{gid:1,codigo:2,descr:2,unidad:3,preciou:4},
{gid:5,codigo:6,descr:2,unidad:7,preciou:8},
];
var c = `
<div class="col-md-6">
<label for="via">Unidad de obra:</label>
<select class="form-control" id="operacion" name="operacion">`;
for(var i=0; i < operaciones.length; i++) {
c+=`
<option
value="${ operaciones[i].gid}"
data-unidad="${ operaciones[i].unidad}"
data-preciou="${ operaciones[i].preciou}"
>
${operaciones[i].codigo}-${ operaciones[i].descr}
</option>`;
}
c += `
</select>
</div>
<div class="col-md-3">
<label>Unidad de medida:</label>
<input type="text" class="form-control" id="unidad" name="unidad" value="1" disabled/>
</div>
<div class="col-md-3">
<label>Precio unitario (€):</label>
<input type="text" class="form-control" id="preciou" name="preciou" value="2" disabled/>
</div>`;
document.body.innerHTML = c;
//userside
$(function(){
$("#operacion").on("change",function(){
var selected = $(this).children("option:selected");
$("#unidad").val(selected.data("unidad"));
$("#preciou").val(selected.data("preciou"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Make Password Field Not Required in Shopify Create Customer Form

I am trying to create a from on my shopify store that will collect an email address and a "Goal" however I believe the default functionality of shopify requires a password to create an account for the shopify store. I want to get around the password requirement. I have pasted what I have so far, any help would be amazing.
{% form 'create_customer' %}
{{ form.errors | default_errors }}
{% if form.posted_successfully? %}
<script>
window.location = "https://www.thankyoupage";
</script>
{% endif %}
<div class="clearfix large_form">
<label for="email" class="login">Email Address</label>
<input type="email" value="" name="customer[email]" id="email" class="large" size="30" />
</div>
<div class="clearfix large_form">
<label for="goal">Goal </label>
<select name="customer[note][Goal]" id="goal">
<option value=""></option>
<option value="Lose Weight">Goal 1 </option>
<option value="Eat Healthy">Gaol2</option>
<option value="Peak Performance">Goal 3</option>
</select>
</div>
<div class="clearfix large_form" style="display:none;">
<label for="password" class="login">Password</label>
<input type="password" value="" name="customer[password]" id="password" class="large password" size="30" is_required="0" />
</div>
<button type="submit" value="Create">Get Started</button>
{% endform %}
If you prefill the field with a default (random) value, the form check requirements should be satisfied.

jquery don't submit form

Hi I'm trying to validate form with jquery before submit. The validation works fine, but never submit.
There is the form:
<form class="form-signin panel-body" role="form" action="addUser" method="post" id="register">
<h2 class="form-signin-heading">Sign Up</h2>
<div id="na" class="form-group">
<input type="text" id="name" name="name" class="form-control" placeholder="Name" required>
</div>
<div id="su" class="form-group">
<input type="text" id="surname" name="surname" class="form-control" placeholder="Surname" required>
</div>
<div id="user" class="form-group">
<input type="text" id="username" name="username" class="form-control" value="<%= request.getParameter("username1") %>" placeholder="Username" required>
</div>
<div id="mail" class="form-group">
<input type="email" id="email" name="email" class="form-control warning" value="<%= request.getParameter("email1") %>" placeholder="Email address" required>
</div>
<div id="pa" class="form-group">
<input type="password" id="password" name="password" class="form-control" value="<%= request.getParameter("password1") %>" placeholder="Password" required>
</div>
<select class="form-control" id="year" name="year">
<option value="">Year</option>
</select>
<select class="form-control" id="month" name="month">
<option value="">Month</option>
</select>
<select class="form-control" id="day" name="day">
<option value="">Day</option>
</select>
<div class="row">
<span> </span>
</div>
<label>
<select class="form-control" id="sex" name="sex">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</label>
<label>
By clicking Sign up, you are agree to our<a data-toggle="modal" href="#terms"> Terms and
Conditions</a> and have read our usage policy data, including ouruse of
<a data-toggle="modal" href="#cookies">cookies</a>.
</label>
<button id="send" class="btn btn-lg btn-primary btn-block" >Sign in</button>
</form>
Mainly I want refuse duplicate username's or email adress. There's my jquery script:
$(document).ready(function() {
$("#register").submit(function(event){
// $("#register").click(function(){
var $username = $("#username").val();
var $mail = $("#email").val();
// Evita que si alguna comprovacio retorna false s'envi el formulari
event.preventDefault();
// Funcio que valida que el nom no estigui en blanc
if($("#name").val().trim() == ""){
$("#na").addClass( "has-error");
return false;
}
// Funcio que valida que el cognom no estigui en blanc
if($("#surname").val().trim() == ""){
$("#su").addClass( "has-error");
return false;
}
// Funcio ajax per validar que el nom d'usuari no està en ús
$.ajax({
url: "/projCreditV1/rwsc/as/check-value/user_name/" + $username,
success: function(data){
// Si retorna TRUE vol dir que el nom d'usuari es valid perque no està en ús
if(data == "true"){
$("#mail").removeClass("has-error");
return true;
}
else{
$("#user").addClass("has-error");
return false;
}
}
});
// Funcio ajax per validar que el mail no està en ús
$.ajax({
url: "/projCreditV1/rwsc/as/check-value/mail/" + $mail,
success: function(data){
// Si retorna TRUE vol dir que el mail es valid perque no està en ús
if(data == "true"){
$("#mail").removeClass("has-error");
return true;
}
else{
$("#mail").addClass("has-error");
return false;
}
}
});
// Funcio que valida que la contrasenya no estigui en blanc
if($("#password").val().trim() == ""){
$("#pa").addClass( "has-error");
return false;
}
});
});
When some field doesn't meets the requirements return false. I think if whole form doesn't return false, should submit..
Thanks
please remove the event.preventDefault();.
if you use that code, it will never execute the form.
The reason the submit doesn't finish is the:
event.preventDefault(); line. The return doesn't work for the async request. Because it doesn't return the value back to the event.
A way to fix this would be:
Make a normal button instead of a submit button
make jquery do the
submit.

Categories