I have this form:
<form accept-charset="UTF-8" action="type.php" id="form" method="post">
<label id="type" for="type" class="">Type</label>
<select class="" id="Type" name="type">
<option id="a" value="A">Type A</option>
<option id="b" value="B">Type B</option>
<option id="c" value="C">Type C</option>
<option id="d" value="C">Type D</option>
<option id="e" value="C">Type E</option>
</select>
<label for="type_number" class="inner_text">Type Number</label>
<input name="type_number" type="text" class="false" id="type_number">
<input type="submit" value="Confirm">
</form>
What I need to do is to validate the Type Number. Type Number must start with a number that I choose. For Example:
Type A - 1234
Type B - 2234
Type C - 3234
Type D - 4234
Type E - 5234
So Type A must start with 1, Type B with 2 and so on. I need to check only the first number.
I must to mention that I have a similar question here: Redirect to 3 pages depending of selected option with validation , it's not same thing, but is similar, also I don't get a good answer there to figure this out.
I apreciate any and all comments, thank you.
P.S. Please excuse my English.
Check below Code this will help you.
Page Code
<form accept-charset="UTF-8" action="verify.php" id="form" method="post">
<label id="type" for="type" class="">Type</label>
<select class="" id="Type" name="type">
<option id="a" value="1">Type A</option>
<option id="b" value="2">Type B</option>
<option id="c" value="3">Type C</option>
<option id="d" value="4">Type D</option>
<option id="e" value="5">Type E</option>
</select>
<label for="type_number" class="inner_text">Type Number</label>
<input name="type_number" type="text" class="false" id="type_number">
<input type="button" id="Confirm" value="Confirm" >
</form>
Script
document.getElementById('Confirm').onclick = function () {
var letter =document.getElementById("type_number").value.match(document.getElementById("Type").value);
if (letter !== null) {
letter = letter[0].toLowerCase();
this.value = letter + this.value.substring(1);
}
else {
alert('Number is not correct!');
}
}
You can do something like this.
var startNumbers = {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5};
function validate() {
// get type
var type = document.getElementById('type').value;
// get number
var number = document.getElementById('number').value;
// get first digit
while (number > 0) {
nr = number;
number = Math.floor(number / 10);
}
// validate
if (nr != startNumbers[type])
return false;
else
return true;
}
Call validate when you need it (onkeyup, on submit, whatever).
Note... this script was directly written as an answer so it may need a few tweaks.
Related
I'm working on the fv calculator. However, I don't know why my JavaScript code doesn't display the answer of future value after I click the calculate button.
How could I solve this problem?
I will be appreciated if someone could offer me help, thanks.
Below is my HTML and JavaScript code.
<html>
<head>
<title>401K Future Value Calculator</title>
<script type="text/javascript" src="mpg.js"></script>
</head>
<body>
<h2>401K Future Value Calculator</h2>
<form id="calculationForm" >
<label for="periodicPayment">Yearly Investment($): </label>
<select id="yearlyInvest" name="Investment”">
<option value="1000: ">1000</option>
<option value="2000: ">2000</option>
<option value="3000: ">3000</option>
<option value="4000: ">4000</option>
<option value="5000: ">5000</option>
<option value="6000: ">6000</option>
<option value="7000: ">7000</option>
<option value="8000: ">8000</option>
<option value="9000: ">9000</option>
<option value="10000: ">10000</option>
</select><br><br>
<label for="annunalInterest">Annual Interest Rate(%) </label>
<input type="text" id="annunalInterestRate"><br><br>
<label for="years">Number of Years(#) </label>
<input type="text" id="numOfYears"><br><br>
<label for="future">Future Value($) </label>
<p id="futureValue">
</p>
<input type="button" id="calculate" value="Calculate">
<input type="button" onclick="clearButton()" id="clear" value="Clear">
</form>
</body>
</html>
function processForm() {
var r, n, p;
r = parseFloat(document.getElementById("annunalInterestRate").value);
n = parseInt(document.getElementById("numOfYears").value);
p = document.getElementById("yearlyInvest").value;
if (isNaN(r)) {
alert("Pleas enter a valid number.");
} else if (isNaN(n)) {
alert("Pleas enter a valid number.");
} else {
var fv = P * ((Math.pow((1 + r), n) - 1) / r);
}
document.getElementById("calculate").value;
document.getElementById("futureValue").innerHTML = fv.toFixed(2);
};
window.onload = function() {
document.getElementById("calculate").onclick = processForm;
};
function clearButton() {
document.getElementById("calculationForm").reset();
}
The way you've written your <option> nodes in the <select> contain an unnecessary : in the value= param. This is causing p to compute as NaN. Instead, rewrite as:
<select id="yearlyInvest" name="Investment”">
<option value="1000">1000</option>
<option value="2000">2000</option>
...
</select>
My goal here is to be able to add preferences to a form I've made... I've created an array of objects containing the following fields like so...
var preferences =[{
base_field:"field1",
base_value:"1",
preference_type:"change",
target_field:"field2_div legend",
target_value:"New Field 2 Legend"
},
{
base_field:"field1",
base_value:"2",
preference_type:"change",
target_field:"field2_div legend",
target_value:"New Field 2 Legend"
}];
$.each(preferences, function(key, preference){
var baseField = $("#" + preference.base_field);
var baseValue = preference.base_value;
var targetField = $("#" + preference.target_field);
var targetValue = preference.target_value;
if (preference.preference_type == 'change') {
var originalValue = targetField.text();
baseField.change(function(){
if(baseField.val() === baseValue){
targetField.text(targetValue);
}
if(baseField.val() !== baseValue){
targetField.text(originalValue);
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div id="field1_div">
<fieldset>
<legend>Field 1 Legend</legend>
<label for="field1">Field 1</label>
<select id="field1" name="field1">
<option value="" selected>Field 1</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</fieldset>
</div>
<div id="field2_div">
<fieldset>
<legend>Default Field 2 Legend</legend>
<input id="field2" type="text" name="field2">
</fieldset>
</div>
I want the text of '#field2_div legend' to change when the value of #field1 changes to '1' or '2' from 'Default Field 2 Legend' to 'New Field 2 Legend', and then if field1 changes to a value that is not '1' or '2', the text of '#field2_div legend' is restored to 'Default Field 2 Legend'
My problem is only the last change function sticks for when field1 = "2"... I think this is because the change function is getting overwritten. Any ideas on how to rewrite this for a more scalable approach?
Solved it like this... Thanks #ADyson !
var preferences =[{
base_field:"field1",
base_value:["1","2"],
preference_type:"change",
target_field:"field2_div legend",
target_value:"New Field 2 Legend"
}];
$.each(preferences, function(key, preference){
var baseField = $("#" + preference.base_field);
var baseValue = preference.base_value;
var targetField = $("#" + preference.target_field);
var targetValue = preference.target_value;
if (preference.preference_type == 'change') {
var originalValue = targetField.text();
baseField.change(function(){
if($.inArray(baseField.val(), baseValue) > -1){
targetField.text(targetValue);
} else{
targetField.text(originalValue);
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div id="field1_div">
<fieldset>
<legend>Field 1 Legend</legend>
<label for="field1">Field 1</label>
<select id="field1" name="field1">
<option value="" selected>Field 1</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</fieldset>
</div>
<div id="field2_div">
<fieldset>
<legend>Default Field 2 Legend</legend>
<input id="field2" type="text" name="field2">
</fieldset>
</div>
add your code like following
$(function(){
$('#field1').change(function(){
if($.inArray($(this).val(), ['1','2']) >= 0){
$('#field2_div').children().find('legend').text('New Field 2 Legend');
}else{
$('#field2_div').children().find('legend').text('Default Field 2 Legend');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="field1_div">
<fieldset>
<legend>Field 1 Legend</legend>
<label for="field1">Field 1</label>
<select id="field1" name="field1">
<option value="" selected>Field 1</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</fieldset>
</div>
<div id="field2_div">
<fieldset>
<legend>Default Field 2 Legend</legend>
<input id="field2" type="text" name="field2">
</fieldset>
</div>
Here is my approach when changing values on the fly in a form.
I left you some work to customize it to your liking.
<div id="field1_div">
<fieldset>
<legend>Field 1 Legend</legend>
<label for="field1">Field 1</label>
<select id="field1" name="field1">
<option value="" selected>Field 1</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</fieldset>
</div>
<div id="field2_div">
<fieldset>
<legend>Default Field 2 Legend</legend>
<input id="field2" type="text" name="field2">
</fieldset>
</div>
<script>
function formChanger(inputValue) {
switch (inputValue) {
case '1':
// do something for selection 1
console.log('selected 1');
break;
case '2':
// do something for selection 2
console.log('selected 2');
break;
case '3':
// do something for selection 2
console.log('selected 3');
break;
case '4':
// do something for selection 2
console.log('selected 4');
break;
default :
// Probably want to remove any of the first 4 options that may have been implemented already.
return null;
}
}
$('#field1').change(function(){
formChanger($(this).val());
});
</script>
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.
I have a form that queries a library database on another site. It works perfectly if I only include input fields for the "format" and "keyword" because the resulting parameters passed to the url come out in the correct order and the destination site recognizes it.
However, I also need my form to have an input field to select to search by "Author", "Title", "Subject" etc. This is what causes the problem. The destination site only recognizes this parameter if it is in the middle of the url (inside the keyword parameter).
My current resulting url:
http://alpha2.suffolk.lib.ny.us/search~S50/X?SEARCH=harry&searchscope=50&SORT=D&m=b
What I need the url to look like:
http://alpha2.suffolk.lib.ny.us/search~S50/X?SEARCH=t:(harry)&searchscope=50&SORT=D&m=b
If you compare the two you will notice a couple differences. First, ignore the parentheses around harry. That doesn't make a difference. The real issue is how do I get the "t:" to be inserted into my url? The "t:" comes from selecting "Title" as the thing to search by.
Here is my current form HTML (If you remove the "searchtype" select box at the bottom the form will execute without errors, but I need it to execute with it.)
<form class="form-inline" role="search" method="get" name="searchform" id="searchform" action="http://alpha2.suffolk.lib.ny.us/search~S50/X">
<div class="form-group" style="float: left; margin-top: 6px;">
<label class="form-title">Search Collection</label>
</div>
<div class="form-group">
<input type="text" value="" name="SEARCH" id="SEARCH" placeholder="Enter Search Terms..." />
<input type="hidden" value="50" name="searchscope" />
<input type="hidden" value="D" name="SORT" />
</div>
<div class="form-group" style="float: left; margin-top: 3px;">
<label for="searchformat">For:</label>
<select name="m" id="m">
<option value="">ANY</option>
<option value="a">BOOK</option>
<option value="e">EBOOK DOWNLOAD</option>
<option value="l">LARGE PRINT BOOK</option>
<option value="b">BLU-RAY</option>
<option value="g">DVD</option>
<option value="i">AUDIO BOOK CD</option>
<option value="h">AUDIO BOOK MP3CD</option>
<option value="x">EAUDIOBOOK DOWNLOAD</option>
<option value="q">PLAYAWAY</option>
<option value="j">MUSIC CD</option>
<option value="p">MAGAZINE/NEWSPAPER</option>
<option value="n">EMAGAZINE DOWNLOADS</option>
<option value="v">PLAYAWAY VIEW</option>
<option value="s">VIDEO GAME</option>
<option value="r">CD-ROM</option>
<option value="d">VHS</option>
<option value="t">GAMES/PUZZLES</option>
<option value="f">DIGITAL IMAGE</option>
<option value="z">EVIDEO DOWNLOADS</option>
<option value="y">EMUSIC DOWNLOADS</option>
<option value="c">SHEET MUSIC</option>
<option value="m">MAP</option>
<option value="w">ONLINE RESOURCE</option>
<option value="o">OTHER MATERIALS</option>
</select>
</div>
<div class="form-group" style="float: left; margin-top: 3px;">
<label for="searchtype">By:</label>
<select name="" id="searchtype">
<option value="a:"> Author</option>
<option value="t:"> Title</option>
<option value="d:"> Subject</option>
<option value="N:"> Note</option>
<option value="" selected="selected"> Keyword</option>
</select>
</div>
<button class="btn btn-primary" id="searchsubmit" type="Submit">GO</button>
</form>
EDIT:
The attempted Javascript (as requested in the comments):
<script>
function searchSubmit() {
m = document.getElementById("m").value;
t = document.getElementById("searchtype").value;
a = document.getElementById("searcharg").value;
var newurl = "alpha2.suffolk.lib.ny.us/search/X~S22?SEARCH="; + t + a + "&searchscope=50&SORT=D&m=" + m;
var searchform = document.getElementById("searchform");
searchform.action = newurl; searchform.submit();
}
</script>
What I would do is get the searchtype-value and add it to the input-search before submitting. Here is a JS-fiddle example:
$(document).ready(function(){
$("#searchform").on("submit", function(e){
var keyWord = $("#SEARCH").val();
var searchtype = $("#searchtype").val();
$("#SEARCH").val(searchtype + keyWord);
});
});
If you want to use the JavaScript approach, you will have to use AJAX and prevent the default behavior of the button.
document.getElementById("searchsubmit").addEventListener("click", function(event){
event.preventDefault();
var xhttp = new XMLHttpRequest();
//here you set up your variables. One example is
var mysearch = "SEARCH=" + document.getElementById("searchtype").value + document.getElementById("SEARCH").value;
xhttp.open("GET", "yourURL?" + yourVariables, true);
xhttp.send();
});
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>