I'm trying to build a server control that has a radiobuttonlist with 2 items and a textbox.
THe radio buttons are YES en NO options.
When YES is selected I want the textbox to be visible and it must be required to fill in.
On NO, the textbox becomes invisible.
I manages to get the textbox to appear and disappear based on the option choice.
But how do I add validation to the textbox and remove it when not visible?
I have tried it with the ASP validators, but the jquery doesn't disable them when the textbox is not visible.
I tried something like this, but it is not working:
<script type="text/javascript">
$(function()
{
$('#TravelOption2_rbList').change(function()
{
var index = $('#TravelOption2_rbList input[type=radio]:checked').val();
if (index != '0')
{
$('#TravelOption2_lblName2').css({'visibility':'visible'});
$('#TravelOption2_txtName1').css({'visibility':'visible'});
$('#TravelOption2_lblName3').css({'visibility':'visible'});
// create validator (not working)
$('#TravelOption2_txtName1').rules('add', {
required: true,
minlength: 2,
messages: { required: 'Required input', minlength: 'Please enter the cost.' }
});
} else {
$('#TravelOption2_lblName2').css({'visibility':'hidden'});
$('#TravelOption2_txtName1').css({'visibility':'hidden'});
$('#TravelOption2_lblName3').css({'visibility':'hidden'});
// remove the validator here
}
});
});
</script>
I have seen a lot of examples but they are not working for me.
Would it not be easier to simply check if the textbox has at least 2 characters in it when you submit it's contents? I'm assuming this is some sort of input form.
<script type="text/javascript">
$(function() {
$('#submitButton').on('click', function(){
if ($('#TravelOption2_txtName1').val().length > 1 ) {
//Textbox has at least 2 characters in it
}
})
});
</script>
This article helped me solve this problem.
Enable-Disable-ASPNet-Validator-Client-Side-Validation-using-JavaScript-or-jQuery
Related
I've 3 different options (artigo, revista, livro)
Each one has a unique form, some with required fields others not
I have to choose only one option, fill the respective form and submit.
The problem is that it doesnt let me submit because there are others required fields in the other divs.
What I want is if I select tipo_artigo1 it sets tipo_livro as not required so I can finally submit the final form.
I already have this code
<script>
$(".js-select2").each(function(){
$(this).select2({
minimumResultsForSearch: 20,
dropdownParent: $(this).next('.dropDownSelect2')
});
$(".js-select2").each(function(){
$(this).on('select2:close', function (e){
if($(this).val() == "tipo_artigo1") {
$('.tipo_artigo').slideDown();
$('.tipo_livro').slideUp();
$('.tipo_revista').slideUp();
}
else if($(this).val() == "tipo_revista2"){
$('.tipo_artigo').slideUp();
$('.tipo_livro').slideUp();
$('.tipo_revista').slideDown();
}
else if($(this).val() == "tipo_livro3"){
$('.tipo_artigo').slideUp();
$('.tipo_revista').slideUp();
$('.tipo_livro').slideDown();
}
});
});
})
</script>
Hopefully, I explained explicitly. Sorry for any grammatical mistakes
You can set the required attribute of an element thanks to $.fn.prop:
if ($(this).val() == "tipo_artigo1") {
// other code
// Unrequires all <.tipo_livro> elements.
$('.tipo_livro').prop('required', false);
}
But since .tipo_livro is a <div>:
if ($(this).val() == "tipo_artigo1") {
// other code
// Unrequires all <div.tipo_livro> sub-elements which are required.
$('.tipo_livro').find('[required]').prop('required', false);
}
If you have the id's of the fields you want to mark as not required, you can use :
$('#input_field').removeAttr('required');
Could you please anyone have done input masking on text box like xxx-xx-6789.
one text and one check box.
If checked on checkbox then apply masking like (xxx-xx-6789).
If Unchecked on checkbox then remove masking like (123-45-6789).
and both case actual value will be 123456789 (for save).
https://github.com/mishraas/jQuery-SSN-Field-Masking
Add one check box as below
<input type="checkbox" name="MaskUnmask" value="MaskUnmask" class="maskunmask"/>
and add change function in javascript as below it will work
<script type="text/javascript">
$(document).ready(function(){
$('#ssn').unmask().maskSSN('999-99-9999', { maskedChar: 'X', maskedCharsLength: 5 });
$(".maskunmask").on("change", function () {
if ($(this).prop('checked')) {
$('#ssn').unmask().mask('999-99-9999');
}
else {
$('#ssn').unmask().maskSSN('999-99-9999', { maskedChar: 'X', maskedCharsLength: 5 });
}
});
});
</script>
To get the value of unmask input text box, use the mask format '999999999'.
var val = $('#ssn').mask('999999999').val();
Try the following, in following mask format applied and removed in checkbox event.
$('#ssn').unmask().maskSSN('999-99-9999', {maskedChar:'X', maskedCharsLength:5});
$("#check").change(function(){
var val = $('#ssn').mask('999999999').val();
if ($(this).prop('checked')) {
$('#ssn').unmask().mask('999-99-9999');
}
else {
$('#ssn').unmask().maskSSN('999-99-9999', { maskedChar: 'X', maskedCharsLength: 5 });
}
alert(val);
});
I'm pretty sure there is a simple way to solve this but of course being a complete newbie to JS, I couldn't find the solution for this.
Currently my code has an autocomplete call to ajax to get search results, like this :
<input type="text" id="search" name="search">
....
<button type="submit" class="button large" id="programsearch">Search</button>
$('#search').autocomplete({
source: '/ajax-get-data',
minLength: 3,
autoFocus: true,
delay: 100
});
$( "#search" ).on( "autocompletechange", function( event, ui ) {
if (! ui.item) {
$(this).val('').attr('placeholder','try again - choose from the list');
}
});
So if you don't select from the list and click the search button, the input clears out into an empty field and the validator will see it as empty and will throw an error. However, if you type something and you get a drop down list but you don't select from the list, when you hit the enter key, it will submit. How can I tie in a condition where if nothing from the list has been selected (but there is a value in the input field) that the enter key will be disabled? I tried to tie in a .keypress() function but it mostly disables the enter key entirely.
This might not be the easiest or most efficient way of doing it - but it should get the job done. I used two global variables, one to track the last value of the search field, and one to track whether an option was chosen. If the value of the search field is changed, then an option is obviously not chosen. The form will only submit when the option was chosen from the list, and the placeholder text will inform the user if they did not select an option when the box loses focus (hence the blur event).
http://jsfiddle.net/Lu5811qt/1/
var submit = false;
var lastVal = $('#search').val();
$('#search').autocomplete({
source: ['asp', 'jsp', 'javascript', 'php', 'python', 'ruby', 'mysql'],
minLength: 1,
autoFocus: true,
delay: 100,
select:function(e, ui){
submit = true;
}
}).on('keydown', function(){
if(lastVal != $(this).val()){
submit = false;
}
lastVal == $(this).val();
}).on('blur', function(){
if(!submit){
$(this).val('').attr('placeholder','try again - choose from the list');
}
});;
$('#submit').on('click', function(e){
if(submit){
alert('submitting');
}
else{
alert('cannot submit, please choose an autocomplete option');
e.preventDefault();
}
});
Edit: I also wanted to mention - you shouldn't rely solely on this. Because it's JS, the client could do some funny things with dev tools. Be sure to verify it on the server as well.
I design my HTML selectbox using bootstrap select plugin. Now, i add jQueryvalidation Plugin for validate my form But, Validation form not work with bootstrap select plugin.
DEMO HERE
HTML:
<form id="myform">
<select name="year" class="selectpicker">
<option value="">Year</option>
<option value="1">1955</option>
<option value="2">1956</option>
</select>
<br/>
<input type="submit" />
</form>
JS:
$(document).ready(function () {
$('select').selectpicker();
$('#myform').validate({ // initialize the plugin
rules: {
year: {
required: true,
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
NOTE: For check this conflict, remove Line 2 from JS, jQuery Validation Worked.
EDIT: adeneo Fix Problem Using ignore[] method : FIDDLE
$('#myform').validate({ // initialize the plugin
ignore: [],
rules: {
year: {
required: true
}
},
errorPlacement: function(error, element) {
if (element.attr("name") == "year") {
error.insertAfter(".bootstrap-select");
} else {
error.insertAfter(element);
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
Now This Worked but I have New Problem: In normal Validation after select fields, error message This field is required auto Hide( OR with add any css, show success message) but Now, error message is show after fix required field. in act: when we choose years, error message not hide.
How do fix This?
The select plugin hides the original select and creates a new one with an unordered list that updates the hidden selects value, but hidden elements are not validated by default by the validation plugin, you have to use the ignore rule and turn on validation for hidden elements
$('#myform').data("validator").settings.ignore = "";
FIDDLE
or
$('#myform').validate({ // initialize the plugin
ignore: [],
rules: {
year: {
required: true
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
FIDDLE
The Bootstrap select plugin creates a new dropdown from an unordered list, and the original select is hidden and it's value is updated when the user interacts with the unordered list.
This has the disadvantange of also moving the error message, as the original, now hidden select is the element being validated, and the new visible dropdown made up of an unordered list is inserted by Bootstrap below the original select in the DOM, the error message is inserted after the original select, but before the unordered list, so it appears above the custom dropdown, not below it like it would if the original select was used.
To fix it you can move the error message for any given element rather easily
$('#myform').validate({ // initialize the plugin
ignore: [],
rules: {
year: {
required: true
}
},
errorPlacement: function(error, element) {
if (element.attr("name") == "year") {
error.insertAfter(".bootstrap-select");
} else {
error.insertAfter(element);
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
FIDDLE
I had a similar issue so here's how I kind of extended #adeneo's answer together with lessons learnt from (the post here).
Note: For those who bump into this post, please read #adeneo's answer and
(the post here) to understand the scope of this solution.
The resulting code that very well functions flawlessly for me looks as follows:
jQuery / javascript:
$(document).ready(function() {
$.validator.setDefaults({
/*OBSERVATION (1): note the options used for "ignore"*/
ignore: ':not(select:hidden, input:visible, textarea:visible)',
/*...other options omitted to focus on the OP...*/
errorPlacement: function (error, element) {
/*OBSERVATION (2): note how selection is on the class "selectpicker"*/
if (element.hasClass('selectpicker')) {
error.insertAfter('.bootstrap-select');
} else {
error.insertAfter(element);
}
/*Add other (if...else...) conditions depending on your
* validation styling requirements*/
}
});
$('#myform').validate({
rules: {
'year': {
required: true
}
},
messages: {
'year': {
required: 'Please select a year from the dropdown'
}
}
});
});
HTML:
<form id="myform">
<select name="year" class="selectpicker">
<option value="">Year</option>
<option value="1">1955</option>
<option value="2">1956</option>
</select><br/>
<input type="submit" />
</form>
Explanation:
OBSERVATION (1): ignore: ':not(select:hidden, input:visible, textarea:visible)' simply means to ignore validation for all elements that's not a hidden <select>, that's not a visible <input> and that's not a visible <textarea>.
In simpler English, it just says to validate hidden <select>, ignore hidden <input> and ignore hidden <textarea> which is what we usually want in many cases. This I think is a better way to target what validation should be ignored or not.
Based on #Alvin Lee's answer here, setting the ignore options on the form element as follows was ok, but had its caveats;
$('#myform').validate().settings.ignore =
':not(select:hidden, input:visible, textarea:visible)';
The Problem: The bootstrap select element got validated but showed the default message This field is required on every other input element instead of overriding it with all the custom validation messages that were previously configured.
The fix: move the ignore setting into $.validator.setDefaults({...}) block... Voila! ! !
OBSERVATION (2):
Instead of doing if (element.attr("name") == "year") {...} like #adeneo pointed, I rather decided to select on class='selectpicker'... then in the javascript, check if the element had this class by doing if (element.hasClass('selectpicker')) {...}. This just ensures that this rule can be applied to all bootstrap-select elements as long as they're decorated with the class selectpicker.
Hope this is clear enough and helpful to somebody who has similar issues!
If you use 'selectpicker' class to initialize bootstrap-select widget, I recommend to partially solve the issue via changing default ignore settings for jquery validate:
$.validator.setDefaults({ ignore: ':hidden:not(.selectpicker)' });
before you validate your form. This is a bit better approach, and you also need to move error messages as adeneo supposed.
And still it will not have a similar validation behavior as select would have. The problem arise when the parent container is hidden. In case you do not use bootstrap-select your select will not validate when container is hidden, but when you use it still validates.
Im using a simple form with a textarea, when the users clicks onto the textarea I want the contents of the textarea to be cleared.
Is this possible?
$('textarea#someTextarea').focus(function() {
$(this).val('');
});
If you only want to delete the default text (if it exists), try this:
$("textarea").focus(function() {
if( $(this).val() == "Default Text" ) {
$(this).val("");
}
});
By testing for the default text, you will not clear user entered text if they return to the textarea.
If you want to reinsert the default text after they leave (if they do not input any text), do this:
$("textarea").blur(function() {
if( $(this).val() == "" ) {
$(this).val("Default Text");
}
});
Of course, the above examples assume you begin with the following markup:
<textarea>Default Text</textarea>
If you want to use placeholder text semantically you can use the new HTML5 property:
<textarea placeholder="Default Text"></textarea>
Although this will only be supported in capable browsers. But it has the added advantage of not submitting the placeholder text on form submission.
My suggestion is that you only remove the initial default content on the first focus. On subsequent focuses, you risk removing user content. To achieve this, simply .unbind() the focus handler after the first click:
$("textarea").focus(function(event) {
// Erase text from inside textarea
$(this).text("");
// Disable text erase
$(this).unbind(event);
});
jsFiddle example
As a note, since you are using a textarea which has open and closing tags, you can can use $(this).text(""); or $(this).html("");... and, since the text inside a textarea is its value you can also use $(this).val(""); and $(this).attr("value", ""); or even this.value = "";.
HTML5 offers a more elegant solution to this problem: the "placeholder" attribute.
It'll create a text in background of your textarea which will appear only when the textarea is empty.
<textarea placeholder="Enter some text !"></textarea>
There are a couple of issues here that are only partially addressed in the current answers:
You need to clear the text when the user focuses the field
You only want to clear it the first time the user clicks on the field
You do not want the user to be able to submit the default text before it's been cleared
You might want to allow the user to submit the default text if they decide to type it back in. I have no idea why they'd want to do this, but if they insist on typing it back in, then I lean toward letting them do it.
With these details in mind, I'd add a class named "placeholder" to the field and use something like the following:
$("form textarea.placeholder").focus(function(e) {
$(this).text("");
$(this).removeClass("placeholder");
$(this).unbind(e);
});
Validate that the "placeholder" class name was removed when the form is submitted to guarantee that the user really, really wants to submit some stupid placeholder text.
If you're using the jQuery Validation Plugin, then you can put it all together like this:
$.validator.addMethod("isCustom", function(value, element) {
return !$(element).hasClass("placeholder");
});
$(form).validate({
rules: {
message: {
required: true,
isCustom: true
}
},
messages: {
message: "Message required, fool!"
},
submitHandler: function(form) {
$(form).find(":submit").attr("disabled", "disabled");
form.submit();
}
});
jQuery(function($){
$("textarea").focus(function(){
$(this).val("");
});
});
Something like this?
$('textarea#myTextarea').focus(function() {
if ($(this).val() == 'default text') {
$(this).val('');
}
});
<textarea type="text" onblur="if ($(this).attr('value') == '') {$(this).val('The Default Text');}" onfocus="if ($(this).attr('value') == 'The Default Text') {$(this).val('');}">The Default Text</textarea>
I found that simply
$('#myForm textarea').val('');
clears the form in Chrome but this did not work for Firefox (6.x). The value was empty in Firebug but the previous text still showed in the textarea. To get around this I select and rebuild the textareas one at a time:
$('#' + formId + ' textarea').each(function(i){
textareaVal = $(this).parent().html();
$(this).parent().html(textareaVal);
});
This finishes the job in Firefox and does not break Chrome. It will go through all of the textareas in a form one by one. Works in all other browsers (Opera, Safari, even IE).
This is possible and i think you are going for a code that can do this for more textareas than one...
This is what i use for my site:
Javascript:
<script type='text/javascript'>
function RemoveText(NameEle)
{
if ($('#' + NameEle) == 'default')
{
$('#' + NameEle).val('');
$('#' + NameEle).text('');
$('#' + NameEle).html('');
}
}
function AddText(NameEle)
{
if ($('#' + NameEle) == '')
{
$('#' + NameEle).val('default');
$('#' + NameEle).text('default');
$('#' + NameEle).html('default');
}
}
</script>
HTML:
<textarea cols='50' rows='3' onfocus='RemoveText(this)' onblur='AddText(this)' name='name' id='id'>default</textarea>