How to focus first input? - javascript

I have a ASP.NET MVC application and I want to focus the first field in error. On submit, if the last field has error and user tries to submit the form, the focus is going to the last field in error instead of the first field. I tried multiple including the below:
$().ready(function() {
$("#Form").submit(function() {
$('.input-validation-error').focus();
$(".input-validation-error").each(function() {
$(this).focus();
});
});
});
Is there any solution where the user can always go to the first field in error.

No need to use each here and loop over all errors. You can just set the focus to first element with error class input-validation-error like:
$('.input-validation-error:first').focus();

#Palash has a good answer but I will explain why your code does not work so you understand it.
You need to leave the loop after the focus is set to the first item by returning false like below:
$(".input-validation-error").each(function () {
$(this).focus();
return false;
});
When you return false, you are instructing jQuery to stop processing the rest of the elements.Otherwise, it will keep looping and you will end up focusing the last item.

You can use eq method.
eq method reduces the set of matched elements to the one at the
specified index.
$('.input-validation-error').eq(0).focus();

Related

Understanding jQuery .change event

I have some issue understanding the jQuery().change() behavior.
The HTML is basically a lot of input elements - checkboxes ( each with ID of id^='o99-post-visible-XXX' - and they are pure CSS images as Checkboxes, but this is irrelevant ) and I have another checkbox ("#o99-check-all") to "check all" and a text input field ('#o99-post-visible-ids') that receives the IDs of the selected boxes.
The jQuery code is as follows:
jQuery(document).ready(function() {
jQuery("#o99-check-all").change(function () {
jQuery("input:checkbox[id^='o99-post-visible-']").prop('checked', jQuery(this).prop("checked")).trigger('change');
});
var checkboxes = jQuery("input.o99-cbvu-posts-checkbox:checkbox");
checkboxes.on('change', function() {
// get IDS from all selected checkboxes and make a comma separated string
var ids = checkboxes.filter(':checked').map(function() {
return this.value;
}).get().join(',');
// put IDS inside a text input field
jQuery('#o99-post-visible-ids').val(ids);
// console.log(ids);
});
});
Now, more or less everything works now, but that is not the issue.
at first , the first chunk of code was:
jQuery("#o99-check-all").change(function () {
// without .trigger('change') chained
jQuery("input:checkbox[id^='o99-post-visible-']").prop('checked', jQuery(this).prop("checked"));
});
and it did not work ( why?? ) - meaning the boxes were selected as expected but the '#o99-post-visible-ids' input field was not receiving the IDs - until I chained a .trigger('change') event - when suddenly it works well.
my confusion is with the following ( which perhaps for my little understanding of jQuery internal works is counter-intuitive )
after chain adding .trigger('change') - isn't it somehow an endless loop where a chain() event is trigger inside a listener of change() ? and if not why?
Why is the code functioning now and did not function correctly before? because again, for my understanding, there was a change, even if not triggered by direct user click. Why would I need to trigger it manually?
I'm not sure I understand what you mean. What is happening now, is that whenever you change the all checkbox, the other checkboxes will be checked/unchecked the same as all, and then the change event is triggered.
Because you added a listener for change, that function will then fire. I.e. this function will run:
function() {
// get IDS from all selected checkboxes and make a comma separated string
var ids = checkboxes.filter(':checked').map(function() {
return this.value;
}).get().join(',');
// put IDS inside a text input field
jQuery('#o99-post-visible-ids').val(ids);
// console.log(ids);
}
Without your .trigger("change") (or .change() in short), you only change a property of the inputs. So the object changes, indeed, but that does not mean the change event is triggered. It does sound counter-intuitive, but events are only triggered by user actions or if you call the event explicitly - in no other way do events get triggered.
its because you have written jQuery('#o99-post-visible-ids').val(ids); inside a function which happens only when the change event done on the inputs, assigning prop directly through .prop does not trigger the change event and so the result handler wont run
Now if I understand you correctly...
...because you're giving every check box the same ID? If you wish to apply it to more than a single element, it is best practice to use a class selector instead.
jQuery(".o99-check-all").change(function () {
// without .trigger('change') chained
jQuery(".o99-check-all").prop('checked', jQuery(this).prop("checked"));
});
See link
https://api.jquery.com/change/

Remove div on input change

I wrote an autocomplete type thingy that goes through divs and adds them to a list if their name/id is found. I am using an event handler that I found online that is called on any sort of input change. The issue that I am having is: When a valid div is found and added to the autocomplete list, and then the user continues to type, but is typing an invalid div name, the div name is removed from the list; HOWEVER, if no divs are found, the list persists but is blank.
A better way to explain is to try it out.
http://jsfiddle.net/ypz0zrzv/21/
Type "Test Unit" in the box, and then continue to type random letters. I am trying to get the now empty list to remove. The issue is that, when I implement such a feature, it is only going to happen after a second character is entered. This is because the handler checks the list on input change.
So if I type "Test Unit" it adds the div. If I type "Test Unita" it shows a blank autocomplete div. If I type "test Unitaa" now the autocomplete div will be gone. I am puzzled how to get the autocomplete to be blank immediately after it has found no divs.
Code problem in question
if ($('#autocomplete_list li').length === 0){
hide_remove($('#autocomplete'))
}
Your check for the auto complete was in the wrong location. It was being triggered by the wrong event.
I moved the check into its own function, in case you want to call this check at a later time:
function checkArray(){
console.log($('#autocomplete_list li').length);
if ($('#autocomplete_list li').length <= 0){
hide_remove($('#autocomplete'))
}
}
Then I added that checkArray() function into the hide_remove() function.
function hide_remove($div){
if ($div.length > 0){
$div.slideUp(250, function(){
$div.remove();
checkArray();
});
}
}
Here is a DEMO. Hope this helps!

Assign value from one input to another input using jQuery...not working

I have a couple of radios (#LocalDelivery and #StandardShip) related to a couple text inputs (#LocalDate and #datepicker). Then, off in another section is another text input with class productAttributeValue.
If LocalDelivery is chosen/checked, I need its input, #LocalDate to get the value and name from the input with class productAttributeValue. Or, if #StandardShip is chosen/checked I need its input, #datepicker, to get the value and name from the input with class productAttributeValue.
I have tried various combinations of the following:
if (!$('#LocalDelivery').is(":checked")) {
$('#datepicker').val("");
$('#LocalDate').val($('.productAttributeConfigurableEntryText div.productAttributeValue input[type="text"]').val());
$('#LocalDate').attr('name',
$('.productAttributeConfigurableEntryText div.productAttributeValue input[type="text"]').attr('name'));
}
if (!$('#StandardShip').is(":checked")) {
$('#LocalDate').val("");
$('#datepicker').val($('.productAttributeConfigurableEntryText div.productAttributeValue input[type="text"]').val());
$('#datepicker').attr('name',
$('.productAttributeConfigurableEntryText div.productAttributeValue input[type="text"]').attr('name'));
}
Per my other thread, Issue with jQuery 'else', this method isn't working. According to the answers given there, this is the wrong method entirely but I'm not sure how else to go about this.
Here is a fiddle:
This is my glorious Fiddle
EDIT:
Per beautifulcoder's comment I have added a click function to both radios. While it would be preferable for the inputs to populate their value without clicking first, this is the first solution I've had that works. Created a fiddle here, hope it helps someone else:
My amazing working Fiddle

Show Input Box on Check

You can see in the paper form attached what I need to convert into a web form. I want it to show the check boxes and disable the input fields unless the user checks the box next to it. I've seen ways of doing this with one or two elements, but I want to do it with about 20-30 check/input pairs, and don't want to repeat the same code that many times. I'm just not experienced enough to figure this out on my own. Anyone know anywhere that explains how to do this? Thanks!
P.S. Eventually this data is all going to be sent through an email with PHP.
I don't think this is a good idea at all.
Think of the users. First they have to click to enter a value. So they always need to change their hand from mouse to keyboard. This is not very usable.
Why not just give the text-fields? When sending with email you could just leave out the empty values.
in your HTML :
//this will be the structure of each checkbox and input element.
<input type="checkbox" value="Public Relations" name="skills" /><input type="text" class="hidden"/> Public Relations <br/>
in your CSS:
.hidden{
display:none;
}
.shown{
display:block;
}
in your jQuery:
$('input[type=checkbox]').on('click', function () {
// our variable is defined as, "this.checked" - our value to test, first param "shown" returns if true, second param "hidden" returns if false
var inputDisplay = this.checked ? 'shown' : 'hidden';
//from here, we just need to find our next input in the DOM.
// it will always be the next element based on our HTML structure
//change the 'display' by using our inputDisplay variable as defined above
$(this).next('input').attr('class', inputDisplay );
});
Have fun.
Since your stated goal is to reduce typing repetitive code, the real answer to this thread is to get an IDE and the zen-coding plug in:
http://coding.smashingmagazine.com/2009/11/21/zen-coding-a-new-way-to-write-html-code/
http://vimeo.com/7405114

How can I use the jQuery Autocomplete plugin for linked input fields?

I'm using the jQuery Autocomplete plugin. I have two input fields on a form, inputfield1 and inputfield2.
I attached autocomplete to the first field. When the that field loses focus, I want to check if a value was entered and if so, then make an AJAX call to retrieve some "\n"-separated strings and use them to drive autocomplete on the second field.
Below is the code I'm using to do that:
/*Receive data from server for autocomplete*/
$("#inputfield1").autocomplete("<url1>");
$("#inputfield1").blur(function(){
// Attach autocomplete if inputfield1 field is not empty
if($("#inputfield1").val() != ""){
var url = "<url2>?q="+$("#inputfield1").val();
$.get(url,function(data){
result=data.split("\n");
$("#inputfield2").autocomplete(result);
});
}
});
But a strange thing is happening: I am able to attach autocomplete to the first field successfully, but I have to give focus twice to the second field in order to use autocomplete on it. Is there any way to fix this problem?
Try this simplified test. If this works check if your result really contains what you think (alert it or write it to console). There could be other characters after splitting (namely whitespace (leading spaces, \t or \r) try trimming every value of the result array.
var data1 = ["a123", "b123", "c123", "d123", "e123", "f123", "g123", "h123", "i123", "j123", "k123", "l123", "m123", "n123", "o123", "p123", "q123", "r123", "s123", "t123", "u123", "v123", "w123", "x123", "y123", "z123"];
var data2 = 'a123\nb123\nc123\nd123\ne123\nf123\ng123\nh123\ni123\nj123\nk123\nl123\nm123\nn123\no123\np123\nq123\nr123\ns123\nt123\nu123\nv123\nw123\nx123\ny123\nz123';
$("#inputfield1").autocomplete(data1);
$("#inputfield1").blur(function(){
if($("#inputfield1").val() != ""){
var result=data2.split("\n");
$("#inputfield2").autocomplete(result);
}
});
I found this code in the current version of the autocomplete plugin:
.click(function(event) {
$(target(event)).addClass(CLASSES.ACTIVE);
select();
// TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
input.focus();
return false;
It seems to put focus back on itself after a click. This might be messing you up.
Instead of handling the blur() event, maybe you'll have better luck if you handle the autocomplete plugin's result() event.
/*Receive data from server for autocomplete*/
$("#inputfield1").autocomplete("<url1>");
$("#inputfield1").result(function(event, data, formatted){
// Attach autocomplete if inputfield1 field is not empty
if(data){
var url = "<url2>?q="+data;
$.get(url,function(data1){
result=data1.split("\n");
$("#inputfield2").autocomplete(result);
});
}
});
Make sure you're using the latest version of the Autocomplete plugin. There was a bug in versions prior to 1.1 where if you enabled autocomplete on a field after that field had focus (as would happen in your example if you tabbed from the first input field directly into the second) it wouldn't work properly until focus was lost and then restored again...
Here's a quick demo that shows this construct working with the latest Autocomplete version.
You say you need to select #inputfield2 twice so the autocomplete event binds to it, right?
I'm just thinking.. can it be possible that you are using your tab key on your keyboard to select #inputfield2 and when that doesn't work you select #inputfield2 with your mouse? If so, isn't it possible that the #inputfield1 blur event doesn't kick in until you "unselect" it with your mouse (maybe some kind of bug)?
I haven't tried this, it's just a thought.

Categories