This one seems really common question in StackOverflow. However, I am having difficulty in validating these textarea (Not to left blank) and checkboxes(At least one should be checked). I tried several validation Javascripts and frameworks but in vain.
I have textarea named "case_title0[]" whose will increase the number "0" to "1","2" and so on when user clicks "Add More" button. I want to validate at the point when user clicks the "Add More" button.
Secondly, I want the checkbox (name="editioncheck'+caseNum+'[]") which is dynamic as well to restrict user to leave it blank. The checkbox looks like "editioncheck0[]", "editioncheck1[]" and so on. It needs to be checked at least once to proceed to next "Add More" button. Until then "Add More" button should remain inactive.
So, I want these two type of validation in my form ie. textarea and checkbox.
Which is the simplest framework or custom code to use here?
I don't want fancy display as just alert() box should work in this regard.
Add common class to all textareas and common class to all checkboxes and perform validation.
<textarea class="t"></textarea>
<textarea class="t"></textarea>
<textarea class="t"></textarea>
<textarea class="t"></textarea>
<input type="checkbox" class="c">
function validate() {
var err = false;
$('.t').each(function(){
if($(this).text().length < 1) {
err = true;
return false;
}
});
if(!err) {
/* code to validate checkboxes like above */
}
return !err;
}
Finally, I have figured out the solution and I am going to post it here. As there is no exactly similar solution to my problem I had to code from scratch. While doing so lot of online resources helped me a lot.
To validate textarea on the fly (dynamic generate of text area when user clicks "Add More" button), here is solution I applied:
var csn='case_title'+caseno; //here "caseno" is incremental number to uniquely identify elements
var csum='case_summary'+caseno;
var caset=document.getElementById(csn).value;
var casesum=document.getElementById(csum).value;
if (caset == null || caset == "") {
alert("Executive Summary must be filled out");
caseNum --;
return false;
}
if (casesum == null || casesum == "") {
alert("Summaries with links must be filled out");
caseNum --;
return false;
Next, to validate the checkboxes I did as follows:
var edval='editioncheck'+caseno;
var checkBoxes=document.getElementsByClassName(edval);
var isChecked = false;
for (var i = 0; i < checkBoxes.length; i++) {
if ( checkBoxes[i].checked ) {
isChecked = true;
};
};
if ( isChecked ) {
//alert( 'At least one checkbox checked!' );
} else {
alert( 'Select at least one edition!' );
caseNum --;
return false;
}
The solution seems similar to the concept of fr34k, so thanks a lot. However, I found this online here http://jsfiddle.net/qyE97/
So, every time user click "Add More" button this script is executed and validates for the textarea and checkboxes.
Related
how to keep validation off if some section of forms not showing during form-filling in jquery. as
function formsubmit(){
var ammount = $('#ammount').val();
var emp_status = $("input[name='empstatus']:checked").val()?$("input[name='empstatus']:checked").val():'undefined';
var com_name = $('#com_name').val();
var ann_inc=$('#ann_inc').val();
var city=$('#city').val();
var emi_paid = $("input[name='emi_paid']:checked").val()?$("input[name='emi_paid']:checked").val():'undefined';
flag = true;
if (ammount.trim()=='') {
$('#msgammount').css('color','red');
$('#msgammount').text('Please Enter Price');
$('#msgammount').show();
return false;
}
if (emp_status == 'undefined') {
$('#msgempstatus').css('color','red');
$('#msgempstatus').text('Please Enter Price');
$('#msgempstatus').show();
return false;
}
if (emi_paid == 'undefined') {
alert('undefined');
return false;
}
}
I want to hide the error emi_paid section as some of the user not going to fill emi_details if they will not took any loan from bank, so i am using radio button if user has any existing loan then only emi option appear,
my code run well the only thing disappoint me to hide the emi_paid error, it will show always at the time of form submission.
Why not use validation js Like validate.js or jQuery.validationEngine v2.6.2.These validation are easy to use as well as these validation has a setting to turn on or off validation for hidden element according to your requirement.
Hidden validation for hidden elements in form submit
$.validator.setDefaults({
ignore: ":hidden"
});
I highly recommend your to use these.
I have a button that is created on each slide in a quiz game. Radio buttons containing the answer choices are appended from an object onto each slide as you cycle through the questions. I want to require that a radio button be clicked on before you can access the nextQuestion button. You can find the .append() on line 5 of the code below (inside of the loadQuestion function). What method would be the best way to achieve the desired result? If you need more of the code, let me know.
var loadQuestion = function (){
$('.question-name').html(name + (qnum) +"/"+ total);
$('.question').html(questions[count].question);
for(var i=0; i<questions[count].options.length; i++) {
$('.inputs').append('<input type="radio" name="question" value="'+questions[count].options[i]+'">'+questions[count].options[i]+'<br>')
}
};
/*--- First Question ---*/
var name = "Question ";
var qnum = 1;
var count = 0;
var total = questions.length;
loadQuestion();
/*--- When the Next Question Button is Hit ---*/
nextQuestion.click(function() {
$('.inputs').html("");
qnum++;
count++;
if (qnum <= 4) {
loadQuestion();
} else if (qnum == 6) {
$('.question-name').html("Your Score:");
$('.question').html("You got X out of 5 questions correct!");
nextQuestion.html("Home Screen").click(function() {
location.reload();
});
} else if (qnum == 5){
loadQuestion();
$('.next-question').html("Get Score!");
}
});
$(document).ready(function () {
$('#nextButton').attr('disabled', true);//disable the button by default on page load
$("input[type=checkbox]").on("click", function () {
if (this.length > 0) {
$('#nextButton').attr('disabled', false);//enable only when the checkbox is checked
}
});
});
I hope this helps!
Security note: Anybody can remove the disabled attribute from the button tag using developer tools in the browser. Use the backend to validate the checkbox value.
There's more than one way to go about this:
"Prevent button press until radio is selected"
From a ui/ux perspective your request raises the following question: "If the user isn't supposed to click on the button until the radio is selected, why is the button available for them to press before the radio is selected?" So, let's start there.
//pseudo-code - use delegate binding '.on()' for dynamically generated elements
$('.inputs').on('click', 'input[name="question"]', function({
if ($(this).is(':checked')) {
$('#nextButton').attr('disabled', false);
} else {
$('#nextButton').attr('disabled', true);
} /*... snip ...*/
}));
Or, you could generate the nextButton after an answer is selected much in the same way that you are currently generating the radio button - just remember to use delegate event binding. This is probably the "better way" because as has already been pointed out by #zadd, the disabled property can be circumvented.
Without reinventing the wheel, you could also just check to see if there's a radio selected when the button is pressed.
// pseudo-code again
nextQuestion.click(function() {
if($('input[name="question"]:checked').length > 0){
// checked!!! go do stuff!!!
} else {
// not checked! i should probably throw an alert or something...
alert('please answer the question before proceeding...');
}
});
I have an image that is kind of a spinner that is displayed to a user on submitting a form.
So in js.coffe I do something like this:
$('.button.save-btn.btn.btn-primary').click ->
$('.loader').show()
And if the form fails validations and an error is shown, at that time I hide the same image, like this:
$('#error-box').show();
$('.loader').hide();
The spinner works fine when an error is encountered but now what if when the user is clicking on the submit button when the form is empty. How do I handle that event? Where exactly do I hide the spinner image in this case?
I hope I explained my query properly, any help will be much appreciated. Thanx in advance:)
I don't use coffee personally but in plain js you could check if the fields have a value before showing the spinning image:
$('.button.save-btn.btn.btn-primary').click(function(){
var form_compiled = false;
//iterate trough each input field
$("#MyformID").find("input, textarea").each(function(){
//check if input field has a value or is empty
if ($(this).val() != ""){
form_compiled = true;
}
})
// and then show the image if at least a filed is filled
if ( form_compiled == true){
$('.loader').show()
}
})
the code above works if the user fills at leas a field.
If you want to run the check on just some mandatory fields you could add them the class "required", for example, then run the js check on those classes:
$('.button.save-btn.btn.btn-primary').click(function(){
var form_compiled = true; << change initialization
$("#MyformID").find(".required").each(function(){
//check if input field is empty
if ($(this).val() == ""){
form_compiled = false; //set to false is a required field is empty
}
})
if ( form_compiled == true){
$('.loader').show()
}
})
I want to set the focus in a single textbox and some text must be entered in the textbox to move the focus out of it. But there is an exception that I should be able click on the buttons on the page without any entry in that textbox.
Here is what I have done using JavaScript...
function Validate() {
var field1 = document.getElementById('<%=textbox.ClientID %>').value;
if (field1 == "") {
alert("Please Enter some value");
document.getElementById('<%=textbox.ClientID %>').focus();
return false;
}
else {
return true;
}
}
And I have called it like...
onblur="return Validate();"
This is the Script. (jquery required)
$(function() {
$('input[id=word]').blur(function() {
var txtClone = $(this).val();
if(txtClone=="")$(this).focus();
});
});
and here is a html tag
<input type='text' id='word' name='word'>
As you've asked, focus won't move away unless you entered some text and able to click on button outside.
I need to change the back button functionality of my phonegap project, which I've succeeded in doing without any problem. The only issue now, is that I need to further change the functionality based on if the user has a certain field selected.
Basically, if the user has clicked in a field with the id of "date-selector1", I need to completely disable the back button.
I was attempting to use document.activeElement, but it only returns the type of the element (input in this case), but I still want the functionality to work when they are in a general input, but not when they are in an input of a specific id.
EDIT
I tried all of the suggestions below, and have ended up with the following code, but still no success.
function pluginDeviceReady() {
document.addEventListener("backbutton", onBackKeyDown, false);
}
function onBackKeyDown() {
var sElement = document.activeElement;
var isBadElement = false;
var eList = ['procedure-date', 'immunization-date', 'lab-test-done', 'condition-onset', 'condition-resolution', 'medication-start-date', 'medication-stop-date', 'reaction-date'];
console.log("[[ACTIVE ELEMENT: --> " + document.activeElement + "]]");
for (var i = 0;i < eList.length - 1;i++) {
if (sElement == $(eList[i])[0]) {
isBadElement = true;
}
}
if (isBadElement) {
console.log('Back button not allowed here');
} else if ($.mobile.activePage.is('#main') || $.mobile.activePage.is('#family') || $.mobile.activePage.is('#login')) {
navigator.app.exitApp();
} else {
navigator.app.backHistory();
}
}
if you're listening for the back button you can add this if statement:
if (document.activeElement == $("#date-selector1")[0]) {
/*disable button here, return false etc...*/
}
or even better (Thanks to Jonathan Sampson)
if (document.activeElement.id === "date-selector1") {
/*disable button here, return false etc...*/
}
You can have a flag set when a user clicks on a field or you can have a click event (or any other type of event) when a user clicks on the field that should disable the back button.
From the documentation it looks like for the specific page that the backbuton is conditional on you can drop back-btn=true removing that back button.
http://jquerymobile.com/test/docs/toolbars/docs-headers.html
If you need complex conditional functionality you can just create your own button in the header or footer, style it using jquery-mobile widgets and implement your own click functionality.