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>
Related
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>
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'])){
Hello I have a HTML form which already prompts users to fill empty fields. And this is the script that I am using:
<!-- Script to prompt users to fill in the empty fields -->
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function() {
var elements = document.getElementsByTagName("INPUT");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function(e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity("To continue, you must correctly fill in the missing fields.");
}
};
elements[i].oninput = function(e) {
e.target.setCustomValidity("");
};
}
});
</script>
This script works flawlesly and it brings up a nice prompt that looks like this:
It works for all the input text fields, but I need another script that will (a) check if at least one checkbox you can see at the bottom of the form is checked, and (b) will bring up a prompt which is styled the same way as the one above.
I looked at other posts and wrote the below script. I referenced checkboxes by their IDs and somehow used the function function(e) from the above script. Well it won't work for me but I must be close...
<!-- Script which prompts user to check at least one checkbox -->
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function() {
if (
document.getElementById("linux-c-arm-checkbox").checked == false &&
document.getElementById("linux-eda-cad-checkbox").checked == false &&
document.getElementById("linux-blender-checkbox").checked == false &&
document.getElementById("linux-photo-checkbox").checked == false &&
document.getElementById("linux-audio-checkbox").checked == false &&
document.getElementById("linux-latex-checkbox").checked == false &&
document.getElementById("linux-desktop-checkbox").checked == false &&
document.getElementById("linux-office-checkbox").checked == false
){
function(e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity("Please choose at least one checkbox.");
}
}
}
});
</script>
Can anyone help me solve this by using javascript without JQuery?
Though there is no way you can put required attribute on a checkbox group and do the validation for atleast one selection, here is a workaround solution. Do the changes accordingly on your HTML.
It takes a hidden textbox as the placeholder of the selected checkbox group. If atleast one is selected the hidden field will also have the value.
function setAccount() {
if (document.querySelectorAll('input[name="gender"]:checked').length > 0)
document.querySelector("#socialPlaceholder").value = document.querySelector('input[name="gender"]:checked').value;
else
document.querySelector("#socialPlaceholder").value = "";
}
function invalidMsg(textbox) {
if (textbox.value == '') {
textbox.setCustomValidity('Please select at least one account');
} else {
textbox.setCustomValidity('');
}
}
<form target="_blank">
<b>Accounts</b>
<input type="text" id="socialPlaceholder" required value="" style="width:0px;height:0px;position: relative;left:-30px;opacity: 0;" oninvalid="invalidMsg(this)"/><br/>
<label>Facebook<input type="checkbox" name="gender" value="facebook" onClick="setAccount()"/></label>
<label>Twitter<input type="checkbox" name="gender" value="twitter" onClick="setAccount()"/></label>
<label>Google Plus<input type="checkbox" name="gender" value="google_plus" onClick="setAccount()"/></label>
<label>Instagram<input type="checkbox" name="gender" value="instagram" onClick="setAccount()"/></label>
</br>
</br>
<input type="submit" value="Submit" />
<br/><br/>
NOTE: Submit without selecting any account to see the validation message
</form>
Your e is null, because you use self executing function inside if and does not pass any event for it.
Try changing e.target to document.getElementById("linux-office-checkbox") or other not-checked element.
In jQuery I would check if any checkbox is selected by doing $('.checkboxClass:checked').length > 0
I want to change what is written in the input tag depending on what was chosen in the select tag.
this is my select tag
<div class="form-group col-lg-4">
<label for="donationType">Donation Type: </label>
<select id="donationType" style="text-transform: capitalize"
name="volunteerProject.donationTypeId" class="form-control">
<option value='0'>Select Donation Type</option>
<s:iterator value="donationTypeList">
<option value='<s:property value="donationTypeId" />'
name='<s:property value="donationType" />'>
<s:property value="donationType" />
</option>
</s:iterator>
</select>
</div>
and this is my input tag
<div class="form-group col-lg-3" id="vpDonateButtonLabelDiv">
<label for="vpTitle">Button Label</label> <input
type="text" class="form-control" id="vpDonateButtonLabel"
name="volunteerProject.donateButtonLabel"
placeholder="Enter button label" maxlength="50" required />
</div>
and here's my javascript code
$('#donationType').change( function() {
var donationType = $(this).val();
if (donationType != 0) {
if (donationType == 1){
$("#vpDonateButtonLabelDiv").append('Donate');
} else if (donationType == 2) {
$("#vpDonateButtonLabelDiv").append('Volunteer');
} else if (donationType == 3) {
$("#vpDonateButtonLabelDiv").append('Share');
} else if (donationType == 5) {
$("#vpDonateButtonLabelDiv").append('Tweet');
}
} else {
$("#vpDonateButtonLabelDiv").append('');
}
});
However, it is not working. What did I miss here? or is my method wrong? Thanks a lot
You have to change the id that are you using and you have to change the append to val to change the value of the text..
$('#donationType').change( function() {
var donationType = $(this).val();
if (donationType != 0) {
if (donationType == 1){
$("#vpDonateButtonLabel").val('Donate');
} else if (donationType == 2) {
$("#vpDonateButtonLabel").val('Volunteer');
} else if (donationType == 3) {
$("#vpDonateButtonLabel").val('Share');
} else if (donationType == 5) {
$("#vpDonateButtonLabel").val('Tweet');
}
} else {
$("#vpDonateButtonLabel").val('');
}
});
for live demo click here
I see that you use jQuery already. You can replace $("#vpDonateButtonLabelDiv").append with $("#vpDonateButtonLabel").val in order to select the input and edit the value. See this fiddle https://fiddle.jshell.net/8odoros/mzL24b5x/
Try changing '.append' to '.value'?
Reference: Set the value of an input field
It's in javascript, but you get the idea.
Edit: Wrong selector, too. You should be changing the textbox, but your selector is your div.
try changing $("#vpDonateButtonLabelDiv").append('Donate'); to $("#vpDonateButtonLabel").val('Donate').
To change the input's text, you could do something like:
$('#donationType').change( function() {
var labels = ['', 'Donate', 'Volunteer', 'Share', 'Tweet' ]; //these could perhaps also be obtained from meta data?
$('#vpDonateButtonLabel').val(labels[$(this).val()]);
});
But I've got an inkling you want to change the label text? If so, this can be done by finding the generated label element within the div: $('#vpDonateButtonLabelDiv').children('label') and setting its text.
$('#donationType').change( function() {
var labels = ['', 'Donate', 'Volunteer', 'Share', 'Tweet' ]; //these could perhaps also be obtained from meta data?
$('#vpDonateButtonLabelDiv').children('label').text(labels[$(this).val()]);
});
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
}