I have 2 text inputs which are related to each other and I need to validate once user tabs out of both the input text fields. This is a snapshot:
And the HTML counterpart:
<div class="four float_left field_div_wrapper">
<div class="padding_5">
<div class="field_title">
Telephon rumah
</div>
<div class="twelve height_30 land_phone_div">
<input type="text" id="telephon_rumah_field_1" class="three land_phone_field_1 land_phone_field">
<input type="text" id="telephon_rumah_field_2" class="eight land_phone_field_2 land_phone_field">
</div>
<div class="twelve float_left clear_left red_text display_hidden error_div_text">
This field must be numeric with 3 to 4 and 7 to 8 digits
</div>
</div>
</div>
My javascript code for validating the 2 text fields of land phone:
function performLandPhoneValidationOnDiv(landphoneDiv) {
var landPhoneValid = true;
// Here we consider both fields (code of area and office / home phone numbers) for validation if they are non-empty
// If both the fields are empty then it is a valid entry!
var areaCodeField = $(landphoneDiv).find(".land_phone_field_1");
var phoneField = $(landphoneDiv).find(".land_phone_field_2");
// We need to check current focus and perform validations only if both the text fields do not have focus currently
// http://stackoverflow.com/a/2684561/260665
// var phoneFieldsHasFocus = $(areaCodeField).is(":focus") || $(phoneField).is(":focus");
var phoneFieldsHasFocus = $(landphoneDiv).is(":focus");
if (!phoneFieldsHasFocus) {
.
.
.
// Internal validation to check if both the fields (area & phone) has valid data
}
return landPhoneValid;
}
And the code which triggers this validation is blur: (I have also tried focusout)
$(".land_phone_field").blur(function () {
performLandPhoneValidationOnDiv($(this).closest(".land_phone_div"));
});
Problem: As you can see in the first image, as soon as I tab out from first field, validation is triggered even before user attempts to enter something in the second section of the phone field.
To avoid this I have tried the following in the performLandPhoneValidationOnDiv callback after the event is triggered:
var phoneFieldsHasFocus = $(areaCodeField).is(":focus") || $(phoneField).is(":focus");
And:
var phoneFieldsHasFocus = $(landphoneDiv).is(":focus");
Both return false as result. I suspect this is so because the blur / focusout event is triggered as soon as I tab out and even before any other element gains focus. For the same reason I tried to see if the parent contains focus in the interim by any chance, it seems not to be the case.
I can handle this situation by using booleans and set the state when user tabs out of both the fields to perform validation, but it would not be a clean solution and I want to know the best way to handle such situations.
Related
I want to show message required when user don't set a choice.
This is my code:
var options = document.querySelectorAll('.myOptions');
var selecText = document.querySelector('.selectFeld>p');
var mylist = document.querySelector('.list_contrat');
//var iconSelect = document.querySelector(".icon_typeCont_rota");
var valueTypeContra = document.querySelector('#typecontrat');
for(option of options) {
option.onclick = function() {
mylist.classList.toggle('myhide');
//iconSelect.classList.toggle('myRotate');
selecText.innerHTML = this.textContent;
valueTypeContra.value = this.getAttribute('data-value'); // get value select option
}
}
<div class="selectFeld" title="Type de contrat">
<input type="text" name="typeContrat" id="typecontrat" class="d-none" required>
<p>Type de contrat</p>
<img src="icon_form/Icon_contrat_deroulant.png" alt="" class="icon_select">
</div>
<ul class="container-optionSelec list_contrat myhide">
<li class="myOptions" data-value="redaction"><p>Redaction</p></li>
<li class="myOptions" data-value="assistance"><p>Assistance</p></li>
</ul>
It's a custom select option, the code set the value for the input displayed none
Since you're not using a standard form element you're not able to use the standard required attribute, and therefore don't have the standard help features that goes along with it. And adding required to your input field does not present the built-in help message because you are hiding it.
You need to use Javascript to program a custom "required" message to go along with your custom form input mechanism. Naturally there are a number of ways to accomplish this, and present an error message to your user. What do you suppose works best for your users?
Upon first glance...
Remove the ineffective required attribute from the input element. Change the input to a hidden type, to avoid using css to hide it. And add a note to the instructions letting your users know ahead of time the selection is necessary to proceed.
Add a submit event handler to the form to capture submission and have an opportunity to validate the form. In the handler check the (now hidden) input field for an empty string indicating the custom selection mechanism has not been used. If the input value is empty, emphasize the instructions, and provide the user an error message.
For example:
var options = document.querySelectorAll('.myOptions');
var selecText = document.querySelector('.selectFeld>p');
var mylist = document.querySelector('.list_contrat');
var valueTypeContra = document.querySelector('#typecontrat');
for (option of options) {
option.onclick = function() {
selecText.style.color = 'black'; // restore black color to instruction
selecText.innerHTML = this.textContent;
valueTypeContra.value = this.getAttribute('data-value');
}
}
// GET FORM AND ADD SUBMIT EVENT HANDLER
document.querySelector('form').onsubmit = function () {
// check if "typeContrat" is equal to an empty string
if ( "" === this.elements['typeContrat'].value ) {
// emphasize the instruction label
selecText.style.color = 'red';
// provide the user and alert message
alert('Veuillez sélectionner type de contrat');
// prevent the form from being submitted
return false;
}
// if "typeContrat" is not an empty string submit the form
else { return true; }
}
<form>
<div class="selectFeld" title="Type de contrat">
<input type="hidden" name="typeContrat" id="typecontrat" class="d-none" value="">
<p>Type de contrat (required)</p>
</div>
<ul class="container-optionSelec list_contrat myhide">
<li class="myOptions" data-value="redaction">
<p>Redaction</p>
</li>
<li class="myOptions" data-value="assistance">
<p>Assistance</p>
</li>
</ul>
<input type="submit">
</form>
However, there are many user interface approaches and programming mechanisms to accomplish this, so first determine what works best for your users, supports your application purpose, goals, and look, meets your security needs—and do that.
So I have a simple log in that requires a user to input values from a json file into two different text boxes ,when the user name and (in this case I have used ID as password) matches then an alert appears to say... "welcome"
After the .click function is carried out the users text still remains in the text box, how can I get both text boxes to appear blank after the .click function?
$(document).ready(function() {
//Hide alert when page loads
$("#loginalert").hide();
$("#invalid").hide();
$("#loginbtn").click(function(event){
$.getJSON('result.json', function(jd) {
var id = $('#userName').val();
var name = $('#userName2').val();
var valid = false;
for (var i=0; i<jd.user.length; i++) {
if ((jd.user[i].ID == id) && (jd.user[i].name == name)) {
valid=true;
$('#loginalert').html('<img src="' + jd.user[i].imgpath + '"><br><p> Welcome: ' + jd.user[i].name + '</p><button type="button" id="btnhide" class="btn btn-primary btn-md">Hide</button>');
//show the alert after loading the information
$("#loginalert").stop().fadeIn('slow').animate({ opacity: 1.0 }, 3000)
$('#invalid').hide();
$('#btnhide').on('click', function(e){
//console.log('here');
e.preventDefault();
$('#loginalert').hide();
});
}
}
if (!valid) {
$('#invalid').fadeIn('slow');
$('#loginalert').hide();
}
});
}); });
username 1 and #username 2 are the text boxes - is there any way to get user name 2 to display in stars ****** when the user enters the password - this question is not that necessary but if i could also get that working that would be good.
thanks guys hope someone can help :)
is there any way to get user name 2 to display in stars ****** when
the user enters the password
You can use an input box with text property set as password. But that password masking character will be . instead of *. Not exactly sure, whether it will be a different character in some browsers.
<input type="password" id="txtPassword" />
text box to appear blank after .click function
You can set the .val() property of the jQuery objects of two those two textboxes.
$('#userName, #username2').val('');
Use <input type="password"> to show typing as stars.
Clear inputs by setting their value to be empty: $('#userName').val('');
And perhaps consider breaking your code down into a couple smaller functions so it's easier to follow.
document.getElementById("#myTextbox").value="";
This should get your textbox and set the value of it to "", which is blank.
Edit: JSFiddle
Another Method:
You can also add the script directly inside the button without using/creating a function.
<input id="inputId" type="name" />
<button onclick="document.querySelector('#inputId').value='';"> Clear </button>
Using querySelector:
<input id="inputId" type="name" />
<button onclick="click()"> Clear </button>
<script>
function click() {
document.querySelector('#inputId').value="";
}
</script>
I am trying to create one of those standard new password forms, where you type the new password once and then a second time to confirm. I would like it so that once you blur away from these fields, if they don't match, both will be marked invalid, as in the following scenario:
User enters password abc into #newpassword1.
User tabs to #newpassword2.
User enters password def into #newpassword2.
User tabs away.
Validation detects a mismatch, and marks both #newpassword1 and #newpassword2 as invalid.
I know that i can mark the target of an event as invalid by using e.target.setCustomValidity(...), but i don't understand JavaScript's event model very well and can't figure out how to mark a different element as invalid based on the event target's own invalidity.
This is the relevant excerpt of (non-working) code that i am trying to use:
if ( $('#newpassword1').val() != $('#newpassword2').val() ) {
errorMessage = "The new passwords you've entered don't match.";
$('#newpassword1, #newpassword2').setCustomValidity(errorMessage);
}
This seems like it should work, intuitively, but of course it does not. The error is simply TypeError: $(...).setCustomValidity is not a function.
Please note: I am not asking how to add a red ring or whatever to a field, i want it to actually be invalid (as in, have its validity.valid property return false).
Is it possible to do this?
Thanks!
Try the below code. You are getting that error because jQuery returns an array of selected objects and since setCustomValidity is supported by native input elements and not jquery objects, you are seeing that error.
$('#newpassword1, #newpassword2').each(function() {
this.setCustomValidity(errorMessage)
});
<div class="cabinet_settings_header cabinet_header">Список регионов работы для выбора</div>
<div class="registration_region_select checkbox-group required">
<?for($i = 0; $i < sizeof($regions); $i++):?>
<label for="region_id_<?=$regions[$i]['region_id']?>">
<input type="checkbox" name="region_id[]" value="<?=$regions[$i]['region_id']?>" id="region_id_<?=$regions[$i]['region_id']?>" />
<?=$regions[$i]['name']?>
</label>
<?endfor;?>
</div>
<div class="cabinet_settings_header cabinet_header">Проверка выбора регионов работы (разрешмет отправку формы, если минимум 1 выбран)</div>
$('.checkbox-group.required input').on('change', function(){
checkRegions();
});
function checkRegions(){
checked_counter = $('.checkbox-group.required :checkbox:checked').length;
if(checked_counter > 0){
$('.checkbox-group.required #region_id_2')[0].setCustomValidity('');
}else{
$('.checkbox-group.required #region_id_2')[0].setCustomValidity('Выберите хотябы 1 из вариантов');
}
}
$(document).ready(function() {
checkRegions();
$("form").submit(function(event){
if($('.checkbox-group.required :checkbox:checked').length <= 0 ){
$('.checkbox-group.required #region_id_2').focus();
event.preventDefault();
}
})
});
I'm trying to show and hide div contents depends on the input of the user.
Here are my codes:
<input type="text" name="pass" id="pass" onkeyup="check_input(this.value)">
<div id="repeated_pattern" style="display:none">
<b>REPEATED PATTERN</b>
<p>Repeated characters</p>
</div>
<script>
function check_input(value){
//this would check if there are 3 or more characters repeated consecutively
var repeat_pattern = /(.)\1\1/.test(value);
if(repeat_pattern) {
$("#repeated_pattern").show(500);
}else{
$("#repeated_pattern").hide(500);
}
}
</script>
Tests:
When I try to input gg, the div contents did not show so the result is ok
When I try to input ggg, the div contents show so the result is ok
But when I try to remove the one g so it is now gg. It supposed to be the div contents must be hide but still it showing. onkeyup is not working properly with the hide() function.
How to onkeyup work with hide() or vice versa?
I'm getting this error:
ReferenceError: check_input is not defined
Try setting up the event handlers in Javascript so they are in scope:
http://jsfiddle.net/vHREF/1/
Javascript:
// Event handlers
if(document.addEventListener)
document.getElementById('pass').addEventListener('keyup',check_input,false);
// Good old Internet Explorer event handling code
if(document.attachEvent)
document.getElementById('pass').attachEvent('keyup',check_input);
function check_input() {
var value = $(this).val();
//this would check if there are 3 or more characters repeated consecutively
var repeat_pattern = /(.)\1\1/.test(value);
if (repeat_pattern) {
$("#repeated_pattern").show(500);
} else {
$("#repeated_pattern").hide(500);
}
}
HTML:
I'm trying to show and hide div contents depends on the input of the user. Here are my codes:
<input type="text" name="pass" id="pass">
<div id="repeated_pattern" style="display:none"> <b>REPEATED PATTERN</b>
<p>Repeated characters</p>
</div>
I am using AngularJS to write the front-end of my website, and currently have a number of widgets displayed on a particular page. I am looking to add the functionality to hide the widget heading based on whether or not the user has selected a particular checkbox on a dialog box that is opened when they click one of the buttons on a widget.
The HTML for this checkbox is:
<div data-ng-if="widget.name === 'umw-tag-box'" ng-hide="hideWidgetHeading()">
...
<div class="divider"></div>
<div class="row ui-checkbox-row">
<label class="col-sm-4 col-xs-6" data-i18n="Hide widget heading:"></label>
<div class="col-sm-8 col-xs-6">
<label class="ui-checkbox">
<input type="checkbox" name="noWidgetHeading" ng-true-value="true" ng-false-value="false" ngChange="hideWidgetHeading()">
<span></span>
</label>
</div>
</div>
</div>
The JS is called when the 'Preview' button is clicked on the dialog box:
var widgetHeadingCheckbox = document.getElementById("noWidgetHeading");
//if(widgetHeadingCheckbox == true){
console.log("Value of widgetHeadingCheckbox: ", widgetHeadingCheckbox);
if(widgetHeadingCheckbox){
console.log("if(widgetHeadingCheckbox) statement entered ");
hideWidgetHeading();
} else {
console.log("else of if(widgetHeadingCheckbox) statement entered ");
hideWidgetHeading();
}
$scope.preview = function(e) {
function hideWidgetHeading(){
if(widgetHeadingCheckbox){
console.log("hideWidgetHeading() called (Widget/ctrl.js line 501) ");
console.log("Value of widgetHeadingCheckbox (should be true): ", widgetHeadingCheckbox);
return widgetHeadingCheckbox;
} else {
console.log("hideWidgetHeading() called (Widget/ctrl.js line 501) ");
console.log("Value of widgetHeadingCheckbox (should be false): ", widgetHeadingCheckbox);
return widgetHeadingCheckbox;
}
}
$timeout(function() { previewDisabled = false; }, 500);
};
At the moment, regardless of whether the checkbox is checked or not, when I click the 'Preview' button on the dialog box, the console is displaying the message:
Value of widgetHeadingCheckbox (should be false): null
which tells me that the widgetHeadingCheckbox variable is either not being set correctly, or it's taking the value of the checkbox when the checkbox is declared, but not initialised (i.e. null), and is not being updated when any changes are made to the value of the checkbox...
What is the best way to ensure that my JS function always holds the correct value of the HTML checkbox element, and is updated any time any changes are made to the element in the HTML?
Edit
So, having done a bit more research, I finally came across AngularJS' $scope.$watch() which is, it seems, how to add an 'event listener' for a change in the value of the checkbox.
I tried adding the following code beneath the declaration of the widgetHeadingCheckbox variable that I am using to get the HTML checkbox element:
var widgetHeadingCheckbox = document.getElementById("noWidgetHeading");
console.log(widgetHeadingCheckbox);
if(widgetHeadingCheckbox){
hideWidgetHeading();
} else {
hideWidgetHeading()
}
function hideWidgetHeading(){
if(widgetHeadingCheckbox){
console.log("Value of checkbox in if(): ", widgetHeadingCheckbox);
return widgetHeadingCheckbox;
} else {
$scope.$watch('widgetHeadingCheckbox', function(){
console.log("Value of checkbox has changed inside $watch() ", widgetHeadingCheckbox);
}, true)
return widgetHeadingCheckbox;
}
}
But, when I load the page, click the button that opens the dialog box, select the checkbox (so that its value is checked/ true), and click the 'Preview' button on the dialog box, the console displays the output:
Value of checkbox has changed (inside $watch() null
I also found that I shouldn't be using quotes in the HTML for the true/ false values of the checkbox, so changed that to:
<div class="col-sm-8 col-xs-6">
<label class="ui-checkbox">
<input type="checkbox" name="noWidgetHeading" ng-true-value= true ng-false-value= false ngChange="hideWidgetHeading()" ng-click="hideWidgetHeading()" ng-model="checkboxModel">
<span></span>
</label>
</div>
So it would seem that the checkbox is never actually being given a true/ false value... Why is this? How can I set it in order to use it in the JS function?
when you use ng-if, it acts like a child.
So the you should access it like $parrent.foo...