How to get the username from HTML form to JavaScript? - javascript

I'm trying to get the user enter a username and access that value from a separate js file. The page redirects from one html to another after the user enters the name in the server (python) code. Is it causing the issue? Because, no matter what method (name, id, form, input field) I try it doesn't work. If I run the script from within the html file then I'm able to access it. Any help is appreciated!
const userStore = window.localStorage;
document.addEventListener('DOMContentLoaded', () => {
// Connect to websocket
var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);
if (!userStore.getItem('username')){
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('#username').onsubmit = function() {
const name = document.querySelector('#username').value;
alert(`Welcome back ${name}!`);
};
});
} else {
userStore.setItem('username', document.querySelector("#username"));
}
{% extends "layout.html" %}
{% block title %}
Title
{% endblock %}
{% block main %}
<section id="cover" class="min-vh-100">
<div id="cover-caption">
<div class="container">
<div class="row text-white">
<div class="col-xl-5 col-lg-6 col-md-8 col-sm-10 mx-auto text-center form p-4">
<h1 class="display-4 py-2">Enter your Username.</h1>
<div class="px-2">
<form id="form" action="/flackchat" method="POST" class="justify-content-center">
<div class="form-group">
<label class="sr-only">Name</label>
<input id="username" type="text" class="form-control" name="username" placeholder="Username">
</div>
<button type="submit" class="btn btn-primary btn-lg">Continue</button>
</form>
</div>
</div>
</div>
</div>
</div>
</section>
{% endblock %}

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', '')])

Stripe 'card-element' isn't visible (Python/Django)

this is my first time using this site to ask a question. I'd appreciate the help, I have to turn in this bit of the project today as part of my course :(
I'm following this tutorial: https://www.youtube.com/watch?v=ncsCnC3Ynlw (chapter: stripe elements)
When I visit my checkout page, the card element isn't showing up.
I am at the stage around 3:45:00, and when looking at the checkout, the div for the card element is just a thin, empty bar.
Could anyone help me find where I made a mistake? I think it might be the connection between the script and the template or just the script itself, but I'm losing my mind trying to figure out what I've done wrong.
My views.py:
def BasketView(request):
carrinho = Carrinho(request)
total = str(carrinho.gettotal())
total = total.replace('.', '')
total = int(total)
stripe.api_key='sk_test_[...]'
intent = stripe.PaymentIntent.create(
amount=total,
currency='brl',
metadata={'integration_check': 'accept_a_payment', 'userid': request.user.id}
)
return render(request, 'pedido/pedido_novo.html', {'client_secret': intent.client_secret})
My html template:
{% load static %}
{% block title %}Livraria Aquaflora | Novo Pedido{% endblock %}
{% block adtscripts %}
<script src="https://js.stripe.com/v3/"></script>
<script src="https://unpkg.com/imask#6.0.7/dist/imask.js"></script>
<script src="{% static 'js/orderform.js' %}"></script>
<script src="{% static 'js/payment.js' %}" data-rel-js></script>
{% endblock %}
{% block conteudo %}
<div class="container-fluid">
<div class="row no-gutter">
<div class="col-md-12">
<div class="login d-flex align-items-center py-5">
<div class="container">
<div class="row">
<form id="payment-form" class="col-12 col-lg-6 mx-auto">
<div class="form-group">
<label class="small font-weight-bold">Nome</label>
<input type="text" class="form-control" id="custName" placeholder="Nome Completo" required>
</div>
<div class="form-group">
<label class="small font-weight-bold">CPF</label>
<input type="text" class="form-control" id="cpf" placeholder="CPF" required>
</div>
<div class="form-group">
<label class="small font-weight-bold">CEP</label>
<input type="text" class="form-control" id="cep" placeholder="CEP" required>
</div>
<div class="form-group">
<label class="small font-weight-bold">Endereço</label>
<input type="text" class="form-control" id="ender" placeholder="Endereço com Número e complemento" required>
</div>
<div class="form-group">
<label class="small font-weight-bold">Bairro</label>
<input type="text" class="form-control" id="bairro" placeholder="Bairro" required>
</div>
<div class="form-group">
<label class="small font-weight-bold">Cidade</label>
<input type="text" class="form-control" id="cidade" placeholder="Cidade" required>
</div>
<div class="form-group">
<label class="small font-weight-bold">Estado</label>
<input type="text" class="form-control" id="estado" placeholder="Estado" required>
</div>
<hr class="my-4">
<h4 class="mb-3">Pagamento</h4>
<hr class="my-4">
<div id="payment-element" class="form-control form-control-payment">
</div>
<button id="submit" class="btn btn-primary btn-block py-2 mb-4 mt-5 fw500 w-100" data-secret="{{ client_secret }}">Pagar</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
var CSRF_TOKEN = '{{ csrf_token }}';
</script>
{% endblock %}
and finally, my script,
var stripe = Stripe('pk_test_[...]');
var elem = document.getElementById('submit');
clientsecret = elem.getAttribute('data-secret');
var elements = stripe.elements();
var style = {
base: {
color: "#000",
lineHeight: '2.4',
fontSize: '16px'
}
};
var card = elements.create("card", { style: style });
card.mount("#card-element");
card.on('change', function(event) {
var displayError = document.getElementById('card-errors')
if (event.error) {
displayError.textContent = event.error.message;
$('#card-errors').addClass('alert alert-info');
} else {
displayError.textContent = '';
$('#card-errors').removeClass('alert alert-info');
}
});
I figured it out. Leaving it here for other dummies like me.
Do not add the .js file to the top of the page. Add it to the bottom, after the /body tag. Turns out values will be NULL if the javascript loads before the page.
The Python code looks correct, at least it looks like mine does in my working integration using Django. So here's a couple of things to try:
You don't need the clientSecret until you use stripe.confirmCardPayment() so don't fetch it yet.
Try putting the data-secret="{{client_secret}}" on the <form> element. You'll need to add an events listener to the <form>'s "submit" event anyway to prevent the default submission and trigger the confirmation so might as well retrieve the client_secret then.
I know this doesn't answer why the button was no selectable but at least it gives you some next steps.

Creating input fields inside a form using JavaScript

I'm working on a quiz app and want to generate a number of input fields representing the answers based on the value that the user types.
I'm using a button named "create" to do that Using JavaScript, but when clicking the button it submits the form.
Please Check the two images below.
Input
Output
HTML Code
{% load static %}
{% block body %}
<button class="btn btn-primary new">Add a question</button>
<form class="question" method="POST" style="display: none">
{% csrf_token %}
<div class="form-group">
<label for="exampleInputEmail1">Title</label>
<input type="text" class="form-control" id="title" placeholder="Question title">
</div>
<div class="form-group" id="answers_num">
<label for="exampleInputPassword1">Number of answers</label>
<input type="number" class="form-control" id="ans_number">
<button class="create_answers">Create</button>
</div>
<div class="form-group">
{% comment %} Generated input fields {% endcomment %}
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
{% block script %}
<script src="{% static 'mcq/index.js' %}"></script>
{% endblock %}
{% endblock %}```
JS code
document.querySelector(".new").addEventListener("click", ()=> {
document.querySelector(".question").style.display = 'block';
document.querySelector("#create_answers").addEventListener("click", ()=> {
answers = this.value;
console.log(answers);
// Create input fields
for (let i = 0; i < answers; i++) {
input = document.createElement("input");
input.classList.add('form-control');
answersDiv = document.querySelector("#answers").appendChild(input);
}
})
})```
You need to explicitly set the type of the button, like
<button class="create_answers" type="button">Create</button>
in order to avoid submitting the form upon click.

Is it possible that jquery .html() method loads code partialy?

I have a following code in jQuery:
$(".edit-trigger").on("click", function () {
url = $(this).data('url');
$.get(url, function(data) {
$("#modal .modal-content").html(data);
});
});
and it is loading following code (data) into modal window:
<form id="personal_info_form" class="modal-form">
<input type="hidden" value="{{ csrf_token }}" name="csrfmiddlewaretoken">
<div class="modal-content">
{% for field in form %}
<div class="row">
<div class="input-field col s12">
{{ field }}
<label for="{{ field.id }}" data-error="wrong">{{ field.label }}</label>
</div>
</div>
{% endfor %}
</div>
<div class="modal-footer">
<button class="modal-action modal-close">Anuluj</button>
<button type="submit">Akceptuj</button>
</div>
</form>
<script>
M.updateTextFields();
</script>
The issue is that script in loaded code is not always executed. Is it possible to ensure execution of that script?

Django form is not displaying

I am new to django forms and while trying to design an HTML form, I notice that the django form blocks are not displaying. Below are the codes:
<body> tag of index.html:
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-login">
<div class="panel-heading">
<div class="row">
<div class="col-xs-6">
Login
</div>
<div class="col-xs-6">
Register
</div>
</div>
<hr>
</div>
<div class="panel-body">
<div class="row">
<div class="col-lg-12">
{% block login_content %}
{% endblock %}
{% block register_content %}
{% endblock %}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
login.html which goes into the {% block login_content %}
{% extends 'index.html' %}
{% block login_content %}
<form id="login-form" action="{% url 'authentication:user_login' %}" role="form" style="display: block;" method="POST">
{% csrf_token %}
<label for="username">Username:</label>
<input id="username" type="text" name="username" placeholder="Enter Username" tabindex="1" class="form-control">
<label for="password">Password:</label>
<input id="password" type="password" name="password" tabindex="=2" class="form-control" placeholder="Password">
<button type="submit" class="btn btn-success">Login</button>
</form>
{% endblock %}
register.html that goes into the {% block register_content %}
{% extends 'index.html' %}
{% block register_content %}
<form id="register-form" role="form" style="display: none;" enctype="multipart/form-data" method="POST">
{% csrf_token %}
{{ user_form.as_p }}
{{ profile_form.as_p }}
<input type="submit" name="" value="Register">
</form>
{% endblock %}
On my UI, the {{ user_form.as_p }} and the {{ profile_form.as_p }} does not appear at all.
When i inspect the console of my UI, the html does not even pick up the following line from the register.html:
<form id="register-form" role="form" style="display: none;" enctype="multipart/form-data" method="POST">
Here is the login.js which is responsible for the UI interactivity:
$(function() {
$('#login-form-link').click(function(e) {
$("#login-form").delay(100).fadeIn(100);
$("#register-form").fadeOut(100);
$('#register-form-link').removeClass('active');
$(this).addClass('active');
e.preventDefault();
});
$('#register-form-link').click(function(e) {
$("#register-form").delay(100).fadeIn(100);
$("#login-form").fadeOut(100);
$('#login-form-link').removeClass('active');
$(this).addClass('active');
e.preventDefault();
});
});
EDIT:
Here is my views.py:
def user_login(request):
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user:
if user.is_active:
login(request, user)
return HttpResponseRedirect(reverse('homepage')) # main page if login is successful
else:
return HttpResponse("ACCOUNT NOT ACTIVE")
else:
print('Someone tried to log in and failed')
print('Username: {}, password, {}'.format(username, password))
return HttpResponse('Invalid login details supplied')
else:
return render(request, 'authentication/login.html', {})
def register(request):
registered = False
if request.method == "POST":
user_form = UserForm(data=request.POST)
profile_form = UserProfileInfoForm(data=request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
if 'profile_pic' in request.FILES:
profile.profile_pic = request.FILES['profile_pic']
profile.save()
registered = True
else:
print(user_form.errors, profile_form.errors)
else:
user_form = UserForm()
profile_form = UserProfileInfoForm()
return render(request, 'authentication/register.html',
{
'user_form': user_form,
'profile_form': profile_form,
'registered': registered
})
Okay, it seems like it is impossible to have a single page display both the templates. Is there anyway to get it done?
In your register.html,
<form id="register-form" role="form" style="display: none;" enctype="multipart/form-data" method="POST">
You are setting style="display: none;", so obviously the form won't show up.
EDIT: I am not sure about the feasibility of showing two different forms in the same page.

Categories