Script validation required on data list option - javascript

<form action="order.php" method="post" name="myForm" id="dropdown" onsubmit="return(validate());">
<input list="From" name="From" autocomplete="off" type="text" placeholder="From Place">
<datalist id="From">
<option value="Stand">
<option value="Hospital">
</datalist>
</form>
Script Validation :
<script>
if (document.myForm.From.value == "") {
alert("Please select From Place.!");
return false;
}
</script>
If null then given me the error message :
Please select From Place.!
User's input is also printing... But i need Option Value to print only ie. "Stand","Hospital"...
I have also deleted type="text" but it didn't change anything.

You need to loop inside your datalist options when submiting :
HTML
<form>
<input list="datalist" id="input">
<datalist id="datalist">
<option value="Internet Explorer">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
</form>
<button onclick="myFunction()">Check</button>
<p id="result"></p>
JS
function myFunction() {
var options = document.getElementById("datalist").options;
var result = false;
for (var i = 0; i < options.length; i++) {
if(document.getElementById("input").value == options[i].value) {
result = true;
}
}
document.getElementById("result").innerHTML = "Validate : " + result + ".";
}
Then you can use the Boolean for your validation.
You can see the result on this fiddle.

Related

How to validate the select method with submit type?

I want to validate the select method with submit type button. I have created a form and under that, I have created the select method and given some options. By submit type, the onClick should validate my submit type with the options in the select method. How can I assign the value of option
to var t based on select?
According to the select option my var t should be changed.
If the value is volvo then it should print val11, similarly Saab= val14, opel= val82, Audi= val34
<select name="carlist" class="temp>
<option value="10">Volvo</option>
<option value="20">Saab</option>
<option value="30">Opel</option>
<option value="45">Audi</option>
</select>
<input type="submit" class="temp" value="submit the answer">
<script>
var t;
if () {
t=value;
} else if () {
t=value;
} else if () {
t=value;
}else {
t=value;
}
</script>
You can call a function on clicking the button. Inside the function get the text of the selected option:
function getValue(){
var el = document.querySelector('.temp');
var val = el.options[el.selectedIndex].text;
var t;
if(val == "Volvo")
t = 'val11';
else if(val == "Saab")
t = 'val14';
if(val == "Opel")
t = 'val82';
else if(val == "Audi")
t = 'val34';
alert(t);
}
<form>
<select name="carlist" class="temp">
<option value="10">Volvo</option>
<option value="20">Saab</option>
<option value="30">Opel</option>
<option value="45">Audi</option>
</select>
<input onclick="getValue()" type="submit" class="temp" value="submit the answer">
</form>
You can also think of using data attribute which is more cleaner and simpler:
function getValue(){
var el = document.querySelector('.temp');
var t = el.options[el.selectedIndex].getAttribute('data-val');
alert(t);
}
<form>
<select name="carlist" class="temp">
<option value="10" data-val="val11">Volvo</option>
<option value="20" data-val="val14">Saab</option>
<option value="30" data-val="val82">Opel</option>
<option value="45" data-val="val34">Audi</option>
</select>
<input onclick="getValue()" type="submit" class="temp" value="submit the answer">
</form>
You can do a few things, here's the simplest I could get away with.
function submitForm() {
const value = document.querySelector('[name="carlist"').value;
console.log(value);
return false; // to prevent it navigating away.
}
<form onsubmit="submitForm()">
<select name="carlist" class="temp">
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Opel</option>
<option value="4">Audi</option>
</select>
<input type="submit" class="temp" value="submit the answer">
You can also have some validation running earlier, e.g. on change:
/**
* This function runs on form submit.
*/
function submitForm(event) {
const value = document.querySelector('[name="carlist"').value;
console.log(value);
// to prevent it navigating away.
event.preventDefault();
return false;
}
/**
* This function runs on selection change
*/
function validateCar(changeEvent) {
console.log('Change');
// do something with changeEvent
}
<form onsubmit="submitForm(event)">
<select name="carlist" class="temp" onchange="validateCar(event)">
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Opel</option>
<option value="4">Audi</option>
</select>
<input type="submit" class="temp" value="submit the answer">
You can set an id attribute on the select element and then access it through a querySelector or getElementById.
<form id="carForm">
<select name="carlist" class="temp" id="car">
<option value="val11">Volvo</option>
<option value="val14">Saab</option>
<option value="val82">Opel</option>
<option value="val34">Audi</option>
</select>
</form>
let carForm = document.getElementById('carForm');
carForm.onsubmit = function(event) {
var t = document.getElementById('car');
...
}
See codepen example

Adding Comma To Javascript Output

I'm trying to run a function that will add commas to the results of a form that multiplies the values of two drop down boxes.
The function I have works on an html element such as p class="points" but it is not working on the output generated by id="results2"
Any idea what I'm doing wrong?
<form name="myForm" id="myForm">
<label>Select Amount</label>
<select id="box1" type="select" oninput="calculate()" />
<option value="choose" selected>Choose</option>
<option value="15000">$15,000</option>
<option value="20000">$20,000</option>
<option value="25000">$25,000</option>
<option value="30000">$30,000</option>
<option value="35000">$35,000</option>
</select>
<label>Select Type</label>
<select id="box2" type="select" oninput="calculate()" />
<option value="x" selected>Choose</option>
<option value=".21">1</option>
<option value=".40">2</option>
</select>
<input class="button" type="submit" value="Submit" id="multiply">
<p>
<strong>here are the results:</strong>
</p>
<h3>
<strong>$<span id="result2"></span></strong> a week
</h3>
</form>
<script>
$(document).ready(function(){
$('#multiply').click(function(event){
event.preventDefault();
var n1=$('#box1').val();
var n2=$('#box2').val();
var result=Math.round(n1*n2*25);
$('#resultholder4').fadeIn(200);
$('#number1').append(n1);
$('#number2').append(n2);
$('#result2').text(result);
});
});
</script>
<script type="text/javascript">
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");
}
$('.points').each(function() {
var v_pound = $(this).html();
v_pound = numberWithCommas(v_pound);
$(this).html(v_pound)
})
</script>
You are just not calling numberWithCommas() on your result. Here is your code with one change (and I had to add the calculate function that is referenced by the select's oninput).
$(document).ready(function() {
$('#multiply').click(function(event) {
event.preventDefault();
var n1=$('#box1').val();
var n2=$('#box2').val();
var result=Math.round(n1*n2*25);
$('#resultholder4').fadeIn(200);
$('#number1').append(n1);
$('#number2').append(n2);
// added call to numberWithCommas, line had been:
//$('#result2').text(result);
// changed to:
$('#result2').text(numberWithCommas(result)); // <--------
});
});
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");
}
$('.points').each(function() {
var v_pound = $(this).html();
v_pound = numberWithCommas(v_pound);
$(this).html(v_pound)
});
function calculate() {
// ?
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="myForm" id="myForm">
<label>Select Amount</label>
<select id="box1" type="select" oninput="calculate()" />
<option value="choose" selected>Choose</option>
<option value="15000">$15,000</option>
<option value="20000">$20,000</option>
<option value="25000">$25,000</option>
<option value="30000">$30,000</option>
<option value="35000">$35,000</option>
</select>
<label>Select Type</label>
<select id="box2" type="select" oninput="calculate()" />
<option value="x" selected>Choose</option>
<option value=".21">1</option>
<option value=".40">2</option>
</select>
<input class="button" type="submit" value="Submit" id="multiply">
<p>
<strong>here are the results:</strong>
</p>
<h3>
<strong>$<span id="result2"></span></strong> a week
</h3>
</form>
Here is a quick dirty method:
function numberWithCommas(x) {
x = x.toString();
var pattern = /(-?\d+)(\d{3})/;
while (pattern.test(x))
x = x.replace(pattern, "$1,$2");
return x;
}
should add that this was provided by Peter Mortensen:
How to print a number with commas as thousands separators in JavaScript
here is a demo:
https://jsfiddle.net/keinchy/dx7qg4nk/1/
-cheers
Your event handler for #multiply never actually calls numberWithCommas. Replace
$('#result2').text(result);
with
$('#result2').text(numberWithCommas(result));
and it should work.

How to display multiple selected value in a box?

I am making a form where when I select familyname of the product, its values will be display in a box (I don't know what I should use todisplay it) and the box can't be edited (only can be read).
-HTML
<select name="fnme" onchange="setText(this)" multiple>
<option value="STR12(12,YU,IO)">STR12(12,YU,IO)</option>
<option value="STR13(13,YU,IO)">STR12(13,YU,IO)</option>
<option value="STR14(14,YU,IO)">STR12(14,YU,IO)</option>
<option value="STR15(15,YU,IO)">STR12(15,YU,IO)</option>
</select>
<td><textarea rows="10" cols="30" name="textBox" id="disabled" value=""/ disabled></textarea></td>
</br>
<p><input type="submit" value="Save"></p>
-ASPCode
<%
DIM fnm,element
fnm=Split(Request("fnme"),"\n")
FOR EACH element IN fnm
Response.Write("<p>--qq-- " & trim(element) & " </p>")
Next
%>
For now I'm using text area but still have a problem in displaying many value, it display on one selected value.
-JS
<script>
function setText(obj) {
var val = obj.value;
document.getElementById('textBox').value = val;
}
</script>
I want to know it is possible to display the multiple value?
When you do:
var val = obj.value;
you're only going to get the value of the first selected option, not all of them (unless you're using something like jQuery).
And the forward slash in:
<textarea ... id="disabled" value=""/ disabled>
doesn't help either. I'll assume that's just a posting typo.
function getMultiSelectValue(select) {
return [].reduce.call(select.options, function(values, option) {
option.selected? values.push(option.value) : null;
return values;
}, []);
}
function showValues(values){
document.getElementById('ta').value = values.join('\n');
}
<select onchange="showValues(getMultiSelectValue(this))" multiple>
<option value="0">0
<option value="1">1
<option value="2">2
</select>
<textarea id="ta" rows="3" readonly></textarea>
I think this could help you.
<html>
<body>
<form action="" name="tof">
<select name="fnme" onchange="setText(this)" multiple>
<option value="STR12(12,YU,IO)">STR12(12,YU,IO)</option>
<option value="STR13(13,YU,IO)">STR12(13,YU,IO)</option>
<option value="STR14(14,YU,IO)">STR12(14,YU,IO)</option>
<option value="STR15(15,YU,IO)">STR12(15,YU,IO)</option>
</select>
<textarea id="res" readOnly></textarea>
</form>
<p id="demo"></p>
<script>
function setText(ob){
var selected_options = document.forms['tof']['fnme'].selectedOptions
var selected_options_values = []
for(i=0; i<selected_options.length; i++){
selected_options_values.push(selected_options[i].value)
}
document.getElementById('res').value = selected_options_values.join('\n')
}
</script>
</body>
</html>

how to get multiple inputs spontaneously in JavaScript

I am new to JavaScript and I am trying to make an html page with JavaScript inside it.
The idea is that, when someone selects the value of option from the select, it should generate automatically the fields of firstName, lastName etc depending on the number which is selected. If one is selected then it should have one field of firstName, lastName and if two is selected then it should generate two fields dynamically.
<select id="noOfAuthor" multiple="multiple">
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
<option value="four">4</option>
<option value="five">5</option>
</select>
If someone selects one then below there should be one code of
Title Name <input type="text" name="txtTitle1">
Author Name <input type="text" name="txtAuthor1" >
Copy right<input type="text" name="txtCopyrightYear1">
If we selects “2” then there should be two code asking
Title Name <input type="text" name="txtTitle1">
Author Name <input type="text" name="txtAuthor1" >
Copy right<input type="text" name="txtCopyrightYear1">
Title Name <input type="text" name="txtTitle2">
Author Name <input type="text" name="txtAuthor2" >
Copy right<input type="text" name="txtCopyrightYear2">
And so on and so forth.
I tried to write a code for doing this, but it is not working.
<html>
<head>
<title>Book Collection</title>
<script language="JavaScript">
function WBook(bookName, writer, yearPublished)
{
this.Title = bookName;
this.Author = writer;
this.CopyrightYear = yearPublished;
}
function showBook(oneBook)
{
var no = showChoices();
var i ;
for(i =0; i<no; i++)
{
document.frmBooks.txtTitle[i].value = oneBook.Title[i];
document.frmBooks.txtAuthor[i].value = oneBook.Author[i];
document.frmBooks.txtCopyrightYear[i].value = oneBook.CopyrightYear[i];
}
}
function displayCollection()
{
var aBook = new WBook("Visual C++ From the Ground Up", "John Paul Mueller", 1998);
showBook(aBook);
}
function showChoices(){
var noOfAuthor = document.getElementById("noOfAuthor");
var result = " You selected";
result += " \n";
for(i=0; i<noOfAuthor.length;i++){
currentOption = noOfAuthor[i];
if(currentOption.selected == true){
result += currentOption.value + "\n";
}
}
result += " \n";
alert(result);
return(result);
}
</Script>
</head>
<body>
<h1>Book Collection</h1>
<form name="frmBooks">
<input type="hidden" name="id" value="" required="true" /><br> <br>
<select id="noOfAuthor" >
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
<option value="four">4</option>
<option value="five">5</option>
</select>
<button type="button" onclick="showChoices()">Submit</button>
Title Name <input type="text" name="txtTitle1">
Author Name <input type="text" name="txtAuthor1" >
Copy right<input type="text" name="txtCopyrightYear1">
Title Name <input type="text" name="txtTitle2">
Author Name <input type="text" name="txtAuthor2" >
Copy right<input type="text" name="txtCopyrightYear2">
<p><input type="button" value="Show Collection" name="btnShow" onClick="displayCollection()">
</form>
</body>
</html>
You can solve it like this (jsFiddle demo):
<html>
<head>
<title>Book Collection</title>
<script language="JavaScript">
function WBook(bookName, writer, yearPublished)
{
this.Title = bookName;
this.Author = writer;
this.CopyrightYear = yearPublished;
}
function showBook(oneBook)
{
var no = showChoices();
var i ;
for(i =0; i<no; i++)
{
document.frmBooks.txtTitle[i].value = oneBook.Title[i];
document.frmBooks.txtAuthor[i].value = oneBook.Author[i];
document.frmBooks.txtCopyrightYear[i].value = oneBook.CopyrightYear[i];
}
}
function displayCollection()
{
var aBook = new WBook("Visual C++ From the Ground Up", "John Paul Mueller", 1998);
showBook(aBook);
}
function showChoices(){
var noOfAuthor = document.getElementById("noOfAuthor");
var result = " You selected";
result += " \n";
result += noOfAuthor.value
for(i=1; i <= noOfAuthor.length;i++){
if(i <= noOfAuthor.value){
document.getElementById("inputs" + i).style.display = 'block';
} else {
document.getElementById("inputs" + i).style.display = 'none';
}
}
result += " \n";
alert(result);
return(result);
}
</Script>
</head>
<body>
<h1>Book Collection</h1>
<form name="frmBooks">
<input type="hidden" name="id" value="" required="true" /><br> <br>
<select id="noOfAuthor" >
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<button type="button" onclick="showChoices()">Submit</button>
<div id="inputs1">
Title Name <input type="text" name="txtTitle1">
Author Name <input type="text" name="txtAuthor1" >
Copy right<input type="text" name="txtCopyrightYear1">
</div>
<div id="inputs2" style="display:none">
Title Name <input type="text" name="txtTitle2">
Author Name <input type="text" name="txtAuthor2" >
Copy right<input type="text" name="txtCopyrightYear2">
</div>
<div id="inputs3" style="display:none">
Title Name <input type="text" name="txtTitle3">
Author Name <input type="text" name="txtAuthor3" >
Copy right<input type="text" name="txtCopyrightYear3">
</div>
<div id="inputs4" style="display:none">
Title Name <input type="text" name="txtTitle4">
Author Name <input type="text" name="txtAuthor4" >
Copy right<input type="text" name="txtCopyrightYear4">
</div>
<div id="inputs5" style="display:none">
Title Name <input type="text" name="txtTitle5">
Author Name <input type="text" name="txtAuthor5" >
Copy right<input type="text" name="txtCopyrightYear5">
</div>
<p><input type="button" value="Show Collection" name="btnShow" onClick="displayCollection()">
</form>
</body>
</html>
very simple with jquery:
<select id="noOfAuthor" multiple="multiple">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<div id="inputs"></div>
$( document ).ready(function() {
$("select#noOfAuthor > option").click(function() {
$( "#noOfAuthor" ).attr("disabled", true);
var howMuch = parseInt($( "#noOfAuthor" ).val());
for(i = 0; i < howMuch; i++) {
$( "#inputs" ).append('Title Name: <input type="text" name="txtTitle' + i + '"><br>Author Name: <input type="text" name="txtAuthor' + i + '"><br>Copy right: <input type="text" name="txtCopyrightYear' + i + '"><br><hr />');
}
});
});
So you get inputs as the selected number.
the Three first willl be:
name="txtTitle0"
name="txtAuthor0"
name="txtCopyrightYear0"
demo: http://jsfiddle.net/mxgbc/3/
I would generate the inputs and labels dynamically. This is a pure javascript example, without using jQuery. I can provide a jQuery solution if you need it.
Example http://jsfiddle.net/A62qA/1 // basic select menu
Example http://jsfiddle.net/A62qA/2/ // mutiple choice select menu
HTML
<select id="noOfAuthor" onchange="inputFunction(this)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<div id="myContainer"></div>
JavaScript
function createInputs(i) {
var myContainer = document.getElementById("myContainer");
var titleName = document.createElement("input");
titleName.setAttribute('name', 'txtTitle1' + i);
var label = document.createElement("Label");
label.innerHTML = "Title Name";
myContainer.appendChild(label);
myContainer.appendChild(titleName);
var authorName = document.createElement("input");
authorName.setAttribute('name', 'txtAuthor1' + i);
var label = document.createElement("Label");
label.innerHTML = "Author Name";
myContainer.appendChild(label);
myContainer.appendChild(authorName);
var copyRight = document.createElement("input");
copyRight.setAttribute('name', 'txtCopyrightYear1' + i);
var label = document.createElement("Label");
label.innerHTML = "CopyRight";
myContainer.appendChild(label);
myContainer.appendChild(copyRight);
}
function inputFunction(y) {
var y = y.value;
var myContainer = document.getElementById("myContainer");
for (var i = 0; i < y; i++) {
createInputs(i);
}
}

validation for select option not working

I doing a form for a small project, and having a trouble trying to validate the select option
hope someone can help
THanks in advance
HTML:
<form method="post" name="vehicleform" action=" " onSubmit="return (validateForm())">
First Name: <input type="text" name="fname"><br>
Last Name: <input type="text" name="lname"><br>
Phone Number <font size="1px">(ex. 123-456-7890)</font>: <input type="text" name="phonenumber"><br>
Location
<select name="location">
<option value="-1">Select one..</option>
<option value="lota">Lot A</option>
<option value="lotb">Lot B</option>
<option value="lotc">Lot C</option>
</select><br>
JS:
function validateForm(){
var d = document.forms['vehicleform']['location'].value;
if( document.vehicleform.location.value == "-1" )
{
alert("Please select your location");
return false;
}
}
There is no need for grouping in the listener, and passing this gives immediate access to the form:
<form ... onsubmit="return validateForm(this)">
You only need to check the selected index to see if something other than the first option (or no option all) is selected:
function validateForm(form) {
if (form.location.selectedIndex < 1) {
alert("Please select your location");
return false;
}
}
And as suggested in the comments, make the first option selected by default:
<select name="location">
<option value="-1" selected>Select one..
<option value="lota">Lot A
as browsers may not make any option selected by default and users won't see "Select one...". That should be a label anyway to assist with accessiblity.
http://jsfiddle.net/LVBSZ/1/
You have no submit button in your code and close tag for form. The other works for me
<script>
function validateForm() {
if (document.forms['vehicleform'].location.value == "-1") {
alert("Please select your location");
return false;
}
}
</script>
<form method="post" name="vehicleform" onSubmit="return validateForm()">
First Name:
<input type="text" name="fname">
<br>Last Name:
<input type="text" name="lname">
<br>Phone Number <font size="1px">(ex. 123-456-7890)</font>:
<input type="text" name="phonenumber">
<br>Location
<select name="location">
<option value="-1">Select one..</option>
<option value="lota">Lot A</option>
<option value="lotb">Lot B</option>
<option value="lotc">Lot C</option>
</select>
<br>
<input type="submit" value="Submit">
</form>

Categories