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.
Related
So I have an hidden field, which I want to fill with multiple other input values, when I click on the submit button of an form.
So I use the event.preventDefault(); and then fill the field using JS and afterwards submit the form.
But when I check the returned value in the database I have an empty string instead of the filled values.
What am I doing wrong and how do i have to fix my code?
This is the whole JS file for that functionality:
if (getHiddenLicenseField() != undefined) {
$('.buybox--button').click(function(event){
event.preventDefault();
fillHiddenLicensePlateField();
$(this).closest('form').submit();
});
}
function getHiddenLicenseField() {
return $('.personalizeAttr')[0];
}
function getLicencePlateInputList() {
return $('.custom-input-inner')[0].getElementsByTagName('input');
}
function fillHiddenLicensePlateField() {
let hiddenCustomField = getHiddenLicenseField();
for (let input of getLicencePlateInputList()) {
hiddenCustomField.value += input.value;
}
}
HTML
Field where the user inputs the data:
Hidden Field, where the input of the user gets inserted to:
<input class="personalizeAttr" type="text" name="sAttr1" data-pers-article="2" value="" placeholder="">
Form:
<form name="sAddToBasket" method="post" action="https://www.123autokennzeichen.de/checkout/addArticle" class="buybox--form" data-add-article="true" data-eventname="submit"> <input type="hidden" name="sActionIdentifier" value=""> <input type="hidden" name="sAddAccessories" id="sAddAccessories" value=""> <input type="hidden" name="sAdd" value="123ak10002"> <input style="display:none" class="personalizeBuyAttr personalize_sAttr1" type="text" name="sAttr1" value="" placeholder="sAttr1">
<div class="buybox--button-container block-group">
<div class="buybox--quantity block">
<div class="js--fancy-select select-field quantity--select">
<select id="sQuantity" name="sQuantity" class="quantity--select">
<option value="1" test="">1</option>
...
<option value="100" test="">100</option>
</select>
</div>
</div>
<button class="buybox--button block btn is--primary is--icon-right is--center is--large" name="In den Warenkorb">
<span class="buy-btn--cart-add">In den</span> <span class="buy-btn--cart-text">Warenkorb</span> <i class="icon--arrow-right"></i>
</button>
</div>
<input type="hidden" name="__csrf_token" value="A14oWCR0O16TU8TmYucIFTdnN8Vz3j">
</form>
Page: https://www.123autokennzeichen.de/kfz-kennzeichen/autokennzeichen/euro-kennzeichen-e-kennzeichen-fuer-elektrofahrzeuge-520mm-x-110mm
i am trying to display the name and selected shape elements in the outerText div in html, but they keep showing up as undefined.
here is the Javascript
let ShapeLink = (function(){
//code here!
return {
initForm: function(frm){
//code here!
frm.addEventListener('submit', function(){
document.getElementById('name').name,
document.getElementById('shapeSelect').option;
})
let display = document.getElementById('outputText').innerHTML =
`${this.name} wants to see a ${this.shapeSelect}`;
console.log(display);
display.innerHTML =`
<div id="outputText">
${this.name} wants to see a ${this.shapeSelect}
</div>`
}
}
})()
and here is the html
<body>
<form>
<label for="name">Name:</label>
<input type="text" id="name">
<label for="shapeSelect">Shape:</label>
<select name="" id="shapeSelect">
<option value="">pick a shape</option>
<option value="square">Square</option>
<option value="circle">Circle</option>
</select>
<input type="submit" value="Submit">
</form>
<div id="outputText"></div>
<svg width=100 height=100></svg>
<script>
ShapeLink.initForm(document.querySelector("form"));
</script>
</body>
note that i need to add all code into the Javascript file
You should keep all your JavaScript together, and there is no need to make your main function global. Beyond that, relying on this can get you into a world of hurt. Since you already have access to the form via frm, you may as well just access its elements property to get the values from your form:
document.addEventListener('DOMContentLoaded', function() {
const ShapeLink = {
initForm: function(frm) {
frm.addEventListener('submit', function(event) {
event.preventDefault();
event.stopPropagation();
let display = document.getElementById('outputText');
display.innerHTML = `
<div id="outputText">
${frm.elements.name.value} wants to see a ${frm.elements.shapeSelect.value}
</div>
`;
});
},
};
ShapeLink.initForm(document.querySelector('form'));
});
<form>
<label for="name">Name:</label>
<input type="text" id="name">
<label for="shapeSelect">Shape:</label>
<select name="" id="shapeSelect">
<option value="">pick a shape</option>
<option value="square">Square</option>
<option value="circle">Circle</option>
</select>
<input type="submit" value="Submit">
</form>
<div id="outputText"></div>
<svg width=100 height=100></svg>
Replace this inside the template literals with a variable value.Here this will point to the form.Also document.getElementById('name').name, will give the name but you may need the value of the input & document.getElementById('shapeSelect').option; need to be replaced by the
document.getElementById('shapeSelect').value;
The form have a submit button, so on click of it it will try to submit the form. The default behaviour of the form can be prevented using the event.preventDefault
let ShapeLink = (function() {
var _name;
var _selOption;
return {
initForm: function(frm) {
frm.addEventListener('submit', function(e) {
e.preventDefault();
// get the value attribute
_name = document.getElementById('name').value;
_selOption = document.getElementById('shapeSelect').value;
//check if name and selected option is not undefined
if (_name && _selOption) {
document.getElementById('outputText').innerHTML = `${_name} wants to see a ${_selOption}`;
}
})
}
}
}())
ShapeLink.initForm(document.querySelector("form"));
ShapeLink.initForm(document.querySelector("form"));
<form>
<label for="name">Name:</label>
<input type="text" id="name">
<label for="shapeSelect">Shape:</label>
<select name="" id="shapeSelect">
<option value="">pick a shape</option>
<option value="square">Square</option>
<option value="circle">Circle</option>
</select>
<input type="submit" value="Submit">
</form>
<div id="outputText"></div>
<svg width=100 height=100></svg>
I was trying to send form data from one webpage to another using this:
Passing data from one web page to another
I am pasting the javascript code of the function i created:
function store(){
window.localStorage.setItem("name",document.getElementById("name").value);
window.localStorage.setItem("email",document.getElementById("email").value);
window.localStorage.setItem("tele",document.getElementById("tele").value);
window.localStorage.setItem("gender",document.getElementById("gender").value);
window.localStorage.setItem("comment",document.getElementById("comments").value);
window.location.href = "contact.html";
}
But the Problem is that the window.location.href is not working and the webpage is not redirected.
I have seen the console for errors but there aren't any.
Can anyone tell Where is the fault?
EDIT 1:
Validate function:
function validate(){
var comment = document.getElementById("comments").value;
var gender = document.getElementById("gender").value;
var len = comment.length;
if (len > 100)
{
alert("Reduce the length of the comment less than 100 characters");
}
else if (gender == "Select Gender")
{
alert("Please Select a gender");
}
else {
store();
}
}
Form's html:
<form class="form-horizontal" role="form">
Submit Button:
<input type="submit" id="submit" value="Submit" onclick="validate()">
Have a look at this plunker:
https://plnkr.co/edit/P4XqhYciFxZeYlRbWXtd?p=preview
<form class="form-horizontal" role="form">
<textarea rows="4" cols="50" id="comments" placeholder="Enter comments"></textarea>
<br />
<select id="gender">
<option value="Select Gender">Select Gender</option>
<option value="male">male</option>
<option value="female">female</option>
</select>
<br />
<button type="button" id="submit" onclick="validate()">Go</button>
</form>
I have updated the plunker. The page is redirecting and you can see that the values are saved in the local storage. It works fine.
Perhaps you had a problem because of your input submit, I used a button instead.
I have a single form on the page and I have some jQuery to make sure that the inputs have been completed before the submit.
But now I need to have multiple similar forms repeated on the page and I need to change the jQuery to only check the two inputs in the form that the button was clicked and not check any other form on the page.
<div class="offerDate">
<form class="form-inline hidden-phone" action="http://www.treacyswestcounty.com/bookings/" method="get">
<fieldset>
<input type="text" name="from_date" placeholder="dd/mm/yy" id="from_date" class="input-small hasDatepicker">
<input type="text" name="to_date" placeholder="dd/mm/yy" id="to_date" class="input-small hasDatepicker">
<button id="submitDates" class="btn btn-main" type="submit">CHECK NOW</button>
</fieldset>
</form>
</div>
<div class="offerDate">
<form class="form-inline hidden-phone" action="http://www.treacyswestcounty.com/bookings/" method="get">
<fieldset>
<input type="text" name="from_date" placeholder="dd/mm/yy" id="from_date" class="input-small hasDatepicker">
<input type="text" name="to_date" placeholder="dd/mm/yy" id="to_date" class="input-small hasDatepicker">
<button id="submitDates" class="btn btn-main" type="submit">CHECK NOW</button>
</fieldset>
</form>
</div>
The jQuery that I have used previously to check on form using ID
// validate signup form on keyup and submit
jQuery('#submitDates').click(function () {
var found = false;
jQuery("#to_date, #from_date").each(function(i,name){
// Check if field is empty or not
if (!found && jQuery(name).val()=='') {
alert ('Please choose your arrival and departure dates!')
found = true;
} ;
});
return !found;
});
.prev( [selector ] )
Returns: jQuery
Description: Get the immediately preceding sibling of each element in
the set of matched elements, optionally filtered by a selector.
This is quite short and will target any input displayed just before a button :
$("button").prev("input")
jsFiddled here
you can try like this:
CODE
jQuery('.submitDates').click(function () {
var found = false;
jQuery(this).siblings("input").each(function (i, name) {
// Check if field is empty or not
if (!found && jQuery(name).val() == '') {
alert('Please choose your arrival and departure dates!')
found = true;
};
});
return !found;
});
assuming your inputs are siblings for the button. Note I also changed button's id into class.
FIDDLE http://jsfiddle.net/FY9P9/
Closest and Find do it as well, wherever the input are for the button :
HTML:
<form class="form">
<input type="text" class="toDate" />
<input type="text" class="fromDate" />
<div class="button">Click</div>
</form>
<form class="form">
<input type="text" class="toDate" />
<input type="text" class="fromDate" />
<div class="button">Click</div>
</form>
JS:
$(".button").each(function () {
$(this).click(function () {
if (($(this).closest(".form").find(".toDate").val() == "") || ($(this).closest(".form").find(".fromDate").val() == "")) {
alert("Please fill in arrival and departure Date");
}
})
})
http://jsfiddle.net/GuqJF/1/
I am having trouble with some Ajax functionality.
I have a single dropdown that needs to update a record when the option changes. Here is a snippet of the Javascript:
function changeResponsibleParty(selectObj, targetDiv){
var idx = selectObj.selectedIndex;
var which = selectObj.options[idx].value;
target = document.getElementById(targetDiv);
target.value = which;
document.forms["changeResponsibleParty"].submit();
}
And the HTML:
<form name="changeResponsibleParty" action="javascript:changeResponsiblePartyAjax('project_todos');" method="post" style="display:inline;">
<input type="hidden" name="todo_id" id="todo_id_15" value="15" />
<input type="hidden" name="project_id" id="project_id_15" value="2" />
<input type="hidden" name="user_id" id="user_id_15" value="" />
<select name="user_id_pick" id="user_id_pick_15" onchange="changeResponsibleParty(this, 'user_id_15');" style="border:0;">
<option value="0">Anyone</option>
<option value="1" selected="selected">Allen McCabe</option>
<option value="2">Thomas Martinez</option>
</select>
</form>
I am using the function to update a hidden input element because for some reason, the tag was posting 1 regardless of which option I chose (1 is my user_id, which I set as selected if the database record value is 1.
Can anyone see what is wrong here?
You use changeResponsibleParty as name for the form and also as name for the function, which will cause conflicts. Rename one of them.