I am trying to have a select drop down with about 25 options certain choices that are picked will make another textbox field appear and be required. I tried making it grayed out and always there but since nothing was entered it was still required and would not process.
Now I have changed it to read-only and just wrote Not Required in the box since its filled out it would accept if its a required field.
But I really would like to learn how to make it just appear when that option is selected and once it appears make it required so the user can not go onto the next page until it is filled out.
(If you choose pickup or truck it is required)
So basically Dropdown makes textbox appear and required and not required when it is not showing
Does anyone have any ideas of how I could do this?
http://jsfiddle.net/of1sdq11/
function GVW(){
var dropdown1 = document.getElementById('vehiclebody');
var textbox = document.getElementById('gvw');
if(dropdown1.selectedIndex == 0){
textbox.value = "";
document.getElementById("gvw").readOnly = false;
}
else if(dropdown1.selectedIndex == 1) {
textbox.value = "NOT REQUIRED";
document.getElementById("gvw").readOnly = true;
}
else if(dropdown1.selectedIndex == 2) {
textbox.value = "";
document.getElementById("gvw").readOnly = false;
}
else if(dropdown1.selectedIndex == 3) {
textbox.value = "NOT REQUIRED";
document.getElementById("gvw").readOnly = true;
}
else if(dropdown1.selectedIndex == 4) {
textbox.value = "";
document.getElementById("gvw").readOnly = false;
}
else if(dropdown1.selectedIndex == 5) {
textbox.value = "NOT REQUIRED";
document.getElementById("gvw").readOnly = true;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select name="vehiclebody" id="vehiclebody" required="yes" message="Please select body." size="1" onChange="GVW();">
<option value="">Choose a Vehicle</option>
<option value="0">2Dr</option>
<option value="1">Pickup</option>
<option value="2">4dr</option>
<option value="3">Truck</option>
<option value="4">Convertible</option>
<option value="5">Van</option>
</select>
<input type="text" name="gvw" id="gvw" onfocus="this.select()" message="Please enter gross vehicle weight." value="">
If I am understanding you correctly, you want to make it so the textbox doesn't even show unless it is required. I modified the code a bit so that you don't need the list of if statements. By making an array that corresponds to the selectedIndex, you can just check the property!
Find the jsFiddle here: http://jsfiddle.net/of1sdq11/19/
First, I made the textbox start hidden. If the display is set to none, it will not be submitted with the form. If display is anything other than none, it will display and submit with the form. If you just wanted an invisible field that was always submitted, you would use visibility set to hidden instead!
<input type="text" name="gvw" id="gvw" onfocus="this.select()" message="Please enter gross vehicle weight." value="" style="display:none;">
Then I modified your code to show the textbox if the properties match. Now all you have to do is set whether required is true or false in the "is_required" variable to match the corresponding selectedIndex and it should work.
function GVW(){
var dropdown1 = document.getElementById('vehiclebody');
var textbox = document.getElementById('gvw');
// Array for storing whether the textbox is required
var is_required = [false, true, false, true, false, true];
// If dropdown1.selectedIndex is 0, it will pull the value from the 0 slot
// of the is_required array
if(is_required[dropdown1.selectedIndex]) {
textbox.required = true;
textbox.style.display = "inline-block";
} else {
textbox.value = "";
textbox.required = false;
textbox.style.display = "none";
}
}
Now on whatever page you are submitting to, you can just check to see if the textbox even existed in the form submission, and if it did, get the data, otherwise skip it!
jQuery Version With Modifications
After further discussion with the OP, I rewrote this to work with all jQuery, along with adding the ability to hide a label in addition. I thought that others may find it helpful, so I wanted to post it here. Find the fiddle here: http://jsfiddle.net/of1sdq11/26/
The HTML
<select name="vehiclebody" id="vehiclebody" required="yes" message="Please select body." size="1">
<option value="">Choose a Vehicle</option>
<option value="0">2Dr</option>
<option value="1">Pickup</option>
<option value="2">4dr</option>
<option value="3">Truck</option>
<option value="4">Convertible</option>
<option value="5">Van</option>
</select>
<div style="display:inline;">
<label for="gvw" style="display:none;"> Gross Vehicle Weight:*</label>
<input type="text" name="gvw" id="gvw" onfocus="this.select()" message="Please enter gross vehicle weight." value="" style="display:none;">
<p style="display:none;">*Gross Vehicle Weight is required for heavy trucks over 5000 lbs. Visit our website for more information. Heavy Truck Information and Fee Schedule based on GVW </p>
</div>
The jQuery
$(function() {
$('#vehiclebody').change(function() {
var selected_index = $(this).find(":selected").index();
var textbox = $('#gvw');
var label = textbox.siblings('label');
var paragraph = textbox.siblings('p');
// Array for storing whether the textbox is required
var is_required = [false, true, false, true, false, true];
// If dropdown1.selectedIndex is 0, it will pull the value from the 0 slot
// of the is_required array
if(is_required[selected_index]) {
textbox.attr("required", "true");
textbox.show();
label.show();
paragraph.show();
} else {
textbox.val("");
textbox.attr("required", "false");
textbox.hide();
label.hide();
paragraph.hide();
}
});
});
Here's what you need. Check this fiddle
http://jsfiddle.net/of1sdq11/15/
<select name="vehiclebody" id="vehiclebody" required="yes" message="Please select body." size="1" onChange="GVW();">
<option value="">Choose a Vehicle</option>
<option value="0">2Dr</option>
<option value="1">Pickup</option>
<option value="2">4dr</option>
<option value="3">Truck</option>
<option value="4">Convertible</option>
<option value="5">Van</option>
</select>
<input type="text" name="gvw" id="gvw" onfocus="this.select()" message="Please enter gross vehicle weight." value="" hidden>
.
function GVW(){
var dropdown1 = document.getElementById('vehiclebody');
var textbox = document.getElementById('gvw');
if(dropdown1.selectedIndex == 0){
textbox.value = "";
document.getElementById("gvw").hidden = false;
document.getElementById("gvw").required = "yes";
}
else if(dropdown1.selectedIndex == 1) {
textbox.value = "NOT REQUIRED";
document.getElementById("gvw").hidden = true;
document.getElementById("gvw").required = "no";
}
else if(dropdown1.selectedIndex == 2) {
textbox.value = "";
document.getElementById("gvw").hidden = false;
document.getElementById("gvw").required = "yes";
}
else if(dropdown1.selectedIndex == 3) {
textbox.value = "NOT REQUIRED";
document.getElementById("gvw").hidden = true;
document.getElementById("gvw").required = "no";
}
else if(dropdown1.selectedIndex == 4) {
textbox.value = "";
document.getElementById("gvw").hidden = false;
document.getElementById("gvw").required = "yes";
}
else if(dropdown1.selectedIndex == 5) {
textbox.value = "NOT REQUIRED";
document.getElementById("gvw").hidden = true;
document.getElementById("gvw").required = "no";
}
}
Related
I can't seem to figure out the proper JavaScript to validate this form. Please help/provide feedback!
Essentially, my script should validate whether the user has entered data in the input text box, has checked a radio button, has checked at least one checkbox, and has selected an option from the select items.
Also the form uses a submit button to invoke the validation script, so that the form is processed only when the form fields are validated and accepted. If a field is invalid then display a message to the user.
Also need to make sure the form doesn't automatically reset every time the user gets a validation error.
<body>
<section>
<h1 style="text-align: center">Vacation Interest Vote Form</h1>
<form name="VacayForm" action="mailto:" onsubmit="return Validate1()" method="post">
<p>Name:<input type="text" name="name" size="25"></p><br>
<p>Do You Prefer an international destination?</p>
<p>Domestic<input type="radio" name="domint" value="domestic"></p>
<p>International<input type="radio" name="domint" value="international"></
<br>
<p>Where would you like to go?</p>
<select type="text" name="continent" value="select" size="1">
<option value="domestic">Domestic</option>
<option value="europe">Europe</option>
<option value="camerica">Central America</option>
<option value="asia">Asia</option>
<option value="aus">Australia</option>
</select>
<br>
<p>Check the box to act as your digital signature to cast your vote
<input type="checkbox" value="agree" name="sig">
<input type="submit" value="Send" name="submit" onclick="if(!this.form.sig.checked){alert('You must agree to cast your vote by checking the box.');
return false}">
<input type="reset" value="Reset"name="reset">
</form>
</section>
<script>
function Validate1() {
var nam = document.forms["VacayForm"]["name"];
var dom = document.forms["VacayForm"]["domestic"];
var int = document.forms["VacayForm"]["international"];
var sel = document.forms["VacayForm"]["select"];
var agree = document.forms["VacayForm"]["agree"];
//if (name.value == "")
//{
// window.alert("Please enter your name.");
// name.focus();
// return false;
//}
if( document.VacayForm.name.value == "" )
{
alert( "Please provide your name!" );
document.VacayForm.name.focus() ;
return false;
}
if (domestic.value == "")
else (international.value == "")
{
window.alert("Please select domestic or international preference to proceed.");
domestic.focus();
international.focus();
return false;
}
if (select.selectedIndex < 1)
{
alert("Please select where you prefer to visit");
select.focus();
return false;
}
return true;
}
//function Validate2() {
// var radios = document.getElementsByName("yesno");
// var formValid = false;
// var i = 0;
// while (!formValid && i < radios.length) {
// if (radios[i].checked) formValid = true;
// i++;
// }
// if (!formValid) alert("Must check an option!");
// return formValid;
//}
</script>
</body>
</html>
Your validate function could look like this...
function validate() {
var form = document.forms.VacayForm;
var name = form.name;
var domInt = form.domint;
var continent = form.continent;
var agree = form.agree;
if (!name.value) {
alert( "Please provide your name!" );
name.focus();
return false;
}
if (!domInt.value) {
alert( "Please select domestic or international preference to proceed" );
domInt.focus();
return false;
}
if (!continent.value) {
alert("Please select where you prefer to visit");
continent.focus();
return false;
}
if (!agree.checked) {
alert("Please check agree to continue");
agree.focus();
return false;
}
return true;
}
This article from Javascript.info website teaches how to use forms and form elements...
I am adding multiple controls on an .aspx page from the .vb page based on certain conditions.
My code looks like following:
Dim sb As New StringBuilder
sb.Append("<table border='0'cellpadding='0' cellspacing='0' width='50%' class ='tabledata' id='tblContent'>")
For Each item As myObject In myLst
sb.Append("<tr><td style='width:50%;' valign='top'>")
sb.Append("<textarea id=txt_comments" & i & " name='txt_comments' rows='5' cols='60'></textarea></td>")
sb.Append("<td style='width:15%' valign='top' align='center'><select ID = validate" & i & " name=ValidateValues style ='border:1;width:150px'><option value = ''>Select</option><option value = 'Yes'>Yes</option><option value = 'No'>No</option><br /><br /></td>")
sb.Append("</tr><tr>")
Next
sb.Append("</table>")
myContent.InnerHtml = sb.ToString
So here I am creating <textarea> and <select> dynamically and adding them to my div(myContent)
<div id="structuredContent" runat="server">
</div>
I have a button next where I need to validate for few conditions.
My validation rule is:
User has to select either yes or no from the dropdown(<select>)
If user select 'yes', they have to enter text in
<textarea>(minimum1 character, maximum 1000 characters)
If user select 'No', <textarea> should be disabled.
I am trying to validate like following:
function validateComments() {
var errorcheck = 0;
$("[id^=txt_comments]").each(function () {
var comment = $.trim($(this).val());
$("[id^=validate]").each(function () {
debugger;
var value = $(this).val();
if (comment == 0 && value == "Yes") {
debugger;
errorcheck = 1;
}
});
}); if (errorcheck == 1) {
//show error message
}
else {
ErrorHide();
return true;
}
}
I am able to validate only for one control(which is textarea) from the above code.
The textbox and respective dropdown should be validated along.
How do I add validation for dropdown and can I combine with in the same function.
Any help?
Thanks in advance.
I don't know how do you expect this like if (comment == 0) { to work.
You'll always get a string as a value and checking it with 0 would always return false. Rather you need to check it with "".
And to enable/disable textarea you'll have to attach an event to select tag and do whatever you want to do.
here is an example
$("#d").change(function(){
if($(this).val() === 'n'){
$("#t").prop('disabled', 'disabled')
}else{
$("#t").prop('disabled', false)
}
});
$('body').on('click', '#b', function() {
var text = $.trim($("#t").val());
if(text === "" && !$("#t").prop('disabled')){
alert("yo! not valid")
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="d">
<option value="0">Select</option>
<option value="y">Yes</option>
<option value="n">No</option>
</select>
<textarea maxlength="50" id="t"></textarea>\
<button id="b">Validate</button>
I have a select option box that when I select it, a div-input appear. The problem that when I put validation on the this div-input, and when i submit even when it hide, it require me to validate it, thus giving me error msg.
How to do enable validation for this input field only when if it appear?
PHP
<div class="form-group">
<label for="inquiry_type">Subject *: </label>
<select name="type" id="inquiry_type" class="form-control">
<option value="0">Please Select</option>
<option value="test1">test1</option>
<option value="test2">test2</option>
<option value="others">Other...</option> //div-input appear when sel
</select>
</div>
<div id="other_subj" class="form-group">
<label for="other_msg_subj">Input Subject Title *: </label>
<input type="text" id="other_msg_subj" class="form-control" name="other_msg_subj" placeholder="Enter Subject Title" required/>
</div>
JQUERY for hide/show
<script>
$(function() {
$('#other_subj').hide();
$('#inquiry_type').change(function(){
if($('#inquiry_type').val() === 'others') {
$('#other_subj').show();
} else {
$('#other_subj').hide();
}
});
});
var inquiry_other_subj = document.getElementById("other_msg_subj").value;
...
} else if (!inquiry_other_subj.match(/^(?=.*[A-Za-z ]).{5,20}$/)) {
alert("Need to enter a proper inquiry title containing only letter!"); // I want this to be active only when the div is shown
} else {
var parameters="...+"&other_msg_subj="+inquiry_other_subj;
PHP validation
//Same for this php validation
...
else if(!preg_match ('%^[A-Za-z\.\' \-]{2,30}$%', $_POST['other_msg_subj'])){
echo "Please enter a valid message subject title!";
exit();
}
This may help.
in JQUERY:
Validate only if others is selected.
var inquiry_type = $('#inquiry_type').val();
else if (inquiry_type === 'others' && !inquiry_other_subj.match(/^(?=.*[A-Za-z ]).{5,20}$/)) {
alert("Need to enter a proper inquiry title containing only letter!");
}
Add the other_msg_subjparameter in the variable parameters only if others is selected.
var parameters = "......"; //Other parameters
if(inquiry_type == "others")
{
parameters = parameters + "&other_msg_subj="+inquiry_other_subj;
}
in PHP:
Check if only the parameter is present
else if(!isset($_POST['other_msg_subj']) && !preg_match ('%^[A-Za-z\.\' \-]{2,30}$%', $_POST['other_msg_subj']))
{
echo "Please enter a valid message subject title!";
exit();
}
Also (Just a suggestion) you can simplify the JQUERY code :
show/hide as toggle(true/false)
true = show(), false = hide()
$(function() {
$('#other_subj').hide();
$('#inquiry_type').change(function(){
var display = $('#inquiry_type').val() === 'others';
$('#other_subj').toggle(display);
});
});
First, you need to disable the input when it's hidden to prevent sending it's data to the server:
$(function() {
$('#other_subj').hide();
$('#inquiry_type').change(function(){
if($('#inquiry_type').val() === 'others') {
$('#other_msg_subj').prop('disabled', false);
$('#other_subj').show();
} else {
$('#other_msg_subj').prop('disabled', 'disabled');
$('#other_subj').hide();
}
});
});
And you need to do a check before validating:
On Javascript side:
else if (
$("#other_msg_subj").is(":visible") &&
!inquiry_other_subj.match(/^(?=.*[A-Za-z ]).{5,20}$/)) {
On PHP side:
else if(isset($_POST['other_msg_subj']) &&
!preg_match ('%^[A-Za-z\.\' \-]{2,30}$%', $_POST['other_msg_subj'])){
I've searched high and low for the answer to this but can't find it anywhere.
I have a form which has the HTML 'required' attributes and it does a fine job of highlighting the fields that need to filled in before submission...or would do, but the system which my form is bolted onto (of which I have no control over) submits the form anyway after a few seconds. It relies on Javascript for it's submission. Therefore I'd like to write a Javascript script to check all fields for a required attribute. Currently I have a script that specifies the fields I want to be mandatory, but if it could look up the attribute instead, that would be brilliant.
In case that input[type=submit] is used, you don't need any JavaScript
<form id="theForm" method="post" acion="">
<input type="firstname" value="" required />
<input type="lastname" value="" required />
<input type="submit" name="submit" value="Submit" />
</form>
Working jsBin
But if input[type=button] is used for submitting the form, use the snippet below
<form id="theForm" method="post" acion="">
<input type="firstname" value="" required />
<input type="lastname" value="" required />
<input type="button" name="button" value="Submit" />
</form>
window.onload = function () {
var form = document.getElementById('theForm');
form.button.onclick = function (){
for(var i=0; i < form.elements.length; i++){
if(form.elements[i].value === '' && form.elements[i].hasAttribute('required')){
alert('There are some required fields!');
return false;
}
}
form.submit();
};
};
Wotking jsBin
Many years later, here is a solution that uses some more modern Javascript:
for (const el of document.getElementById('form').querySelectorAll("[required]")) {
if (!el.reportValidity()) {
return;
}
}
See Vlad's comment for a link to the Constraint Validation API (thanks Vlad, that helped!)
You can use Constraint validation API, which is supported by most browsers.
I'm late to the party but this worked for me.
<input type="firstname" value="" required />
document.getElementById('theForm').reportValidity();
if (check) {
//success code here
return true;
}
Credit to Vlad and a.l.e for pointing me in the right direction with their previous answers. This is a simplified version of their approach.
this will be validating all your form field types
$('#submitbutton').click(function (e) {
e.preventDefault();
var form = document.getElementById("myForm");
var inputs = form.getElementsByTagName("input"), input = null, select = null, not_pass = false;
var selects = form.getElementsByTagName("select");
for(var i = 0, len = inputs.length; i < len; i++) {
input = inputs[i];
if(input.type == "hidden") {
continue;
}
if(input.type == "radio" && !input.checked) {
not_pass = true;
}
if(input.type == "radio" && input.checked){
not_pass = false;
break;
}
if(input.type == "text" && !input.value) {
not_pass = true;
}
if(input.type == "text" && input.value){
not_pass = false;
break;
}
if(input.type == "number" && !input.value) {
not_pass = true;
}
if(input.type == "number" && input.value){
not_pass = false;
break;
}
if(input.type == "email" && !input.value) {
not_pass = true;
}
if(input.type == "email" && input.value){
not_pass = false;
break;
}
if(input.type == "checkbox" && !input.checked) {
not_pass = true;
}
if(input.type == "checkbox" && input.checked) {
not_pass = false;
break;
}
}
for(var i = 0, len = selects.length; i < len; i++) {
select = selects[i];
if(!select.value) {
not_pass = true;
break;
}
}
if (not_pass) {
$("#req-message").show();//this div # in your form
return false;
} else {
//do something here
}
});
If using either the simple "required" solution above or the "Constraint Validation API" solution, how do you make a select option required if it is contingent on another select field having a certain answer. I used the "required" method as you can see below which works great for Country select.
<select id="country_code" name="country_code" required>
<option value="">--None--</option>
<option value="AL">Albania</option>
<option value="US">United States</option>
</select>
<script>
$("select[name='country_code']").change(function() {
if ($(this).val() == "US") {
$("select[name='state_code'] option").removeClass('hidden');
$("select[name='state_code'] option").addClass('required');
} else {
} else {
$("select[name='state_code'] option").addClass('hidden');
}
});
</script>
<label for="state_code">State/Province</label>
<select id="state_code" name="state_code">
<option value="">--None--</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
</select>
As you can see, I tried adding the class "required" to State select if Country select is US, but it didn't do anything.
I am having trouble displaying strings depending on the if/else statements in my validation.
If you look at the code below, if the if statement is met, then it displays the message which is fine, but then when I make sure the if statement is met and deliberately fail the else if statement, instead of displaying a message, it just displays a blank. Why is it not displaying a message for when else if statement is met in javascript validation below:
function editvalidation() {
var isDataValid = true;
var currentAssesO = document.getElementById("currentAssessment");
var noStudentsO = document.getElementById("addtextarea");
var studentAssesMsgO = document.getElementById("studentAlert");
studentAssesMsgO.innerHTML = "";
if (currentAssesO.value == ""){
$('#targetdiv').hide();
studentAssesMsgO.innerHTML = "Please Select an Assessment to edit from the Assessment Drop Down Menu";
isDataValid = false;
}else if (noStudentsO.value == ""){
$('#targetdiv').hide();
studentAssesMsgO.innerHTML = "You have not Selected any Students you wish to Add into Assessment";
isDataValid = false;
}
else{
studentAssesMsgO.innerHTML = "";
}
return isDataValid;
}
UPDATE:
HTML:
SELECT BOX (Options are appended into this box):
<select multiple="multiple" name="addtextarea" id="studentadd" size="10">
</select>
DROP DOWN MENU:
<select name="session" id="sessionsDrop">
<option value="">Please Select</option>
<option value='20'>EWYGC - 10-01-2013 - 09:00</option>
<option value='22'>WDFRK - 11-01-2013 - 10:05</option>
<option value='23'>XJJVS - 12-01-2013 - 10:00</option>
</select> </p>
ALERT MESSAGE:
<div id='studentAlert'></div>
Reuirements for validation:
If drop down menu is empty, then display message that assessment needs to be select from drop down menu in alert message div.
If drop down menu is not empty, then check to see if the select box contains any options, if select box contains no options, then replace div alert message stating no students have been selected to add to assessment
If drop down menu is not empty and select box is not empty (or in other words contains an option), then div alert message is just an empty string ""
Rephrase your JavaScript this way:
function editvalidation() {
var isDataValid = true;
var currentAssesO = document.getElementById("currentAssessment");
var noStudentsO = document.getElementById("addtextarea");
var studentAssesMsgO = document.getElementById("studentAlert");
var errorMsg = "";
studentAssesMsgO.innerHTML = "";
if (currentAssesO.value == "" || noStudentsO.value == "") {
$('#targetdiv').hide();
isDataValid = false;
if (currentAssesO.value == "") {
errorMsg += "Please Select an Assessment to edit from the Assessment Drop Down Menu";
}
if (noStudentsO.value == "") {
errorMsg += "You have not Selected any Students you wish to Add into Assessment";
}
studentAssesMsgO.innerHTML = errorMsg; // Plus whatever styling for messages.
}
return isDataValid;
}
Updated answer
Please include jQuery by putting this in the <head> section.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Update your script:
function editvalidation()
{
if ($("#sessionsDrop").val()=="")
$("#studentAlert").html("Assessment needs to be filled.");
if ($("#sessionsDrop").val()!="" && $("#studentadd").children().length==0)
$("#studentAlert").html("No students have been selected to add to assessment.");
if ($("#sessionsDrop").val()!="" && $("#studentadd").children().length!=0)
return true;
return false;
}
Here is the magic:
else {
studentAssesMsgO.innerHTML = "";
alert(noStudentsO.value); // tell me why I'm in this block
}