I am using javascript for validating a form in django template, but it's not working,
the DOM events are not fetching the values. even if i give valid input
to form the console says empty string
HTML snippet
<form onsubmit="return validate_hotel()" action="confirm_hotel/{{hotel_name}}" method="post">
{% csrf_token %}
<div id="left">
<label>Check in date</label>
<input id="checkin" type="date" autocomplete="off" name="checkin" > <br><br>
<label>Number of guests</label><br>
<select autocomplete="off" name="guests" id="guests">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select><br><br>
<label>Username</label>
<input id="HotelUsername" type="text" name="username" autocomplete="off">
</div>
<div id="right">
<label>Check out date</label>
<input id="checkout" type="date" autocomplete="off" name="checkout"> <br><br>
<label>Number of rooms</label><br>
<select autocomplete="off">
<option value="1">1</option>
<option value="2">2</option><br>
</select><br><br>
<label> password</label>
<input id="password" type="password" autocomplete="off" name="password" >
</div>
<br><label id="hotel_error_message"> {{error_message}} </label><br>
<button type="submit">Confirm booking</button>
</form>
here is the javascript function i am using to validate things.
i am using document.getElementById() method to fetch the input values.
function validate_hotel()
{
var hotel_username = document.getElementById("HotelUsername").value;
var checkin = document.getElementById("checkin").value;
var checkout = document.getElementById("checkout").value;
var hotel_password = document.getElementById("password").value;
var date_regx = /^(19|20)\d\d([- /.])(0[1-9]|1[012])\2(0[1-9]|[12][0-9]|3[01])$/
var username_regx = /^[a-zA-Z0-9_$.#]+$/
var password_regx = /^(?=.*\d).{4,12}$/
var valid = true;
console.log(hotel_username, checkin, checkout, hotel_password);
if (! username_regx.test(hotel_username))
{
valid = false;
}
if (! password_regx.test(hotel_password))
{
valid = false;
}
if (! date_regx.test(checkin))
{
valid = false;
}
if (! date_regx.test(checkout))
{
valid = false;
}
if (!valid)
{
document.getElementById("hotel_error_message").innerHTML = "Invalid inputs";
}
return valid;
};
Javascript code is executed by the browser (client side) and It is not related to backend (django etc ...). Your code has no problem and works correctly.
To check javascript code I'm using Firefox debugger. It is possible to create break points in your javascript code and watch the variables to check if they get value or not.
In Firefox browser, open debugger.
Find the file that contains javascript code
create some break points on some lines
execute your code (submit the form)
and then by hovering the mouse on your variables check if they get value or
not. you can also add some watch to check variables.
when your code is stopped at break points, checking the value of variables is also
available in console.
Anyway, the code works correctly check if you have some elements with same name or something like this.
Related
I want to check if the Value enter in the input is in the datalist.
If not i inform that the value is not in the list, I write something but the submit is done anyway, i miss something ?
Edit: I edit to have a trial form. If i enter productD the submit can't not be done becuase is not in the list defined.
<tbody>
<div class="fichetechniquediv">
<form action="{% url 'createdfichetechnique' %}" method='post' onclick="return myCheckFunction(this)">
<h1>Create the technical Sheet</h1>
<br><br>
<div class="divlot">
<label for="lot">Enter your Lot:</label>
<input type="text" id="lot" name="lot" required minlength="7" oninput="this.value = this.value.toUpperCase()">
</div>
<br><br>
<div class="divproduct">
<label for="productlist">Enter or Select Product:</label>
<input type="text" name="Product" id="productlist" list="productslist" label="'Enter or Select your Product:">
<datalist id="productslist">
<option value="productA">productA</option>
<option value="productB">productB</option>
<option value="productC">productC</option>
</datalist>
</div>
<br><br>
<input class="buttonsave" type="submit" value="Create" name="submit">
</form>
</div>
</tbody>
<script>
function myCheckFunction(form) {
var list = document.getElementsById("productslist");// get the values that are currently under the datalist tag in option tags
var val = document.getElementsByName("Product");// get the user input
if( list.include(val)){ // compare the options with the user input
submit(form)}// if one is equal with the user input submit the form with the method submit();
else{
return false// else don't submit the form, the user will have to change his input
}
}
</script>
Example productD
const list = document.querySelector("#productslist")
const btn = document.querySelector(".buttonsave")
console.log(list.options.length)
if(list.options.length <= 0 ){
btn.disabled = true
}else {
btn.disabled = false
}
Check if is any products. If the script can't see any products disable the button to send. I hope I helped
You cannot use include for DOM elements like you do.
Also you have duplicate IDs
Instead do this:
const list = document.querySelectorAll("productslist option")
document.getElementById("myForm").addEventListener("submit", function(e) {
const val = document.getElementById("productlistInput").value
const found = [...list].find(opt => opt.value===val)
if (!found) {
alert("Please choose an existing value");
e.preventDefault();
}
})
<form id="myForm" action="..." method='post'>
<h1>Create the technical Sheet</h1>
<br><br>
<div class="divlot">
<label for="lot">Enter your Lot:</label>
<input type="text" id="lot" name="lot" required minlength="7" oninput="this.value = this.value.toUpperCase()">
</div>
<br><br>
<div class="divproduct">
<label for="productlist">Enter or Select Product:</label>
<input type="text" name="Product" id="productlistInput" list="productslist" label="'Enter or Select your Product:">
<datalist id="productslist">
<option value="prod1">Product 1</option>
<option value="prod2">Product 2</option>
</datalist>
</div>
<br><br>
<input class="buttonsave" type="submit" value="Create" name="submit">
</form>
There are two things going wrong in this:
document.getElementsById("productslist"); is incorrect. The function is getElementById(...)
document.getElementById("productslist"); will get you an HTML nodes, not the values.
One of the ways to get the values is:
const values = [];
Array
.from(document.getElementById("productslist").options)
.forEach((option) => {
values.push(option.value);
}
Now that you have the values in the values array, you can look it up to check if the value is already present.
So this is my first question, and it's also the first code I'm trying to write.
I basically want to make a form to collect values like the Departing Airport Code. An input for the Departing Airport Code would look like 'ams'.
This value is needed to customize the URL which the getLink function opens in a new tab.
I've read other questions and tried a lot of things. But the input doesn't appear in the URL that gets opened in the new tab.
In this example, I'm trying to get the input with '+dairport+' placed in the getLink URL.
How can I get the input data from the form and use it in the URL that gets opened when I click the button?
document.getElementById("dairport").value = "dairport";
function getLink(dairport) {
window.open("https://www.skyscanner.nl/transport/flights/+dairport+/jfk/210701/210714/?adults=1&adultsv2=1&cabinclass=business&children=0&childrenv2=&destinationentityid=27537542&inboundaltsenabled=false&infants=0&originentityid=27536561&outboundaltsenabled=false&preferdirects=false&preferflexible=false&ref=home&rtn=1");
}
<form name="box">
<label for="dairport">Departing Airport Code:</label><br>
<input type="text" id="dairport" name="dairport"><br>
<label for="aairport">Arriving Airport Code:</label><br>
<input type="text" id="aairport" name="aairport"><br>
<label for="ddate">Departing Date:</label><br>
<input type="date" id="ddate" name="ddate"><br>
<label for="adate">Arriving Date:</label><br>
<input type="date" id="adate" name="adate"><br>
<label for="class">Class:</label><br>
<select id="class" name="class"><br>
<option value="business">Business</option>
<option value="first">First</option>
</select><br>
<button onclick="getLink(dairport);">Launch</button>
</form>
document.getElementById("dairport").value = "dairport"; will set the value of the input with the id of dairport. What you want to do is get the value the user entered. That is just document.getElementById("dairport").value and should be inside your getLink() function.
You also don't really need a form since you aren't submitting any information to a server or similar.
Then you can use template literals to include the value of the departingAirport variable in the link to open. What you are doing is adding the literal string +airport+ in the URL which is no good, you need to put the value of the variable (which is what template literals help with).
function getLink() {
let departingAirport = document.getElementById("dairport").value;
window.open(`https://www.skyscanner.nl/transport/flights/${departingAirport}/jfk/210701/210714/?adults=1&adultsv2=1&cabinclass=business&children=0&childrenv2=&destinationentityid=27537542&inboundaltsenabled=false&infants=0&originentityid=27536561&outboundaltsenabled=false&preferdirects=false&preferflexible=false&ref=home&rtn=1`);
}
<label for="dairport">Departing Airport Code:</label><br>
<input type="text" id="dairport" name="dairport"><br>
<label for="aairport">Arriving Airport Code:</label><br>
<input type="text" id="aairport" name="aairport"><br>
<label for="ddate">Departing Date:</label><br>
<input type="date" id="ddate" name="ddate"><br>
<label for="adate">Arriving Date:</label><br>
<input type="date" id="adate" name="adate"><br>
<label for="class">Class:</label><br>
<select id="class" name="class"><br>
<option value="business">Business</option>
<option value="first">First</option>
</select><br>
<button onclick="getLink();">Launch</button>
#andrew Lhor Thanks for the answer again! I tried 2 window.opens with 2 different Arriving Airports but it doesn't seem to work (only the first window is opening).
It now looks like this:
function getLink() {
let departingAirport = document.getElementById("dairport").value;
let arrivingAirport = document.getElementById("aairport").value;
let arrivingAirport2 = document.getElementById("aairport2").value;
let classSeat = document.getElementById("class").value;
let departingDate = document.getElementById("ddate").value;
let arrivingDate = document.getElementById("adate").value;
window.open(`https://www.skyscanner.nl/transport/flights/${departingAirport}/${arrivingAirport}/${departingDate}/${arrivingDate}/?adults=1&adultsv2=1&cabinclass=${classSeat}&children=0&childrenv2=&destinationentityid=27537542&inboundaltsenabled=false&infants=0&originentityid=27536561&outboundaltsenabled=false&preferdirects=false&preferflexible=false&ref=home&rtn=1`);
window.open(`https://www.skyscanner.nl/transport/flights/${departingAirport}/${arrivingAirport2}/${departingDate}/${arrivingDate}/?adults=1&adultsv2=1&cabinclass=${classSeat}&children=0&childrenv2=&destinationentityid=27537542&inboundaltsenabled=false&infants=0&originentityid=27536561&outboundaltsenabled=false&preferdirects=false&preferflexible=false&ref=home&rtn=1`);
}
And this:
<label for="dairport">Departing Airport:</label><br>
<input type="text" id="dairport" name="dairport"><br>
<label for="aairport">Arriving Airport:</label><br>
<input type="text" id="aairport" name="aairport"><br>
<label for="aairport2">Arriving Airport2:</label><br>
<input type="text" id="aairport2" name="aairport2"><br>
<label for="ddate">Departing Date:</label><br>
<input type="text" id="ddate" name="ddate"><br>
<label for="adate">Arriving Date:</label><br>
<input type="text" id="adate" name="adate"><br>
<label for="class">Class:</label><br>
<select id="class" name="class"><br>
<option value="business">Business</option>
<option value="first">First</option>
</select><br>
<button onclick="getLink();">Launch</button>
I'm working on a project, and for testing it I need to fill in a large amount of 'input' elements every time when reloading the page. I'm filling in the same numbers every time, so I need 'input' elements to somehow 'remember' the value they were given.
I've seen an example with 'autocomplete' attribute, but then I have to choose the value from a drop box for each input element, so that won't help me.
Is there any way I can code the input tag with pre-written data? Or maybe using javascript?
With jQuery, you can write a plugin to set the input of fields based on data.
You can do the same without jQuery, but you need to find all inputs, textareas, selects, etc. and filter the other junk out of the form before setting values.
Check out this question for more tips: Using jQuery and JSON to populate forms?
(function($) {
$.fn.populateData = function(data) {
var $form = this;
$.each(data, function(key, value) {
$('[name=' + key + ']', $form).val(value);
});
}
})(jQuery);
var pocForm = document.forms['poc-form'];
var pocFormData = {
fname : 'John',
lname : 'Doe',
dob : '1970-12-25'
};
$(pocForm).populateData(pocFormData);
.form-field {
margin-bottom: 0.25em;
}
.form-field label {
display: inline-block;
width: 6em;
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="poc-form">
<div class="form-field">
<label for="poc-fname">First Name:</label>
<input type="text" id="poc-fname" name="fname" />
</div>
<div class="form-field">
<label for="poc-lname">Last Name:</label>
<input type="text" id="poc-lname" name="lname" />
</div>
<div class="form-field">
<label for="poc-dob">Date of Birth:</label>
<input type="date" id="poc-dob" name="dob" />
</div>
</form>
here the unput value
<form >
First name: <input type="text" name="fname" value="John"><br>
Last name: <input type="text" name="lname" value="Doe"><br>
</form>
In your input you can use the value tag and set the default value.
<input type="text" name="example" value="Value Goes Here">
You can more or less tell autocomplete how to work: https://html.spec.whatwg.org/multipage/forms.html#autofill
But it still leaves it up to the browser.
A better option is datelist, giving you a text-input with predefined options for autocomplete and an dropdown-menu.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist
<label>Choose a browser from this list:
<input list="browsers" name="myBrowser" />
</label>
<datalist id="browsers">
<option value="Chrome">
<option value="Firefox">
<option value="Internet Explorer">
<option value="Opera">
<option value="Safari">
<option value="Microsoft Edge">
</datalist>
EDIT:
After reading your question again, I realized that this isn't very good for your use-case. Sorry.
In that case I'd just go with a single line of jQuery:
$('input[type="text"]').val('Hello world') ;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="t1" />
<input type="text" name="t2" />
<input type="text" name="t3" />
<input type="text" name="t4" />
<input type="text" name="t5" />
<input type="text" name="t6" />
<input type="text" name="t7" />
with Javascript, you can use static text in strings:
var mystring = "This is my string of text";
var anotherString = "A second string of text";
var myInputs = document.getElementsByTagName("input");
myInputs[0].value = mystring;
myInputs[1].value = anotherString;
If you need the text to be from user entered data, you need to first save the text:
tx = myInputs[0].value
localStorage.setItem("item_name", tx);
//note: you would need to use a keyup event or button to save the data as the user types or clicks the button. Also look in to JSON "stringify" and "parse" to save more complex items.
After you have saved the data you wished, call it and point it to the input you wish.
var savedTx = localStorage.getItem("item_name");
if (savedTx) {//it's important to look for the data first to avoid errors
myInputs[0].value = "My data: " + savedTx + "!";
}
A form that insert data into mysql but before inserting data I wanted to write a JavaScript that will validate the form before submit but can let it work. In the HTML I have added required and pattern attribute for the input to validate the form data and to check whether user fill the required fields but i also want to add a script that will also validate the form and show the a message in the tag with id errorMessage but it doesn't seem to work.
var inputFields = document.theForm.getElementsByTagName("input");
for (key in inputFields) {
var myField = inputFields[key];
var myError = document.getElementById('errorMessage');
myField.onchange = function() {
var myPattern = this.pattern;
var myPlaceholder = this.placeholder;
var isValid = this.value.search(myPattern) >= 0;
if (!(isValid)) {
myError.innerHTML = "Input does not match expected pattern. " + myPlaceholder;
} else { //pattern not valid
myError.innerHTML = "";
} //pattern is valid
} // myField has changed
} // inputFields
<form id="createForm" name="theForm" method="post" action="createUser.php">
<legend><span class="icon"><img src="/registerUser/img/createIcon.png"></span> Create New User</legend>
<p><span id="requiredfields">* required field.</span>
</p>
<span id="formMessage" class="message"> </span>
<span id="errorMessage"> </span>
<input id="fname" type="text" name="fname" placeholder="Name *" pattern="[A-Za-z ]+" required>
<br>
<br>
<input id="email" type="email" name="email" placeholder="Email *" required>
<br>
<br>
<input id="username" type="text" name="username" placeholder="Username *" required>
<br>
<br>
<input id="password" type="password" name="password" placeholder="Password *" required>
<br>
<br>
<label for="roles">Roles:</label>
<select id="role" name="roles">
<option>Select Role</option>
<option value="empty"></option>
<option value="Reporter">Reporter</option>
<option value="Lover">Lover</option>
<option value="Other">Other</option>
</select>
<br>
<br>
<input id="create" type="submit" name="createUser" value="Create User">
</form>
When you specify an input element validation pattern as an html5 attribute like this:
pattern="[A-Za-z ]+"
...the browser checks that the whole input value matches the pattern. In other words, your pattern is treated like ^[A-Za-z ]+$ even though the ^ and $ are not explicitly in the pattern.
But in your JavaScript code when you use the pattern like this:
var myPattern = this.pattern; // get pattern from element
var isValid = this.value.search(myPattern) >= 0;
...the .search() method doesn't try to match the whole string, it returns the index of the first pattern match within the string. Which means that, e.g., in the case of your Name field your JS will consider it valid as long as at least one character matches the pattern, even if other characters don't.
The simplest way to work around this is to update your pattern:
pattern="^[A-Za-z ]+$"
Or you could update your JS something to be something like the following:
var isValid = !myPattern || this.value.search("^" + myPattern + "$") >= 0;
That is, put ^ and $ around the pattern to force JS to match the whole string against the pattern, but only do the test if a non-blank pattern was specified for the field (some of your fields don't have a pattern).
Anytime a person gets executed, I notify the Judge who put him away.
Recently, we have found there is a problem with people putting down the wrong Executioner. This would not normally be a big deal, but there are some bosses with big families that can make life difficult for the person that performed the execution.
So, the form now needs to be modified to also include an email to the Executioner.
Here are the basics of the webpage:
<form method="post">
Person Executed:
<input type="text" name="_jp2code_killed" value="" size="30" />
<br />
<input type="hidden" name="_jp2code_name_original_value" id="_jp2code_name_original_value" value="Web Master" />
<input type="hidden" name="_jp2code_mail_original_value" id="_jp2code_mail_original_value" value="no-reply#jp2code.net" /><br />
Judge:
<select name="Judge" id="Judge">
<option value="Neal Barton" _jp2code_judge="NBarton#ketknbc.com">Neal Barton</option>
<option value="Howard Pain" _jp2code_judge="hpain#courtcircuit1.us">Howard Pain</option>
</select>
Executioner:
<select name="Executioner" id="Executioner">
<option value="Joe Byrd" _jp2code_executioner="jbyrd#walls.tx.us">Joe Byrd</option>
<option value="Jim Estelle" _jp2code_executioner="jestelle#tdcj.org">Jim Estelle</option>
</select>
<br />
<input type="submit" value="Submit" />
<br />
debug:
<input type="text" name="_jp2code_debug" id="_jp2code_debug" size="30" /><br />
</form>
With those definitions in place, here is the jQuery (v1.7) that I am trying to get to work:
$(function () {
// Save references to elements
var objName = $('#_jp2code_name_original_value');
if (!objName.attr('_jp2code_custom_parameter') ||
($.trim(objName.attr('_jp2code_custom_parameter')) == '')) {
objName.attr('_jp2code_custom_parameter', objName.val());
}
var objEmail = $('#_jp2code_mail_original_value');
if (!objEmail.attr('_jp2code_custom_parameter') ||
($.trim(objEmail.attr('_jp2code_custom_parameter')) == '')) {
objEmail.attr('_jp2code_custom_parameter', objEmail.val());
}
$('#Judge').each(function () {
$(this).change(function () { // Add OnChange EventHandler
var oItem = $(this); // reference to current element
var oName = $('#_jp2code_name_original_value'); // Save references to names
var oEmal = $('#_jp2code_mail_original_value'); // Save references to emails
if ($.trim(oItem.Val()) != '') {
oName.val(oName.attr('_jp2code_mail_original_value') + ',Judge');
oEmal.val(oEmal.attr('_jp2code_mail_original_value') + ',' + $(this).children(':selected').attr('_jp2code_judge'));
} else {
oName.val(oName.attr('_jp2code_mail_original_value'));
oEmal.val(oEmal.attr('_jp2code_mail_original_value'));
}
$('#_jp2code_debug_name').val(oName.val());
$('#_jp2code_debug_emal').val(oEmal.val());
});
});
});
So, despite my best efforts, a couple of things aren't working:
My debug boxes that should be getting the people's names and email addresses is not working. Those debug boxes should always at least include the Web Master name and email address, then append the person's name and address when they are selected. I can't seem to get past that.
Once that is working, how would I add the logic functioning, then I need to include both names and both email addresses from the select boxes.
Here is where I have been fiddling with this:
http://jsfiddle.net/jp2code/c5Q2V/
I solved it.
JS Fiddle: http://jsfiddle.net/jp2code/wunC2/1/
I added a custom attribute to my elements with "Web Master" or the default email address to the HTML:
<form method="post">
Person Executed: <input type="text" name="_jp2code_killed" value="" size="30"/>
<br/>
<input type="hidden" name="_jp2code_name_original_value" id="_jp2code_name_original_value" _jp2code_name_original_value="Web Master" />
<input type="hidden" name="_jp2code_mail_original_value" id="_jp2code_mail_original_value" _jp2code_mail_original_value="norsvp#mail.com" /><br/>
Judge:
<select name="Judge" id="Judge">
<option value="First1 Judge1" _jp2code_judge="judge1#mail.com">First1 Judge1</option>
<option value="First2 Judge2" _jp2code_judge="judge2#mail.com">First2 Judge2</option>
</select>
Executioner:
<select name="Executioner" id="Executioner">
<option value="First1 Exec1" _jp2code_executioner="exec1#mail.com">First1 Exec1</option>
<option value="First2 Exec2" _jp2code_executioner="exec2#mail.com">First2 Exec2</option>
</select>
<br/>
<input type="submit" value="Submit" />
<br/>
debug: <input type="text" name="_jp2code_debug_name" id="_jp2code_debug_name" size="50" /><br/>
debug: <input type="text" name="_jp2code_debug_emal" id="_jp2code_debug_emal" size="50" /><br/>
</form>
For the jQuery, I trimmed it down to a function that was passed to both Select controls, and I had to call the function once so the data would be pre-populated:
$(function() {
function jp2code_get_data() {
var obj1 = $('#_jp2code_name_original_value');
var val1 = obj1.attr('_jp2code_name_original_value');
val1 += ','+$('#Judge').children(':selected').val();
val1 += ','+$('#Executioner').children(':selected').val();
var obj2 = $('#_jp2code_mail_original_value');
var val2 = obj2.attr('_jp2code_mail_original_value');
val2 += ','+$('#Judge').children(':selected').attr('_jp2code_judge');
val2 += ','+$('#Executioner').children(':selected').attr('_jp2code_executioner');
obj1.val(val1);
obj2.val(val2);
$('#_jp2code_debug_name').val(obj1.val());
$('#_jp2code_debug_emal').val(obj2.val());
}
$('#Judge, #Executioner').each(function () {
$(this).change(jp2code_get_data);
});
jp2code_get_data();
});
This is probably not helpful to everyone, but I like to post the solution if others have the same problem.