Jquery Focus on input field - javascript

The HTML on the page has 20 <input> fields each named and given ID's in increasing order from 1 to 20.
If the variable id is set to the next sequential id (id + 1), this function will cause focus to apply to that field. However, when clicking outside of the current input field, the last one input field will not regain focus if the number entered is greater than 10, but an alert will be displayed.
$(":input").focusout(function(){
var input = $(this).val();
var id = $(this).attr('id');
if(input > 10){
alert('You must enter a number between 0 and 10 '+id);
$("#"+id).select();
}
});
How can the last input field be set to regain focus?

Try replacing:
$("#"+id).select();
With:
$(this).focus();
In this case, $("#"+id) and $(this) are the same element, and I'm assuming you want to focus the element when there is an error.
Aside: I don't believe that id or name values can legally start with a number, you may want to prefix them with something like option1, option2, etc. It might work, but it might also cause issues later that are difficult to debug. Best to err on the side of caution and best practices.
What are valid values for the id attribute in HTML?
Edit: After failing to get focus() to work, I tried with setTimeout and was able to make it happen. I'm not sure why, or if this is really necessary, but it seems to work.
$(":input").focusout(function(){
var $this = $(this),
input = $this.val();
if (input > 10){
alert('You must enter a number between 0 and 10');
setTimeout(function(){
$this.focus();
}, 1);
}
});
I'd love to hear if there is a better way to do this or an explanation. I suspect that the blur and focus events are not fired in an order that makes the previous method possible?
Demo: http://jsfiddle.net/zRWV4/1/
As mentioned in the comments, you should eventually make sure the value is an integer with parseInt or similar (you seem to already be aware of this).

replace
$("#"+id).select();
by
$("#"+id).focus();
or even by
$(this).focus();

You should parse the text inside the input to compare it with a number. var input = parseInt($(this).val());
'
$(":input").blur(function(){
var input = parseInt($(this).val());
var id = $(this).attr('id');
if(input > 10){
alert('You must enter a number between 0 and 10 '+id);
$("#"+id).select();
}
});

(Try to use .blur() instead of .focusout(). But that probably won't help)
Try to remove the alert() for a while - it sometimes can make problems with focus...

jsFiddle Example
This is my code, I'll explain what I changed:
$('input[id^="input"]').focusout(function(){
var selected = parseInt($(this).val(), 10);
if (selected <= 10) {
$("#input-"+selected).focus();
}
else {
alert('Invalid Argument! 1-10 only!');
$(this).focus();
}
});
I use focus() instead of select() which won't work.
You confused id with select which caused you to always try and select $("#input-IDOFSELECTIONINPUT") instead of $("#input-IDOFWANTEDINPUT")
In your code, although an alert would have been thrown, the rest of the code would have continued normally. It won't in my code.
You've put your desired result ($("#"+id).select();) in the undesired condition (input > 10), which practically never gave it a chance.
Last but not least, I gave the inputs a better (and valid) id. IDs must not start with a number.

Related

Applying increasing values to text field on focus or on click

I have 18 rows of text fields and in each one I need to give it an increasing ID, however they're not just straight forward, as the bottom row in the grid could need ID 1 and the first one could need ID 15 depending on what is chosen. It doesn't need to look that pretty as long as it does the job. I will be using it to insert data in to a database from an iPad and ideally having an onclick event on the row title, and that adding the next incremental number would be perfect, however if that's not possible adding an onfocus event would be fine.
I already have the following
$('.played').on('focus', function(){
var $this = $(this);
if($this.val() == ''){
$this.val('1');
} else {
$this.val('');
}
});
Which adds the number 1 in the clicked text field and if you click on it when it has the value of 1, it removes it. What I'd now like to do is when the next 'played' class text field that's clicked, it populates it with 2, and so on up to 18. Is this possible?
Maybe something like the following to get the max value that you can check against yourself to know if you need to set it or clear it out, and additionally if you don't have a value and you do have a max value, your new value would be max + 1
var valueArray = $('.played').map(function(played){ return $(played).val(); }).toArray();
var maxValue = Math.max(valueArray);

Hiding Selected item with Jquery

I have this code
$("#tag_price").on('change', function(event) {
if ($(this).val() == -2)
$('<input type="text" class="ipt" id="customprice" name="customPrice" />').insertAfter(this),
$('<p id="customprice" class="semi_margin_top">Introduce el precio exacto</p>').insertAfter(this);
else if ($(this).val() !== -2)
$('#customprice').hide;
});
The first part is working, when the input has value -2, the second input is shown. But I want it to dissappear when another value is selected, because if not the second input will remain forever.
I want the second input ONLY to show when value -2 is selected, and dissappear when another value is selected. I thought I could achieve that with Jquery and hide, but I't wont work.
Thank you!
The corollary to hide() you're looking for is show(). There are a few other issues with your code that you'll need to take care of as well.
First, you're missing { } around your if statement, so your else if should be throwing an error as the $('<p...') line is outside of the if.
Secondly, there's no need for else if as there isn't a 3rd option. The value is either "-2" or it isn't.
Right now, you're appending a new element every time that someone selects the "-2" item, which is not the right way to do it. Check to see if those elements are already in the DOM, and only add them if they aren't there. If they are, then call show().
if ($(this).val() === -2) {
$('#customprice').show();
}

value-attribute seems not to show input-field-content

I'm trying to use jquery to check if every input-field has already been filled out. And if yes, I'd like to make a green border around the form.
This was my approach:
if($('input:text[value=""], textarea[value=""]').length == 0){
alert("DONE");
}
Hovever the value="" -Selector doesn't work.
It seems that the value-attribute only contains the input-field's default-value, but not the actual content inserted by the user - according to firebug.
This command alerts me the actual contents:
$('input:text[value!=""]').each(function(){
alert($(this).val());
});
My Question: Where are the actual input-field contents stored? And how can I use jQuery to check efficiently, if there are empty fields?
You are right, the attribute selectors only work with the value the attribute really has. Later on, changing the value of the input will only change the DOM element's internal state.
Where are the actual input-field contents stored?
You can access the value via the value property of the DOM element elementNode.value.
And how can I use jQuery to check efficiently, if there are empty fields?
You can use .filter:
$('input').filter(function() {
return !this.value;
});
A neat way of validating inputs is to attach a validation rule to the element for your script to find and validate against.
To make a field required:
<input type="text" data-validate="required" />
Your script:
$('[data-validate]').each(function() {
var rule = $(this).attr('data-validate'), value = $(this).val();
switch (rule) {
case 'required':
if (!value) {
alert('Field invalid!');
}
break;
}
});
It works pretty well for me.
You can make it more efficient by selecting only specific element types or children of a specific element (such as a form).
You could try using .filter() like this:
var empty = $('input:text').filter(function(){ return $(this).val() == "" }).length;
if(empty > 0){
alert("There are "+empty+" fields which have not been filled out");
}
my approach if you are not willing to use Jquery validate.
give a class to each of your input fields and then use Jquery class selector to test if those all have filled or not. You can use this even for dropdown too.
You should use this construction:
var incomplete = $('form :input').filter(function() {
return $(this).val() == '';
});
if (incomplete) {
alert('Please fill all fields!');
}
:input selector selects all input, textarea, select and button elements.
Read this: http://api.jquery.com/input-selector/

Listen for input in a hidden input-field

Is there a way, on document ready / page load, one can listen for more than three characters being typed in a row that don't do anything else, while nothing else is focused, and if that event occurs transfer those three characters and anything else that is typed after into an input-field of type text / search that is hidden — either by the display, visibility, or opacity CSS properties?
I would appreciate any help in doing this.
I have done something like this with a label and radio-button / check-box that is hidden. But that is because the input is just a click on the label. Not as complex as alpha-numeric input.
If you can help me with any part of achieving the above, I would greatly appreciate it.
Should be straight forward:
var keys = [];
$(document).on('keypress', function(e) {
keys.push( String.fromCharCode(e.which) );
if (keys.length > 2)
$('input').fadeIn(400).val( keys.join('') );
});
FIDDLE
Your question is vague, but what you could do is call .focus() on the input whenever any other input has the event onblur and use the oninput event for your hidden field.
You can bind keypress to the document and store the result in a variable until you're ready, something like:
var typedString = "";
$(document).keypress(function(e){
typedString += String.fromCharCode(e.keyCode);
if(typedString.length >= 3){
$('#some-textbox').show();
$('#some-textbox').val(typedString);
}
});

overriding data-confirm values

I want to change the value of data-confirm attribute on a button (submit) based on user's choices on a form. I put the following on the change function of a dropdown list:
...
if($("#"+select_name).val() == "abc")
{
$(".variable_button").attr("data-confirm","abc is good choice!");
} else
{
$(".variable_button").attr("data-confirm","abc would have been great but this is fine too...");
}
...
The problem I am facing is that apparently data-confirm cannot be changed once it is assigned a non-empty string. I have it set to "" in the server code. And, it changes to one of the two messages shown above when the user first makes a selection on the dropdownlist. But if the user changes the selection one more time, the data-confirm message does not change. Is this per design or am I missing something?
Don't use .attr(), use .data():
var newData = ($("#"+select_name).val() == "abc")
? "abc is good choice!"
: "abc would have been great but this is fine too...";
$(".variable_button").data("confirm", newData);
jQuery does allow you to update a data- attribute with the .attr() method, so something else is breaking.
Here's a working example (JSFiddle):
var counter = 1;
$('#click').click(function() {
button = $('#click');
console.log(button.attr('data-confirm'));
button.attr('data-confirm', 'this is test ' + counter);
console.log(button.attr('data-confirm'));
counter++;
});
Can you try to repo the issue in a JSFiddle?
On rereading your question, it sounds like an event handler isn't firing the second time the user changes the selection. See if you can set a breakpoint in your event handler to see if it even gets hit.

Categories

Resources