I am using JQuery and JavaScript for an input form for time values, and I can't make JavaScript to provide the intended reaction to incorrect input format.
What do I do wrong...?
I have a set of 3 text inputs with class "azeit" (and under these a number of others of class "projekt"). All are used to input time values. As soon as the user exits the field I validate the format, do a calculation with it and display the result of this in a field with id "summe1". This works. If the format is incorrect, I display an alert and what I want to do is return the focus to the field after emptying it. However, the focus never gets returned (although it will get emptied all right). This is it:
var kalkuliere_azeit = function(e) {
var anf = $("#anfang");
var ende = $("#ende");
var pause = $("#pause");
var dauer_in_min = 0;
var ungueltiges = null;
if (nonempty(anf.val(), ende.val()), pause.val()))
{
if (!is_valid_date(make_date(anf.val()))){
ungueltiges = anf;
};
if (!is_valid_date(make_date(ende.val()))){
ungueltiges = ende;
};
if (!is_valid_date(make_date(pause.val()))){
ungueltiges = pause;
};
if (ungueltiges)
{
alert("invalid time"); //This is where I am stuck
ungueltiges.val("");
ungueltiges.focus();
}
else {
dauer_in_min = hourstring_to_min(ende.val())
- hourstring_to_min(anf.val())
- hourstring_to_min(pause.val());
$("#summe1").text(min_to_hhmm(dauer_in_min));
};
};
};
....
$(document).ready(function() {
$(".projekt").change( kalkuliere_summe);
$(".azeit").focusout(kalkuliere_azeit);
});
The fields with the class "projekt" are below those with the class "azeit" so they'll get the focus when the user leaves the third field of class "azeit".
I apologize for supplying incomplete source code. I hope someone can see what's wrong.
One point I'd like to mention is that I tried binding the handler to onblur and onfocus as well. When I bind it to onfocus the focus does get reset to the field, but the last field the user enters will not update the field $("#summe1") correctly (because this would need focusing another field of the same class).
Im not sure whats wrong with your code but one way of doing it would be to put the focus into a function.
So ...
function focusIt()
{
var mytext = document.getElementById("divId");
mytext.val("");
mytext.focus();
}
And call it from the if/else statement ...
if (ungueltiges)
{
alert("invalid time");
focusIt()
}
Related
I have used a range picker (Progress bar) to get measurements from the customers. I have set it's limit from 1 to 50 so it takes 1 value by default if user do not select it and user can add product to the cart without selecting range picker. Is there any way that we can change by default value on page load with javascript (No jQuery) to something that does not allow user to add product to the cart.
Link: https://cutt.ly/nrB4PAR
I am using this code now but it's not working. I want value to be null.
<script type="text/javascript" language="javascript">
debugger;
var range_val = document.getElementById("tmcp_range_1").value;
if (range_val == 1)
{
document.getElementById("tmcp_range_1").value = "";
}
</script>
UPDATED:
I’m not sure I really understand why you need this, but you have to put that code in a function, then call an event listener.
function changeVal() {
var range_val = document.getElementById("tmcp_range_1").value;
if (range_val == 1) {
document.getElementById("tmcp_range_1").value = "22";
}
}
window.addEventListner("load", changeVal);
Updating the input value after DOM loads will change the value.
function updateVal() {
var range_val = document.getElementById("tmcp_range_1").value;
if (range_val == 1) {
document.getElementById("tmcp_range_1").value = "22";
}
}
window.addEventListner("load", updateVal);
And also you need to change noUiSlider logic to update UI.
Ref link https://refreshless.com/nouislider/slider-read-write/
I'm working on autocomplete textbox feature of angularjs. I want the user only to select name from the existing autocomplete list instead of typing a new name. Eg.,When user types 'Al' autocomplete list shows the matching list and user can select one name from the existing list instead of typing a new name.How to restrict user from submitting a new name which is not present in the existing list.
Demo : http://plnkr.co/edit/AdmtP1b6K9kQorMHmt7t?p=preview
Code Sample:
$scope.countryList = ["Afghanistan","Albania","Algeria","Andorra","Angola","Anguilla","Antigua & Barbuda","Argentina","Armenia","Aruba","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bermuda","Bhutan","Bolivia","Bosnia & Herzegovina","Botswana","Brazil","British Virgin Islands","Brunei"];
$scope.validateField = function(){
alert("Clicked on submit , validte field");
}
$scope.complete=function(string){
var output=[];
angular.forEach($scope.countryList,function(country){
if(country.toLowerCase().indexOf(string.toLowerCase())>=0){
output.push(country);
}
});
$scope.filterCountry=output;
}
$scope.fillTextbox=function(string){
$scope.country=string;
$scope.filterCountry=null;
}
Any inputs would be helpful.
You can disable submit button and also highlight the border of the input field red, telling user to select name from drop down list.
First you need to update your complete() function. Use an else if statement that will check if the value is from the list or not, if not then you can implement your desired logic in that else if statement.
This method is flexible and easy to customize your error generation messages. You can show and hide the div that has the error message or you can apply css style on input-field using ng-style or ng-class. Right now I'll show you how to disable or enable button. Here is the updated code snippet:
$scope.complete = function(string) {
var output = [];
angular.forEach($scope.countryList, function(country) {
if (country.toLowerCase().indexOf(string.toLowerCase()) >= 0) {
output.push(country);
$scope.enableDisable = false;
} else if (country.toLowerCase().indexOf(string.toLowerCase()) < 0) {
$scope.enableDisable = true;
}
});
$scope.filterCountry = output;
}
And the In the html section you just need to add ng-disabled attribute and set its value.
<input type="submit" value="submit" ng-disabled="enableDisable" ng-click="validateField()">
So, you can do whatever you want in that else if statement to get the desire error message.
Take a look at this plunkr.
you can check for the validity of input using something like below and monitoring the value using ng-change
$scope.checkInput = function(){
$scope.validInput = $scope.countryList.indexOf($scope.country) > -1;
}
I'm building a PDF in Scribus and stumbling through javascript (basic newbie here) as I go. I've ran into an issue and I can't seem to find a good answer.
I have a combobox called productType where a user selects a product. Once they do that I want a text field called mortClause to display the proper clause. I've placed the following code under the combobox's Action -> On Blur -> Javascript.
Here is what I have that is not working:
var ckSelect = this.getField("productType");
var ckResult = this.getField("mortClause");
if (ckSelect.value === "VA") {
mortClause.value = 'VA Clause';
} else if (ckSelect.value === "FHA") {
mortClause.value = 'FHA Clause';
} else {
mortClause.value = 'Normal Clause';
}
"mortClause" is not the name of your variable, its ckResult.
If you change
mortClause.value = 'VA Clause';
to
ckResult.value = 'VA Clause';
you get the expected behaviour.
But you probably already know that. or gave up, after 3 years.
I am working on an html form which employs jscript to perform functions such as loading form settings, loading the form with default values, data validation, among others. It then uses htm to display the page.
When the form loads the first field is populated with default data which is appropriate 99% of the time. I want the first field of the form to not only acquire focus upon load but also to have the default value (text) selected so that the 1% of users can easily begin typing without having to backspace through or highlight the text.
I've looked on a number of sites including stackoverflow and the most common suggestion is to add a line -- fieldid.select(); This line would immediately follow the focus line -- fieldid.focus(); Adding the select line had no effect at all. The field does receive focus but the cursor is blinking at the end of the default text and the text is not selected.
Here is the code snippet that I am using...
function windowLoad()
{
hideExtraFields();
loadFormSettings();
comboEventType.focus();
var params = getUseCaseParams();
if (params)
{
inputLocation.value = params.EventLocation;
comboEventType.value = "This is the default text";
comboEventSubtype.value = "this is the default subtext";
}
else
{
var unitData = getMyUnitData();
inputLocation.value = unitData.Position.LocationString;
comboEventType.value = "This is the default text";
comboEventSubtype.value = "this is the default subtext";
}
}
Make sure you are calling select() after you have already set your default values.
function windowLoad()
{
hideExtraFields();
loadFormSettings();
var params = getUseCaseParams();
if (params)
{
inputLocation.value = params.EventLocation;
comboEventType.value = "This is the default text";
comboEventSubtype.value = "this is the default subtext";
}
else
{
var unitData = getMyUnitData();
inputLocation.value = unitData.Position.LocationString;
comboEventType.value = "This is the default text";
comboEventSubtype.value = "this is the default subtext";
}
comboEventType.focus();
inputLocation.focus()
inputLocation.select()
}
Order matters here. Notice this works:
http://jsfiddle.net/g1zmprmx/
But this doesn't:
http://jsfiddle.net/bspga4gb/
I have a webpage I'm building where I need to be able to select 1-9 members via a dropdown, which then provides that many input fields to enter their name. Each name field has a "suggestion" div below it where an ajax-fed member list is populated. Each item in that list has an "onclick='setMember(a, b, c)'" field associated with it. Once the input field loses focus we then validate (using ajax) that the input username returns exactly 1 database entry and set the field to that entry's text and an associated hidden memberId field to that one entry's id.
The problem is: when I click on the member name in the suggestion box the lose focus triggers and it attempts to validate a name which has multiple matches, thereby clearing it out. I do want it to clear on invalid, but I don't want it to clear before the onclick of the suggestion box name.
Example:
In the example above Paul Smith would populate fine if there was only one name in the suggestion list when it lost focus, but if I tried clicking on Raphael's name in the suggestion area (that is: clicking the grey div) it would wipe out the input field first.
Here is the javascript, trimmed for brevity:
function memberList() {
var count = document.getElementById('numMembers').value;
var current = document.getElementById('listMembers').childNodes.length;
if(count >= current) {
for(var i=current; i<=count; i++) {
var memberForm = document.createElement('div');
memberForm.setAttribute('id', 'member'+i);
var memberInput = document.createElement('input');
memberInput.setAttribute('name', 'memberName'+i);
memberInput.setAttribute('id', 'memberName'+i);
memberInput.setAttribute('type', 'text');
memberInput.setAttribute('class', 'ajax-member-load');
memberInput.setAttribute('value', '');
memberForm.appendChild(memberInput);
// two other fields (the ones next to the member name) removed for brevity
document.getElementById('listMembers').appendChild(memberForm);
}
}
else if(count < current) {
for(var i=(current-1); i>count; i--) {
document.getElementById('listMembers').removeChild(document.getElementById('listMembers').lastChild);
}
}
jQuery('.ajax-member-load').each(function() {
var num = this.id.replace( /^\D+/g, '');
// Update suggestion list on key release
jQuery(this).keyup(function(event) {
update(num);
});
// Check for only one suggestion and either populate it or clear it
jQuery(this).focusout(function(event) {
var number = this.id.replace( /^\D+/g, '');
memberCheck(number);
jQuery('#member'+number+'suggestions').html("");
});
});
}
// Looks up suggestions according to the partially input member name
function update(memberNumber) {
// AJAX code here, removed for brevity
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
document.getElementById('member'+memberNumber+'suggestions').innerHTML = self.xmlHttpReq.responseText;
}
}
}
// Looks up the member by name, via ajax
// if exactly 1 match, it fills in the name and id
// otherwise the name comes back blank and the id is 0
function memberCheck(number) {
// AJAX code here, removed for brevity
if (self.xmlHttpReq.readyState == 4) {
var jsonResponse = JSON.parse(self.xmlHttpReq.responseText);
jQuery("#member"+number+"id").val(jsonResponse.id);
jQuery('#memberName'+number).val(jsonResponse.name);
}
}
}
function setMember(memberId, name, listNumber) {
jQuery("#memberName"+listNumber).val(name);
jQuery("#member"+listNumber+"id").val(memberId);
jQuery("#member"+listNumber+"suggestions").html("");
}
// Generate members form
memberList();
The suggestion divs (which are now being deleted before their onclicks and trigger) simply look like this:
<div onclick='setMember(123, "Raphael Jordan", 2)'>Raphael Jordan</div>
<div onclick='setMember(450, "Chris Raptson", 2)'>Chris Raptson</div>
Does anyone have any clue how I can solve this priority problem? I'm sure I can't be the first one with this issue, but I can't figure out what to search for to find similar questions.
Thank you!
If you use mousedown instead of click on the suggestions binding, it will occur before the blur of the input. JSFiddle.
<input type="text" />
Click
$('input').on('blur', function(e) {
console.log(e);
});
$('a').on('mousedown', function(e) {
console.log(e);
});
Or more specifically to your case:
<div onmousedown='setMember(123, "Raphael Jordan", 2)'>Raphael Jordan</div>
using onmousedown instead of onclick will call focusout event but in onmousedown event handler you can use event.preventDefault() to avoid loosing focus. This will be useful for password fields where you dont want to loose focus on input field on click of Eye icon to show/hide password