I have an HTML form with input fields. I am trying to get the data from the input fields to be passed to a javascript function for processing. I am trying to get the value of "tenantid" but the only thing I get, when displaying the value in the popup:
first objectHMTLFormElement
How can I get values entered in the form to the Javascript code?
TIA
I have:
testing.blade.php
<script type="text/javascript" src="{{ URL::asset('js/test.js') }}">
</script>
[.. snip ..]
<form id="oogie" class="form-horizontal" role="form" method="POST" action="{{ url('') }}/dashboard">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('tenantid') ? ' has-error' : '' }}">
<label for="tenantid" class="col-md-4 control-label"> Tenant ID </label>
<div class="col-md-6">
<input id="tenantid" type="integer" class="form-control" name="tenantid" value="{{ old('tenantid') }}" required autofocus>
#if ($errors->has('tenantid'))
<span class="help-block">
<strong>{{ $errors->first('tenantid') }}</strong>
</span>
#endif
</div>
</div>
</form>
[... snip ...]
<button class="ClickMe" onclick="testme();">Click me</button>
test.js
function testme()
{
alert("got in");
var parameters = document.getElementById("oogie");
alert("first " + parameters );
}
That's because your script isn't trying to access the value of the field, but the field itself.
You should use document.getElementById(ID).value. This will fix your issue.
Related
I am doing a project in Django. In my views I send data to the HTML pages with dictionaries. I can easily access that data on HTML, but when I try to access it on Javascript I can't because Javascripts thinks it's a variable name.
For example, I have a log in page. If the credentials are wrong, I send them to the same page and tell them that the username or password are wrong. I want to keep the previously written username on the form, so the person only needs to rewrite the password. I send the username from the view to the Javascript, but I can't access it.
My view code:
def login_form(request):
assert isinstance(request, HttpRequest)
if 'username' and 'password' in request.POST:
user = request.POST['username']
passw = request.POST['password']
if rightcredentials(user,passw):
tparams = {
'message': 'login successful',
}
return render(request, 'about.html', tparams)
else:
tparams = {
'login' : 'failure1',
'username_info' : user
}
return render(request, 'login_form.html', tparams)
Javascript code:
{% if login == 'failure1' %}
<form action="." method="post">
{% csrf_token %}
<div class="program-info">
<h3 class="program-title">Sign Into Your Account</h3>
<p>Wrong Username or password</p>
<div class="form-group">
<input type="text" value="" class="form-control" name="username" id="username" placeholder="Username">
</div>
<div class="form-group">
<input type="password" class="form-control" name="password" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary">Log In</button>
</div>
</form>
<script type="text/javascript">
{% autoescape off %}
var paramvalue = {{ username_info }}
{% endautoescape %}
document.getElementById("username").value = paramvalue;
</script>
{%endif%}
After inserting username: 'pedro' and the wrong password on the form I get the following error:
Uncaught ReferenceError: pedro is not defined
Is there a way to access the string username_info or a way to convert the variable name to a string?
Wrapping the {{ }} in quotation marks should do the trick
{% autoescape off %}
var paramvalue = "{{ username_info }}"
{% endautoescape %}
In my Django/Python application I have fields which are necessary or not, depending on what is selected in previous fields. Thats why those are not mandatory by default. I would like to run a script which would raise an error on the chosen field, depending on the selection. I would like to do that when 'Submit' button is pressed, via script.
My html code:
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST" id="PostForm" data-sektor-url="{% url 'ajax_load_sektors' %}" novalidate enctype="multipart/form-data">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Report</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" id="submit" type="submit">Submit</button>
</div>
</form>
</div>
<script>
$("#submit").click(function () {
if (document.getElementById('id_res_person_1').value == '') {
HERE I WOULD RAISE AN ERROR ON THAT FIELD
}
});
</script>
You need to call a function when form is submitted, make your validation and if all good submit to the view
Here is an example:
JS
function validate(url) {
// do your validation
if(allIsOk){
// get the form
my_form.submit();
}
}
On Submit or link
<fom onsubmit="validate()">
I am trying to build a one page web page using PHP laravel and all its features.
I use javascript to scroll through the pages when pressing specific links.
At the bottom of the page I have a form that runs some php code (sends an email,...)
After this POST request I redirect back to my webpage.
The problem is that when I redirect back I see the top of the page and the contact form and error or success codes are at the bottom of my page near the FORM.
This is why I am looking for a way to automatically scroll/move to the contact form after the post request just like i do when pressing the link button.
HTML:
#if (count($errors) > 0)
<div class="alert alert-danger">
<button type="button" class="close" data-dismiss="alert">×</button>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
#endif
<form method="post" action="sendemail">
{{ csrf_field() }}
<div class="form-group">
<label for="exampleFormControlInput1">Name</label>
<input type="text" class="form-control" name="name" id="exampleFormControlInput1">
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Email</label>
<input type="email" class="form-control" name="email" id="exampleFormControlInput1">
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Message</label>
<textarea class="form-control" name="message" id="exampleFormControlTextarea1" rows="8"></textarea>
</div>
<div class="form-group">
<input type="submit" name="send" class="btn btn-secondary" value="Send" />
</div>
</form>
</div>
PHP Route:
Route::post('/sendemail', 'App\Http\Controllers\SendEmailController#send');
PHP Controller:
function send(Request $request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email',
'message' => 'required'
]);
$data = array(
'name' => $request->name,
'email' => $request->email,
'message' => $request->message
);
Mail::to($request->email)->send(new SendMailValidation($data));
return back()->with('success', 'Thank you!');
}
Javascript (atm only used for client side browsing when pressing a link item):
let contactLinkItem = document.querySelector("#contactLinkItem");
contactLink.addEventListener("click", navigateContact, false);
function navigateContact() {
contactLinkItem.scrollIntoView({ behavior: "smooth" });
}
You can check if errors bag has any messages then call javascript function that you already created above to trigger scrolling behavior
#if($errors->any())
<script>
navigateContact()
</script>
#endif
// Your old code
let contactLinkItem = document.querySelector("#contactLinkItem");
contactLink.addEventListener("click", navigateContact, false);
function navigateContact() {
contactLinkItem.scrollIntoView({ behavior: "smooth" });
}
Recommendation:
Use Ajax calls with API to submit your forms (Or Livewire), and you have the ability to show validation errors without scrolling or even leaving the page. This is the best for your users experience.
When I send the from I get the value $_POST['person_id'] = "John Smith".
But I need the Id, not the name. I need: $_POST['person_id'] = 1.
HTML:
<form id="form-person" name="form-person" method="post" action="personchoose">
<div class="typeahead__container">
<div class="typeahead__field">
<div class="typeahead__query">
<input class="person_id" name="person_id"
placeholder="Search..." autocomplete="off" type="search">
</div>
<div class="typeahead__button">
<button type="submit">
<i class="typeahead__search-icon"></i>
</button>
</div>
</div>
</div>
</form>
JavaScript:
$.typeahead({
input: ".person_id",
order: "desc",
source: [{id:1, display:"John Smith"},{id:2, display:"Simen Nguien"},{id:3, display:"Maria Carlata"},{id:4, display:"Anna Sngenta"},{id:5, display:"Carmen Muller"}]
});
The way you are using the typeahead plugin is to pre-populate the text box before form submission. Therefore, the only value that is being submitted is the persons name in the textbox value.
There are many ways to achieve what you want but probably the easiest is to use the callback functions of the plugin. Either when someone clicks/selects the option or submits the form.
First add a hidden field to the form for the id of the person to be stored:
<form id="form-person" name="form-person" method="post" action="personchoose">
<div class="typeahead__container">
<div class="typeahead__field">
<div class="typeahead__query">
<input class="person_id" name="person_name"
placeholder="Search..." autocomplete="off" type="search">
<input type="hidden" name="person_id" id="person_id" value="" />
</div>
<div class="typeahead__button">
<button type="submit"> submit
<i class="typeahead__search-icon"></i>
</button>
</div>
</div>
</div>
</form>
Then use the callbacks to set the hidden field with the selected item:
$.typeahead({
input: ".person_id",
order: "desc",
source: [{id:1, display:"John Smith"},{id:2, display:"Simen Nguien"},{id:3, display:"Maria Carlata"},{id:4, display:"Anna Sngenta"},{id:5, display:"Carmen Muller"}],
callback: {
onClick: function (node, a, item, event) {
$('#person_id').val(item.id);
},
onSubmit: function() {
console.log($('#person_id').val());
}
}
});
I have a register form that I wish to do validation on the moment a user clicks submit. This is what the HTML looks like:
<form ng-submit="RegistrationC.fireReg()" novalidate name="register">
<div class="row">
<div class="col-md-6 form-group">
<input type="text" autocomplete="off" class="form-control" placeholder="First Name" ng-model="RegistrationC.first_name" required name="first_name">
<div class="help-block" ng-messages="register.first_name.$error" ng-show="submitted && register.first_name.$error">
<p ng-message="required">This field is required.</p>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 form-group col-md-offset-3">
<button type="submit" class="btn btn-success btn-block" ng-click="submitted=true">Register Now</button>
</div>
</div>
</form>
It is showing the validation message if a username is not typed in, but it still submits. What am I missing?
EDIT 1
//init.js - RegistrationController
reg_list.fireReg = function () {
var url = 'user/register';
api.makeCall(reg_list, url)
.then(function (response) {
reg_list.response = response;
console.warn(response);
$location.path('/user/verify');
})
.catch(function (errorMessage) {
console.log("got an error in initial processing", errorMessage);
event.restoreButton();
});
};
I know there's issues in this function, I will fix them at a later stage.
Submit this form only if it is valid. <whatever_form_name>.$valid
<form ng-submit="register.$valid && RegistrationC.fireReg()" novalidate name="register">
Just add checkpoint whether form is valid or not before submitting form
Try like this
<form ng-submit="register.$valid && RegistrationC.fireReg()" novalidate name="register">
If you want to disable html5(or browser) validator, You have to remove 'required' attribute in your html code
http://www.the-art-of-web.com/html/html5-form-validation/
http://www.w3schools.com/tags/att_input_required.asp