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
}
Related
I'm trying to use this to create a message that states "Please enter a number" when you hit submit on a form and there's no number in the input for "If you would like to state a specific amount type it in the box below". It's doing absolutely nothing, so I don't know what's going on. I'm still in school and this is my first class with JavaScript so I would appreciate any help you can give.
Here is the JavaScript portion:
```
// test page form exception code - Chapter 4
function verifyFormCompleteness() {
var specificAmountBox = document.getElementById("specificamount");
var completeEntry = true;
var messageElement = document.getElementById("message");
var messageHeadElement = document.getElementById("messageHead");
var validity = true;
var messageText = "";
try {
if (specificAmountBox.value == "" || specificAmountBox.value == null){
window.alert = "Please enter a number in the specific amount box";
}
}
catch(message) {
validity = false;
messageText = message;
specificAmountBox.value = ""; // removes bad entry from input box
}
finally {
completeEntry
messageElement.innerHTML = messageText;
messageHeadElement.innerHTML = "";
alert("This is happening in the finally block");
}
if (validity = true) {
return submit;
}
}
```
Here is the HTML portion:
```If you would like to state a specific amount type it in the box below:<br>
<input type="number" id="specificamount" name="specificamount">
<h1 id="messageHead"></h1>
<p id="message"></p>
<br>
<br>
```
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 simple form with a couple of dropdowns a multi-select and an editor.
The dropdowns both have an initial item which has a text value of Please Select and a value of ''. On submission I have the following bit of Javascript/JQuery that checks that I have values in my dropdowns, multi-select and editor.
var validFlag = true;
var dropdownlist = $("#addNew_dTeam").data("kendoDropDownList");
if (dropdownlist.value() == "") {
validFlag = false;
errorMsg = "<li>Select Team</li>"
}
dropdownlist = $("#addNew_dType").data("kendoDropDownList");
if (dropdownlist.value() == "") {
validFlag = false;
errorMsg += "<li>Select Entry Type</li>"
}
var multiSelect = $("#msServers").data("kendoMultiSelect");
if (multiSelect.value() == "") {
validFlag = false;
errorMsg += "<li>Add at least one Server or select N/A</li>"
}
var editor = $("#diaryComments").data("kendoEditor");
if (editor.value() == "") {
validFlag = false;
errorMsg += "<li>A comment is mandatory</li>"
}
The code works fine for the dropdowns and multi-select, but the check for empty editor content does not work. My editor is empty yet the if (editor.value() == "") is not true.
While editor is empty, consider one blank space so your condition will be like if (editor.value() == ' ') (there is one space between single quote)...
Demo
hope so it will work for you...
Hi i have a html list item thats hidden by default on the page that contains a date picker:
<li id="hiddenListItem" style="display:none;">
<label for="returning">Returning:</label>
<input type="text" id="returning" required/>
<span class="form_hint">Proper format "12/04/2014"</span>
</li>
If the user selects that they want a return journey then the list item is made visible:
<script>
function needReturn() {
var item = document.getElementById("hiddenListItem");
item.style.display = 'list-item';
}</script>
<script>
function dontNeedReturn() {
var item = document.getElementById("hiddenListItem");
item.style.display = 'none';
}</script>
If the user click continue button then external .js file validates the form, but if they don't need a return ticket then browser displays message saying please fill in this information.
I was hoping to determine the state of the listitem style and if it was visible then show the warning else continue:
else if (returning === "")
{
var item = document.getElementById("hiddenListItem");
if(item.style.display === "list-item")
{
alert("Please enter a return date.");
}
}
I cant get the above statement to work, any help please.
HTML and JS is not my thing.
This should work:
if (item.style.display !== 'none') {
alert("Please enter a return date.");
}
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";
}
}