Hi I have almost finished a assignment on "Javascript" although I cant find any information on how to make some fields mutually exclusive, basically the top part of my form the user has to insert the address into mandatory fields then further down the form the is a radio check box the user must pick home address or other, (home being the top address they already inserted) the form is already validated to if the choose the home they do not have to insert any thing in other but I need to make it mutually exclusive so if they choose other it cant be the same as above, can any one please help me or give me a link for a tutorial, cause I can only find info on mutually exclusive radio button or check boxes nothing on what the user inputs to text box thanks
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Joes Fruit and Vegetable Store</title>
<script>
//calender dropdown menu
var monthtext=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec'];
function populatedropdown(dayfield, monthfield, yearfield){
var today=new Date()
var dayfield=document.getElementById(dayfield)
var monthfield=document.getElementById(monthfield)
var yearfield=document.getElementById(yearfield)
for (var i=0; i<31; i++)
dayfield.options[i]=new Option(i, i+1)
dayfield.options[today.getDate()]=new Option(today.getDate(), today.getDate(), true, true) //select today's day
for (var m=0; m<12; m++)
monthfield.options[m]=new Option(monthtext[m], monthtext[m])
monthfield.options[today.getMonth()]=new Option(monthtext[today.getMonth()], monthtext[today.getMonth()], true, true) //select today's month
var thisyear=today.getFullYear()
for (var y=0; y<20; y++){
yearfield.options[y]=new Option(thisyear, thisyear)
thisyear+=1
}
yearfield.options[0]=new Option(today.getFullYear(), today.getFullYear(), true, true) //select today's year
}
// function validate
function validate_form ()
{
//validate name
valid = true;
if ( document.input.name.value == "")
{
alert ( "Please enter your name");
valid = false;
}
// validate address
if ( document.input.address.value == "")
{
alert ( "Please enter your Address" );
valid = false;
}
// validate Town
if ( document.input.town.value == "")
{
alert ( "Please enter your Town" );
valid = false;
}
// validate postcode
var y = document.getElementById("postcode").value;
if(isNaN(y)||y.indexOf(" ")!=-1)
{
alert("Postcode must be in numbers.");
document.getElementById("postcode").focus();
return false;
}
if (y.length>4 || y.length<4)
{
alert("Postcode should be 4 digit");
document.getElementById("postcode").focus();
return false;
}
// validate home phone
var y = document.getElementById('hphone').value;
if(isNaN(y)||y.indexOf(" ")!=-1)
{
alert("Home Phone number must be in numbers.");
document.getElementById('hphone').focus();
return false;
}
if (y.length>10 || y.length<10)
{
alert("Home Phone number should be 10 digit");
document.getElementById('hphone').focus();
return false;
}
// validate work phone
var y = document.getElementById('wphone').value;
if(isNaN(y)||y.indexOf(" ")!=-1)
{
alert("work Phone number must be in numbers.");
document.getElementById('wphone').focus();
return false;
}
if (y.length>10 || y.length<10)
{
alert("Work Phone number should be 10 digit");
document.getElementById('wphone').focus();
return false;
}
// validate fax
var y = document.getElementById('fax').value;
if(isNaN(y)||y.indexOf(" ")!=-1)
{
alert("Fax number must be in numbers.");
document.getElementById('fax').focus();
return false;
}
if (y.length>10 || y.length<10)
{
alert("Fax Phone number should be 10 digit");
document.getElementById('fax').focus();
return false;
}
// validate email
{
var x=document.forms["input"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
// validate radio buttons
var o = document.getElementById('rad1');
var t = document.getElementById('rad2');
if ( (o.checked == false ) && (t.checked == true ) )
{
// validate alternative address
if ( document.input.street.value == "")
{
alert ( "Please enter alternative Address" );
valid = false;
}
// validate alternative suburb town
if ( document.input.suburb.value == "")
{
alert ( "Please enter alternative Suburb or town" );
valid = false;
}
} // validate alternative postcode
if ( (o.checked == false ) && (t.checked == true ) )
{
var y = document.getElementById('postcode2').value;
if(isNaN(y)||y.indexOf(" ")!=-1)
{
alert("Alternative Postcode must be in numbers.");
document.getElementById('postcode2').focus();
return false;
}
if (y.length>4 || y.length<4)
{
alert("Alternative Postcode should be 4 digit");
document.getElementById('postcode2').focus();
return false;
}
}
//validate message box
var o = document.getElementById("card");
if (o.checked == true )
{
if ( document.input.message.value == "" || document.input.message.value == "Please Enter message here" )
{
alert ( "Please enter message" );
valid = false;
}
return valid;
}
}
</script>
</head>
<body>
<b>Order form for Joe's Fruit Shop</b><br>
<br>
<b> * means you must fill in the details.</b><br>
<br>
<b>Your details:</b><br>
<br>
<!-- Beggining of Form -->
<form name="input" action="Joes.html" onsubmit="return validate_form ()">
<!--name input form -->
* Name: <input type="text" name="name" id="name" onclick="this.value='';" placeholder="Enter your Name"><br>
<br>
<!-- Address input form -->
* Address: <input type="text" name="address" id="address" onclick="this.value='';" placeholder="Enter your street address"><br>
<br>
<!-- Town & state dropdown form-->
* Suburb or Town: <input type="text" name="town" id="town" onclick="this.value='';" placeholder="Town"> * State:
<!-- state drop down list -->
<select name="state">
<option value="NSW">NSW</option>
<option selected="selected" value="QLD">QLD</option>
<option value="SA">SA</option>
<option value="WA">WA</option>
<option value="TAS">TAS</option>
<option value="VIC">VIC</option>
<option value="NT">NT</option>
<option value="ACT">ACT</option>
</select>
<!-- post code input form -->
* Postcode: <input type='text' name="postcode" id="postcode" onclick="this.value='';" placeholder="****"><br>
<br>
<!-- Home phone input form-->
* Phone: <input type='text' name="hphone" id="hphone" onclick="this.value='';" placeholder="x-xxxx-xxx">
<!-- work phone input form -->
* Work phone <input type='text' name="wphone" id="wphone" onclick="this.value='';" placeholder="x-xxxx-xxx"><br>
<br>
<!-- Fax input form-->
*Fax: <input type='text' name="fax" id="fax" onclick="this.value='';" placeholder="0x-xxxx-xxx">
<!-- Email input form-->
* Email address: <input type='text' name="email" id="email" onclick="this.value='';" onsubmit="return validateForm();" placeholder="Enter your current email"><br>
<br>
<br>
<!-- credit card form --> <b>Credit card details:</b><br>
<br>
* Type:
<select name="credit card">
<option selected="selected" value="AMEX">Amex</option>
<option value="Visa">Visa</option>
<option value="Mastercard">Mastercard</option>
</select>
<!--credit card month expiry date-->
*Expiry date:
<select name="expiration_month">
<option value="">Choose...</option>
<option selected="selected" value="1">January</option>
<option value="2">Febuary</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<!-- Credit card year expiry date-->
<select name="expiration_year">
<option value="">Choose...</option>
<option selected="selected" value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
</select>
<br>
<br>
<b>Purchase details</b><br>
<br>
<!-- Product dropdown form-->
* Product:
<select name="product">
<option value="carrot">Bag of carrots</option>
<option value="zucchini">Zucchini</option>
<option value="cabbage">Cabbage</option>
<option value="grapes">Grapes</option>
<option value="tomatoes">TAS</option>
<option value="apples">Apples</option>
<option value="banana">banana</option>
<option selected="selected" value="cucumber">Cucumber</option>
</select>
<!-- Quantity dropdown form-->
Quantity:
<select name="quantity">
<option selected="selected" value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
<br>
<br>
<br>
* <b>Deliver to:</b>
<br>
<br>
<!-- Address Radio check buttons-->
<input type='radio' id="rad1" name='rad' checked="checked">Home Address<br>
<input type='radio' id="rad2" name='rad'/>Other Address<br>
<br>
<!-- alternative street form-->
Street <input type='text' name="street" id="street" onclick="this.value='';" placeholder="Street"><br>
<br>
<!-- alternative Suburb form-->
Suburb <input type='text' name="suburb" id="suburb" onclick="this.value='';" placeholder="Suburb or town"><br>
<br>
<!-- alternative State dropdown form-->
State
<select name="state">
<option value="NSW">NSW</option>
<option selected="selected" value="QLD">QLD</option>
<option value="SA">SA</option>
<option value="WA">WA</option>
<option value="TAS">TAS</option>
<option value="VIC">VIC</option>
<option value="NT">NT</option>
<option value="ACT">ACT</option>
</select>
<br>
<br>
<!-- alternative post code form -->
Postcode:<input type='text' name="postcode2" id="postcode2" onclick="this.value='';" placeholder="****"><br>
<br>
<br>
* Date delivery required:
<!-- Calender drop down menu-->
<select id="daydropdown">
</select>
<select id="monthdropdown">
</select>
<select id="yeardropdown">
</select>
<script type="text/javascript">
//populatedropdown(id_of_day_select, id_of_month_select, id_of_year_select)
window.onload=function(){
populatedropdown("daydropdown", "monthdropdown", "yeardropdown")
}
</script>
<br>
<br>
<!-- include a card option-->
Include a card: <input type="checkbox" name="card" id="card">Yes<br>
<br>
Personal message on card: <textarea name="message" id="message" cols="20" rows="10" onclick="this.value='';">Please Enter message here</textarea><br>
<br>
Click on <b>Submit</b> when done; click on <b> Clear form</b> to reset.
<!-- submit button-->
<input type="submit" value="Submit">
<!-- reset button-->
<input type="reset" value="Reset">
</form><br>
<script>
<!--
document.write("<i>Last updated "+document.lastModified+"<I>");
//-->
</script>
</body>
</html>
This is incomplete. I've added functions for some of your options. copy and check for yourself where the changes are. I think you can do the rest
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Joes Fruit and Vegetable Store</title>
<script>
//calender dropdown menu
var monthtext=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec'];
function populatedropdown(dayfield, monthfield, yearfield){
var today=new Date()
var dayfield=document.getElementById(dayfield)
var monthfield=document.getElementById(monthfield)
var yearfield=document.getElementById(yearfield)
for (var i=0; i<31; i++)
dayfield.options[i]=new Option(i, i+1)
dayfield.options[today.getDate()]=new Option(today.getDate(), today.getDate(), true, true) //select today's day
for (var m=0; m<12; m++)
monthfield.options[m]=new Option(monthtext[m], monthtext[m])
monthfield.options[today.getMonth()]=new Option(monthtext[today.getMonth()], monthtext[today.getMonth()], true, true) //select today's month
var thisyear=today.getFullYear()
for (var y=0; y<20; y++){
yearfield.options[y]=new Option(thisyear, thisyear)
thisyear+=1
}
yearfield.options[0]=new Option(today.getFullYear(), today.getFullYear(), true, true) //select today's year
}
// function validate
function validate_form ()
{
//validate name
valid = true;
if ( document.input.name.value == "")
{
alert ( "Please enter your name");
valid = false;
}
// validate address
if ( document.input.address.value == "")
{
alert ( "Please enter your Address" );
valid = false;
}
// validate Town
if ( document.input.town.value == "")
{
alert ( "Please enter your Town" );
valid = false;
}
// validate postcode
var y = document.getElementById("postcode").value;
if(isNaN(y)||y.indexOf(" ")!=-1)
{
alert("Postcode must be in numbers.");
document.getElementById("postcode").focus();
return false;
}
if (y.length>4 || y.length<4)
{
alert("Postcode should be 4 digit");
document.getElementById("postcode").focus();
return false;
}
// validate home phone
var y = document.getElementById('hphone').value;
if(isNaN(y)||y.indexOf(" ")!=-1)
{
alert("Home Phone number must be in numbers.");
document.getElementById('hphone').focus();
return false;
}
if (y.length>10 || y.length<10)
{
alert("Home Phone number should be 10 digit");
document.getElementById('hphone').focus();
return false;
}
// validate work phone
var y = document.getElementById('wphone').value;
if(isNaN(y)||y.indexOf(" ")!=-1)
{
alert("work Phone number must be in numbers.");
document.getElementById('wphone').focus();
return false;
}
if (y.length>10 || y.length<10)
{
alert("Work Phone number should be 10 digit");
document.getElementById('wphone').focus();
return false;
}
// validate fax
var y = document.getElementById('fax').value;
if(isNaN(y)||y.indexOf(" ")!=-1)
{
alert("Fax number must be in numbers.");
document.getElementById('fax').focus();
return false;
}
if (y.length>10 || y.length<10)
{
alert("Fax Phone number should be 10 digit");
document.getElementById('fax').focus();
return false;
}
// validate email
{
var x=document.forms["input"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
// validate radio buttons
var o = document.getElementById('rad1');
var t = document.getElementById('rad2');
if ( (o.checked == false ) && (t.checked == true ) )
{
// validate alternative address
if ( document.input.street.value == "")
{
alert ( "Please enter alternative Address" );
valid = false;
}
// validate alternative suburb town
if ( document.input.suburb.value == "")
{
alert ( "Please enter alternative Suburb or town" );
valid = false;
}
} // validate alternative postcode
if ( (o.checked == false ) && (t.checked == true ) )
{
var y = document.getElementById('postcode2').value;
if(isNaN(y)||y.indexOf(" ")!=-1)
{
alert("Alternative Postcode must be in numbers.");
document.getElementById('postcode2').focus();
return false;
}
if (y.length>4 || y.length<4)
{
alert("Alternative Postcode should be 4 digit");
document.getElementById('postcode2').focus();
return false;
}
}
//validate message box
var o = document.getElementById("card");
if (o.checked == true )
{
if ( document.input.message.value == "" || document.input.message.value == "Please Enter message here" )
{
alert ( "Please enter message" );
valid = false;
}
return valid;
}
}
function fnc1()
{
document.getElementById("hsuburb").value=document.getElementById("town").value;
document.getElementById("hstate").value=document.getElementById("state").value;
document.getElementById("postcode2").value=document.getElementById("postcode").value;
document.getElementById("hsuburb").disabled="disabled";
document.getElementById("hstate").disabled="disabled";
document.getElementById("postcode2").disabled="disabled";
}
function fnc2(myid)
{
value=document.getElementById(myid).value;
a=document.getElementById("town").value;
b=document.getElementById("state").value;
c=document.getElementById("postcode").value;
if(value==a)
{alert("change your town");
document.getElementById(myid).value='';
}
else if(value==b)
{alert("change your state");
document.getElementById("default").selected="Selected";
}
else if(value==c)
{alert("change your postcode");
document.getElementById(myid).value='';
}
}
function fnc3()
{
document.getElementById("hsuburb").disabled=false;
document.getElementById("hstate").disabled=false;
document.getElementById("postcode2").disabled=false;
}
</script>
</head>
<body>
<b>Order form for Joe's Fruit Shop</b><br>
<br>
<b> * means you must fill in the details.</b><br>
<br>
<b>Your details:</b><br>
<br>
<!-- Beggining of Form -->
<form name="input" action="Joes.html" onsubmit="return validate_form ()">
<!--name input form -->
* Name: <input type="text" name="name" id="name" onclick="this.value='';" placeholder="Enter your Name"><br>
<br>
<!-- Address input form -->
* Address: <input type="text" name="address" id="address" onclick="this.value='';" placeholder="Enter your street address"><br>
<br>
<!-- Town & state dropdown form-->
* Suburb or Town: <input type="text" name="town" id="town" onclick="this.value='';" placeholder="Town"> * State:
<!-- state drop down list -->
<select name="state" id="state" >
<option value="NSW">NSW</option>
<option selected="selected" value="QLD">QLD</option>
<option value="SA">SA</option>
<option value="WA">WA</option>
<option value="TAS">TAS</option>
<option value="VIC">VIC</option>
<option value="NT">NT</option>
<option value="ACT">ACT</option>
</select>
<!-- post code input form -->
* Postcode: <input type='text' name="postcode" id="postcode" onclick="this.value='';" placeholder="****"><br>
<br>
<!-- Home phone input form-->
* Phone: <input type='text' name="hphone" id="hphone" onclick="this.value='';" placeholder="x-xxxx-xxx">
<!-- work phone input form -->
* Work phone <input type='text' name="wphone" id="wphone" onclick="this.value='';" placeholder="x-xxxx-xxx"><br>
<br>
<!-- Fax input form-->
*Fax: <input type='text' name="fax" id="fax" onclick="this.value='';" placeholder="0x-xxxx-xxx">
<!-- Email input form-->
* Email address: <input type='text' name="email" id="email" onclick="this.value='';" onsubmit="return validateForm();" placeholder="Enter your current email"><br>
<br>
<br>
<!-- credit card form --> <b>Credit card details:</b><br>
<br>
* Type:
<select name="credit card">
<option selected="selected" value="AMEX">Amex</option>
<option value="Visa">Visa</option>
<option value="Mastercard">Mastercard</option>
</select>
<!--credit card month expiry date-->
*Expiry date:
<select name="expiration_month">
<option value="">Choose...</option>
<option selected="selected" value="1">January</option>
<option value="2">Febuary</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<!-- Credit card year expiry date-->
<select name="expiration_year">
<option value="">Choose...</option>
<option selected="selected" value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
</select>
<br>
<br>
<b>Purchase details</b><br>
<br>
<!-- Product dropdown form-->
* Product:
<select name="product">
<option value="carrot">Bag of carrots</option>
<option value="zucchini">Zucchini</option>
<option value="cabbage">Cabbage</option>
<option value="grapes">Grapes</option>
<option value="tomatoes">TAS</option>
<option value="apples">Apples</option>
<option value="banana">banana</option>
<option selected="selected" value="cucumber">Cucumber</option>
</select>
<!-- Quantity dropdown form-->
Quantity:
<select name="quantity">
<option selected="selected" value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
<br>
<br>
<br>
* <b>Deliver to:</b>
<br>
<br>
<!-- Address Radio check buttons-->
<input type='radio' id="rad1" name='rad' onClick="fnc1()">Home Address<br>
<input type='radio' id="rad2" name='rad' onClick="fnc3()" />Other Address<br>
<br>
<!-- alternative street form-->
Street <input type='text' name="street" id="hstreet" onclick="this.value='';" placeholder="Street"><br>
<br>
<!-- alternative Suburb form-->
Suburb <input type='text' name="suburb" id="hsuburb" onclick="this.value='';" placeholder="Suburb or town" onChange="fnc2(this.id)"><br>
<br>
<!-- alternative State dropdown form-->
State
<select name="state" id="hstate" onChange="fnc2(this.id)">
<option value="-1" id="default">select</option>
<option value="NSW">NSW</option>
<option selected="selected" value="QLD">QLD</option>
<option value="SA">SA</option>
<option value="WA">WA</option>
<option value="TAS">TAS</option>
<option value="VIC">VIC</option>
<option value="NT">NT</option>
<option value="ACT">ACT</option>
</select>
<br>
<br>
<!-- alternative post code form -->
Postcode:<input type='text' name="postcode2" id="postcode2" onclick="this.value='';" placeholder="****" onChange="fnc2(this.id)"><br>
<br>
<br>
* Date delivery required:
<!-- Calender drop down menu-->
<select id="daydropdown">
</select>
<select id="monthdropdown">
</select>
<select id="yeardropdown">
</select>
<script type="text/javascript">
//populatedropdown(id_of_day_select, id_of_month_select, id_of_year_select)
window.onload=function(){
populatedropdown("daydropdown", "monthdropdown", "yeardropdown")
}
</script>
<br>
<br>
<!-- include a card option-->
Include a card: <input type="checkbox" name="card" id="card">Yes<br>
<br>
Personal message on card: <textarea name="message" id="message" cols="20" rows="10" onclick="this.value='';">Please Enter message here</textarea><br>
<br>
Click on <b>Submit</b> when done; click on <b> Clear form</b> to reset.
<!-- submit button-->
<input type="submit" value="Submit">
<!-- reset button-->
<input type="reset" value="Reset">
</form><br>
<script>
<!--
document.write("<i>Last updated "+document.lastModified+"<I>");
//-->
</script>
</body>
</html>
Related
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 made a drop-down menu for user to select,for the date, it looks like this
How do I the alert user that they didn't select a date? The month, day and year are options in the <select> element
if(document.forms[0].checkindate.selectedIndex == 1) {
window.alert("You must select a date.");
return false;
}
I did this, but it doesn't work.
Give select values are empty and validate by using html required like
<select required>
<option value="">Month</option>
<option vslue="1">1</option>
</select>
<select required>
<option value="">Day</option>
<option vslue="1">1</option>
</select>
<select required>
<option value="">Year</option>
<option vslue="2016">2016</option>
</select>
Or use Javascript or jQuery Validation
<html>
<head>
<title>Form</title>
<script type="text/javascript">
function validate()
{
if(document.getElementById("city").value=="-1")
{
alert('Please select a city');
return false;
}
else if (document.getElementById('day').value=='')
{
alert('Please provide date for D.O.B');
document.getElementById("day").style.borderColor="red";
document.getElementById("day").style.backgroundColor="yellow";
document.getElementById("day").style.borderWidth=2;
return false;
}
else if (document.getElementById('month').value=='')
{
alert('Please provide month for D.O.B');
document.getElementById("month").style.borderColor="red";
document.getElementById("month").style.backgroundColor="yellow";
document.getElementById("month").style.borderWidth=2;
return false;
}
else if (document.getElementById('year').value=='')
{
alert('Please provide year for D.O.B');
document.getElementById("year").style.borderColor="red";
document.getElementById("year").style.backgroundColor="yellow";
document.getElementById("year").style.borderWidth=2;
return false;
}
}
</script>
<body>
<form >
City : <select id="city">
<option value="-1">-~Select One~-</option>
<option>City 1</option>
<option>City 2</option>
<option>City 3</option>
<option>City 4</option>
<option>City 5</option>
</select>
<br>
Date of Birth:
Day
<input type="number" name="day" id='day' min="1" max="31" value="" required>
Month
<input type="number" name="month" min="1" id='month' max="12" value="" required>
Year
<input type="number" name="year" min="1950" id='year' max="2020" value="" required>
<input type="submit" value="Login" onclick="return(validate());"
</form>
</body>
</html>
Refer to the above given example to have a clear view. Hope you will understand.
You can use the .each() function to check if any of the dropdowns are not selected by the user.
$('select').each(function () {
if (this.value)
alert('value selected');
else
alert('no selection');
});
<div class='input1'>
<select name="gender" class="gender" id="gender">
<option value="">Gender</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
js
reg_gender = /(male|female)/;
if(form.gender.value == "" && (!reg_gender.test(form.gender.value)) ) {
alert("Please select gender!");
form.gender.focus();
return false;
}
EDITTED
How should I validate country using the method similar to gender? However, my country is not hardcoded. It is calling from an api.
Make simple change to your HTML:
<div class='input1'>
<select id="gender" name="gender" class="gender">
<option value="">Gender</option> <!-- make change value="" -->
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
Also add some line of codes in your javascript:
reg_gender = /(male|female)/;
if(form.gender.value == "" && (!reg_gender.test(form.gender.value)) ) {
alert("Please select gender!");
form.gender.focus();
return false;
}
This expression /(male|female)/ check if value is either male or female
I am trying to validate radiobuttons and optionbox in javascript. Here is the code but it is not working...
Javascript Code for OprionBox and Radio:
function checkCountry()
{
if(document.form.country.selectedIndex=="")
{
alert("Please select country from the list");
return false;
}
return true
}
function checkGender()
{
if(!document.getElementsByName("sex")[0].checked && !document.getElementsByName("sex")[1].checked)
{
alert("Select Male/Female");
return false;
}
return true;
}
function validate()
{
checkCountry();
checkGender();
}
HTML code:
<form name="form" method="post" onSubmit="return validate()">
<select name="country">
<option value="select">(Please select a country)</option>
<option value="pk">Pakistan</option>
<option value="chn">China</option>
<option value="uk">United Kingdom</option>
<option value="usa">United States of America</option>
<option value="ir">Iran</option>
<option value="ma">Malaysia</option>
</select><br>
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female<br></form>
Please help...
Change if(document.form.country.selectedIndex=="") to if(document.getElementsByName("country").selectedIndex=="0")
You'll have to change the line where you check for the selected index to:
if(document.form.country.selectedIndex === 0) thats because of your "Please select a country" entry you will always have a selected index.
If i then add <input type="submit" value="test"/> inside your form to test submitting i will get your error messages.
Please see http://jsbin.com/oviped/2/edit it is working!
This is whole code and its working fine
<html>
<head>
<script type="text/javascript">
function checkGender()
{
if(!document.getElementsByName("sex")[0].checked && !document.getElementsByName("sex")[1].checked)
{
alert("Select Male/Female");
return false;
}
return true;
}
function checkCountry()
{
if(document.getElementsByName("country")[0].selectedIndex==0)
{
alert("Please select country from the list");
return false;
}
return true
}
function validate()
{
checkCountry();
checkGender();
}
</script>
</head>
<body>
<form onSubmit="return validate()" >
<select name="country">
<option value="select">(Please select a country)</option>
<option value="pk">Pakistan</option>
<option value="chn">China</option>
<option value="uk">United Kingdom</option>
<option value="usa">United States of America</option>
<option value="ir">Iran</option>
<option value="ma">Malaysia</option>
</select><br>
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female<br>
<input type="submit" value="Submit" >
</form>
</body>
</html>
Hey guys, I just updated my signup form to include drop down menu selectors to select gender and class and section. But I don't know how to verify them and check that a value is selected.
Here is the code:
<form name="registration_form" method="post" action="register.php" onsubmit="return Validate();"><input type=hidden name=todo value=post>
<table>
<tr><td class="label">First Name:</td><td><input type="text" name="fname"></td></tr>
<tr><td class="label">Last Name:</td><td><input type="text" name="lname"></td></tr>
<tr><td class="label">Gender:</td><td><select name="gender">
<option>Select your gender:</option>
<option value="M">Male</option>
<option value="F">Female</option>
</select></td></tr>
<tr><td class="label">E-Mail Address:</td><td><input type="email" name="email"></td></tr>
<tr><td class="label">Username:</td><td><input type="text" name="username"></td></tr>
<tr><td class="label">Password:</td><td><input type="password" name="password"></td></tr>
<tr><td class="label">Password Confirmation:</td><td><input type="password" name="password_confirmation"></td></tr>
<tr><td class="label">Class:</td><td><select name="class">
<option>Select your class:</option>
<option value="1">Grade 1</option>
<option value="2">Grade 2</option>
<option value="3">Grade 3</option>
<option value="4">Grade 4</option>
<option value="5">Grade 5</option>
<option value="6">Grade 6</option>
<option value="7">Grade 7</option>
<option value="8">Grade 8</option>
<option value="9">Grade 9</option>
<option value="10">1S</option>
<option value="11">2S</option>
<option value="12">3S</option>
</select></td></tr>
<tr><td class="label">Section:</td><td><select name="section">
<option>Select a section:</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
<option value="S">S</option>
<option value="SE">SE</option>
<option value="GS">GS</option>
<option value="LS">LS</option>
</select></td></tr>
<tr><td>Are you human?</td></tr>
</table>
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
require_once('recaptchalib.php');
$publickey = "6LfF478SAAAAAFR1_ZfSFzGyEhkcXlNVRg8iJeWU"; // you got this from the signup page
echo recaptcha_get_html($publickey);
?>
<table>
<tr><td class="label"><input class="submitButton" type="submit" value="Register"></td></tr>
</table>
</form>
</div>
<script language = "Javascript">
function Validate()
{
if (document.registration_form.fname.value == '')
{
alert('Please fill in your first name!');
return false;
}
if (document.registration_form.lname.value == '')
{
alert('Please fill in your last name!');
return false;
}
if (document.registration_form.email.value == '')
{
alert('Please fill in your email address!');
return false;
}
if (document.registration_form.username.value == '')
{
alert('Please fill in your desired username!');
return false;
}
if (document.registration_form.password.value == '')
{
alert('Please fill in your desired password!');
return false;
}
if (document.registration_form.password_confirmation.value == '')
{
alert('Please fill in your password again for confirmation!');
return false;
}
if (document.registration_form.password.value !=
document.registration_form.password_confirmation.value)
{
alert("The two passwords are not identical! "+
"Please enter the same password again for confirmation!");
return false;
}
return true;
}
</script>
My question is what can I add to the Validate function so that it returns false if the values selected are "Please select your ... "
Edit(1): Ok I tried this but it didn't seem to work, what's wrong?
var selectedClass = document.getElementById("class");
if(selectedClass.selectedIndex ==0){
alert('Please select your class!');
return false;
}
Edit(2): Never mind I got it to work.
function validate(){
var selectedClass = doument.getElementById("Class");
if(selectedClass.selectedIndex ==0){
alert(selectedClass.options[0].text);
return false;
}
}
The selectedIndex of "Please select your... " would be 0 so your code should check that the selectedIndex of the select control is always greater than 0.