I'm trying to make sure every field is required but this code only works on "input" tags but not on the select and textarea tags.
Any help will be appreciated. Thanks!
HERE IS MY BLADE
<div class="tab">
<div class="form-group mb-3">
<select name="currency" class="choices form-control" id="devise{{ Auth::user()->cred->id }}"
onchange="deviseSelect({{ Auth::user()->cred->id }})" required="true">
<option value="" selected disabled>choose</option>
<option value="USD">USD</option>
<option value="FC">FC</option>
</select>
</div>
</div>
HERE IS MY JAVASCRIPT FOR THE "SELECT" HTML TAG
<script>
var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab
function validateSelect()
{
// This function deals with validation of the form fields
var x,z, i, valid = true;
x = document.getElementsByClassName("tab");
z = x[currentTab].getElementsByTagName("select");
// A loop that checks every select field in the current tab:
for (i = 0; i < z.length; i++) {
var option = z.options[i];
// If a field is empty...
if (option.value == "") {
// add an "invalid" class to the field:
z[i].className += " required";
// and set the current valid status to false:
valid = false;
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
</script>
I FOUND WHERE I'VE MISTAKEN
I just changed something inside the for loop and everything started working perfectly.
<script>
for (i = 0; i < z.length; i++) {
// If a field is empty...
if (z[i].value == "") {
// add an "invalid" class to the field:
z[i].className += " is-invalid";
// and set the current valid status to false:
valid = false;
}
}
</script>
Related
Hello I am new to javascript and all these html and stuff. I have the following code from w3schools that validates the input fields. I have html input fields that are like this.
<div id="employed" style="display:none;">
<p><input placeholder="Name Of The Organization / Institution ..." name="organization"></p>
<p><input placeholder="Designation ..." name="desig"></p>
<p><input placeholder="Place Of Work ..." name="workplace"></p>
<p><input placeholder="Communication Address ..." name="cadd"></p>
<p><input placeholder="E_mail ID ..." name="offemail"></p>
<p><input placeholder="Contact Number ..." name="contact"></p>
</div>
I have a javascript that shows the hidden field when user selects radio buttons.
But when I click next it validates the fields even if they are hidden.
The javascript for validation is this.
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].value == "") {
// add an "invalid" class to the field:
y[i].className += " invalid";
// and set the current valid status to false
//valid = false;
(y[i].style.display == "none")?valid = true:valid = false;
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
Please I am learning right now and I am stuck here. Thanks in advance!
Because the input dom is still avaiable in your document and it's just hidden only. To prevent your validation validates the hidden input. change your code to this.
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].value == "" && y[i].parentElement.style.display != 'none') {
// add an "invalid" class to the field:
y[i].className += " invalid";
// and set the current valid status to false
//valid = false;
(y[i].style.display == "none")?valid = true:valid = false;
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
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'm building a tabbed for using a mixture of JavaScript and CSS. So far I have validation on my text inputs that ensure a user can't progress unless data has been input.
I have got it working so that my script detected unchecked radios, but the problem is that I want the user to only select one. At the moment even when one gets selected the script won't let you progress because it's seeing the other three as unchecked. How could I add a rule to look at the radios and set valid = true if one is selected - if more or less than 1 then fail?
my function:
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].type === "text") {
if (y[i].value == "") {
// add an "invalid" class to the field:
y[i].classList.add('invalid');
// and set the current valid status to false:
valid = false;
} else if (!y[i].value == "") {
y[i].classList.remove('invalid');
valid = true;
}
}
if (y[i].type === 'radio') {
//y[i].classList.remove('invalid');
//valid = true;
if (!y[i].checked) {
y[i].classList.add('invalid');
valid = false;
} else {
y[i].classList.remove('invalid');
valid = true;
}
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
Do I need to split the validation down into further functions to separate validating different field types?
I think that radio buttons are the way to go. Especially from a UI point of view. Why would you let the user pick more than one item only to tell them later they can't?
Having said that, you can do what you're trying to do with something like this:
function validateForm() {
var checkBoxHolders = document.querySelectorAll(".checkboxholder");
var valid = true;
for (var i = 0; i < checkBoxHolders.length; i++) {
var numChecked = checkBoxHolders[i].querySelectorAll("input[type='checkbox']:checked").length;
if (numChecked === 1) {
checkBoxHolders[i].classList.remove('invalid');
} else {
checkBoxHolders[i].classList.add('invalid');
}
valid = valid && numChecked === 1;
}
document.getElementById('valid').innerHTML = 'I am valid: ' + valid;
}
.invalid {
background-color: orange;
}
<input type="text" id='foo'>
<input type="text" id='bar'>
<div class='checkboxholder'>
First group
<input type="checkbox" id='check1'>
<input type="checkbox" id='check2'>
</div>
<div class='checkboxholder'>
Second group
<input type="checkbox" id='check3'>
<input type="checkbox" id='check4'>
</div>
<button type='button' onclick='validateForm()'>Validate me</button>
<div id='valid'>
</div>
With jQuery, it'd be something like:
if (jQuery('input[name=RadiosGroupName]:checked').length === 0) {
valid = false;
}
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
}
Haven't been around in a while. Got a hot project I'm working on and I can't seem to figure out how to disable an input text field. The situation is that I have a form that is filled out and then when it is submitted I leave the form where it is but disable the input fields so it can't be changed. So the user can continue to see what they have submitted.
<html>
<head>
<script>
function enableDisable() {
var disable = true;
var arglen = arguments.length;
var startIndex = 0;
var frm = document.example1; //change appropriate form name
if (arglen > 0){
if (typeof arguments[0] == "boolean") {
disable = arguments[0];
if (arglen > 1) {
startIndex = 1;
}
}
for (var i = startIndex; i < arglen; i++) {
obj = eval("frm." + arguments[i]);
if (typeof obj=="object") {
if (document.layers) {
if (disable) {
obj.onfocus = new Function("this.blur()");
if (obj.type == "text") {
obj.onchange = new Function("this.value=this.defaultValue");
}
}
else {
obj.onfocus = new Function("return");
if (obj.type == "text") {
obj.onchange = new Function("return");
}
}
}
else {
obj.disabled=disable;
}
}
}
}
}
</script>
</head>
<body>
<form name="example1">
Text Field: <input type="text" name="text1">
<br>
<input type="submit" name="control1" onclick="enableDisable(this.submit, 'text1', 'submit', 'select1')">
</form>
</body>
</html>
I think you want the text field to be a read only field.
there is a difference between a disabled text field and a read only text field.
READONLY and DISABLED both remove the functionality of the input field, but to different degrees. READONLY locks the field: the user cannot change the value. DISABLED does the same thing but takes it further: the user cannot use the field in any way, not to highlight the text for copying, not to select the checkbox, not to submit the form. In fact, a disabled field is not even sent if the form is submitted.
So you should look into this post for more info regarding the same.
http://www.htmlcodetutorial.com/forms/_INPUT_DISABLED.html