How to Skip ReadOnly and Disabled inputs while using .focus() - javascript

how would this code be modified so it does not .focus() the first form object if it is readonly or disabled and to skip to the next form input for focus?
Currently it returns an error if the first input box is disabled, but i would also like to skip to the next input box if it's readonly too, and if all inputs are disabled and readonly, then it should not focus anything..
<script language="javascript" type="text/javascript">
// Focus first element
$.fn.focus_first = function() {
var elem = $('input:visible', this).get(0);
var select = $('select:visible', this).get(0);
if (select && elem) {
if (select.offsetTop < elem.offsetTop) {
elem = select;
}
}
var textarea = $('textarea:visible', this).get(0);
if (textarea && elem) {
if (textarea.offsetTop < elem.offsetTop) {
elem = textarea;
}
}
if (elem) {
elem.focus();
}
return this;
}
</script>
Actually using input:enabled:visible fixes alot of my issues, but i'm still trying to figure out if readonly, to skip to the next one.

use :
$(yourElement).not(":disabled").not(":readonly")

Well here is the answer anyways for those looking..
var elem = $('input:enabled:visible:not([readonly="readonly"])', this).get(0);

You need to change the condition to
if (elem && !elem.prop('readonly') && !elem.prop('disable')) {

Related

get index of input element in javascript

If I have 3 input boxes on a web page and the user clicks the second input, I need to get the input index, the position of the input on the page. I need it in pure javascript. This is what I have so far but it doesn't work...
document.querySelector('html').onclick = function (e) {
log(e);
}
function log(obj) {
var nodeName = obj.target.nodeName
var idx = nodeName.length
console.log(nodeName, idx);
}
Any help would be appreciated!
Pure javascript:
function getIndexFromSet(set, elm){
var setArr = [].slice.call(set);
for( var i in setArr )
if( setArr[i] == elm )
return i;
}
The above function can be used like so:
function checkInputFocus(e){
if(e.target && e.target.nodeName == 'input' )
index = getIndexFromSet(inputs, e.target);
}
var inputs = document.querySelectorAll('input');
document.addEventListener("click", checkInputFocus);
using jQuery, if you run this on this page (in your console)
var inputs = $('input'); // get all input elements on the page
inputs.index( $('#save-pinned-sites-btn') ); // find the index of spesific one
you will get a number representing the index of an $('#save-pinned-sites-btn') element
Inline:
<input onclick="for(i=0;i<this.parentNode.getElementsByTagName('input').length;i++){if(this==this.parentNode.getElementsByTagName('input')[i]){alert(i);}}">
Or change that to
onclick="show_index(this)"
And Add:
function show_index(which) {
for(i=0;i<which.parentNode.getElementsByTagName('input').length;i++){
if(which==which.parentNode.getElementsByTagName('input')[i]){
alert(i);
}}

JavaScript Button Style change on click

I have put together this piece of JavaScript, but I am struggling with the code as I'm a newbie. What I want to do is when a button is clicked it will change the background color opacity. The code below does this, but now I want the button to be reverted to the normal state when I click it again.
How can I do this? Thanks..
Normal state: background="rgba(255,0,0,0.8)"; Pressed state:
background="rgba(255,0,0,0.6)";
function highlight(id) {
document.getElementById(id).style.background="rgba(255,0,0,0.6)";
}
I would use a CSS class:
.opacityClicked{
background:rgba(255,0,0,0.8);
}
.opacityDefault{
background:rgba(255,0,0,0.6);
}
And change your function to:
function highlight(id) {
var element = document.getElementById(id);
element.class = (element.class == "opacityClicked") ? "opacityDefault" : "opacityClicked";
}
Or if you want to use only JavaScript
var isClicked = false;
function highlight(id) {
isClicked = !isClicked;
var element = document.getElementById(id);
element.style.background = (isClicked == true) ? "rgba(255,0,0,0.6)" : "rgba(255,0,0,0.8)";
}
Update(See comments: if you use 2 buttons):
var buttonClicked = null;
function highlight(id) {
if(buttonClicked != null)
{
buttonClicked.style.background = "rgba(255,0,0,0.8)";
}
buttonClicked = document.getElementById(id);
buttonClicked.style.background = "rgba(255,0,0,0.6)";
}
You could do something really quick like this:
First, add a hidden input element to your page like so:
<input type="button" id="foobar" value="FooBar!" onclick="highlight('foobar')" style="background-color:rgba(255,0,0,0.8);" />
<input type="hidden" id="one_neg_one" value="1" /> <= hidden element
Next, put this in your highlight function:
function highlight(id) {
var a = 7;
var o = document.getElementById("one_neg_one");
var newa = (a + (parseInt(o.value) * -1)) * 0.1;
document.getElementById(id).style.background="rgba(255,0,0," + newa + ")";
o.value = o.value * -1;
}
That should work, although I agree with a previous answer that you should use a css class for this.
#Ruben-J answer works fine. There is a syntax error though - you should instead use element.className rather than element.class.
https://developer.mozilla.org/en-US/docs/Web/API/Element/className
Below is an updated answer using the correct syntax:
function highlight(id) {
var element = document.getElementById(id);
element.className = (element.className == "opacityClicked") ? "opacityDefault" : "opacityClicked";
}
Also noticed that this answer doesn't show the HTML. Make sure to pass through the id element, not the name of the id.

Simple dynamic form

I have aI need to validate the input by .onblur such that whenever a text input loses focus it gets validated by the same JS function.
My problem is with the JS function. I want to grab the value of the item that loses focus.
function valid(){
if (isNaN("this should be the value of the text item??")){
}
Thankss..
To grab the value of an item as you blur, you should add the onBlur trigger to the DOM element as follows:
<input type="text" name="validate_me" onBlur="valid(this);" />
That way you have access to the DOM element that triggered the onBlur event and can access its properties (such as value or innerHTML in the case of textarea elements.
Your valid function can then be something like:
function valid(element) {
if (element.value != '' && isNaN(element.value))
alert('This field is not valid!');
};
This javascript should do what you are asking for:
(function(){
var after = function(existing,after) {
if ( existing == null || typeof existing !== 'function' ) {
return after;
}
else {
return function() { existing(arguments); after(arguments); }
}
}
var validate = function(input) {
alert('validating ' + input.name);
}
window.onload = after(window.onload, function() {
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
if ( inputs[i].type === 'text' ) {
inputs[i].onblur = after(inputs[i].onblur, function() {
validate(this);
});
}
}
});
}());
Clearly you will have to replace the alert in the validate function with your validation logic, but this should do what you ask.
A couple notes, the immediately invoked function is to ensure you don't clobber any globals, and the after function is to ensure that if you there is already an attached listener that your new validate listener will be called after the existing one.

Onsubmit validate change background requried fields?

Anyone know of a good tutorial/method of using Javascript to, onSubmit, change the background color of all empty fields with class="required" ?
Something like this should do the trick, but it's difficult to know exactly what you're looking for without you posting more details:
document.getElementById("myForm").onsubmit = function() {
var fields = this.getElementsByClassName("required"),
sendForm = true;
for(var i = 0; i < fields.length; i++) {
if(!fields[i].value) {
fields[i].style.backgroundColor = "#ff0000";
sendForm = false;
}
else {
//Else block added due to comments about returning colour to normal
fields[i].style.backgroundColor = "#fff";
}
}
if(!sendForm) {
return false;
}
}
This attaches a listener to the onsubmit event of the form with id "myForm". It then gets all elements within that form with a class of "required" (note that getElementsByClassName is not supported in older versions of IE, so you may want to look into alternatives there), loops through that collection, checks the value of each, and changes the background colour if it finds any empty ones. If there are any empty ones, it prevents the form from being submitted.
Here's a working example.
Perhaps something like this:
$(document).ready(function () {
$('form').submit(function () {
$('input, textarea, select', this).foreach(function () {
if ($(this).val() == '') {
$(this).addClass('required');
}
});
});
});
I quickly became a fan of jQuery. The documentation is amazing.
http://docs.jquery.com/Downloading_jQuery
if You decide to give the library a try, then here is your code:
//on DOM ready event
$(document).ready(
// register a 'submit' event for your form
$("#formId").submit(function(event){
// clear the required fields if this is the second time the user is submitting the form
$('.required', this).removeClass("required");
// snag every field of type 'input'.
// filter them, keeping inputs with a '' value
// add the class 'required' to the blank inputs.
$('input', this).filter( function( index ){
var keepMe = false;
if(this.val() == ''){
keepMe = true;
}
return keepMe;
}).addClass("required");
if($(".required", this).length > 0){
event.preventDefault();
}
});
);

Deselect contents of a textbox with javascript

I understand that with javascript you can select the contents of a textbox with the following code (in jQuery):
$("#txt1").select();
Is there a way to do the opposite? To deselect the content of a textbox? I have the focus event of a series of textboxes set to select the contents within them. There are times now that I want to focus a particular textbox WITHOUT selecting it. What I am planning on doing is calling the focus event for this particular textbox, but then follow it with a call to deselect it.
$("input[type=text]").focus(function() {
$(this).select();
});
//code....
$("#txt1").focus();
//some code here to deselect the contents of this textbox
Any ideas?
Thanks!
what about this:
$("input").focus(function(){
this.selectionStart = this.selectionEnd = -1;
});
If you just assign the value of the textbox to itself, it should deselect the text.
You need to set the selectionStart and selectionEnd attribute. But for some reason, setting these on focus event doesn't work (I have no idea why). To make it work, set the attributes after a small interval.
$(document).ready(function(){
$('#txt1').focus(function(){
setTimeout(function(){
// set selection start, end to 0
$('#txt1').attr('selectionStart',0);
$('#txt1').attr('selectionEnd',0);
},50); // call the function after 50ms
});
});
To "focus a particular textbox WITHOUT selecting it":
I would use the part of the patched jquery plugin jquery-fieldselection
using that you can call
$('#my_text_input').setSelection({"start":0, "end":0}); // leaves the cursor at the left
or use this reduced version that places the cursor at the end of the text (by default)
(function() {
var fieldSelection = {
setSelection: function() {
var e = (this.jquery) ? this[0] : this, len = this.val().length || ;
var args = arguments[0] || {"start":len, "end":len};
/* mozilla / dom 3.0 */
if ('selectionStart' in e) {
if (args.start != undefined) {
e.selectionStart = args.start;
}
if (args.end != undefined) {
e.selectionEnd = args.end;
}
e.focus();
}
/* exploder */
else if (document.selection) {
e.focus();
var range = document.selection.createRange();
if (args.start != undefined) {
range.moveStart('character', args.start);
range.collapse();
}
if (args.end != undefined) {
range.moveEnd('character', args.end);
}
range.select();
}
return this;
}
};
jQuery.each(fieldSelection, function(i) { jQuery.fn[i] = this; });
})();
used this way:
$('#my_text_input').setSelection(); // leaves the cursor at the right
Rather than selecting and then deselecting, why not just temporarily store a boolean on the dom element?
$("input[type=text]").focus(function() {
if($(this).skipFocus) return;
$(this).select();
});
//code....
$("#txt1").skipFocus = true;
$("#txt1").focus();
I'd like to suggest a simple solution
$("input[type=text]").focus(function() {
$(this).select();
});
$("input[type=text]").blur(function() {
$('input[type="hidden"][value=""]').select();
});
//code....
$("#txt1").focus();
Here is a simple solution without jquery
<input type="text" onblur="this.selectionStart = this.selectionEnd = -1;">
If you want to deselect a text box using jQuery do the following:
$(your_input_selector).attr('disabled', 'disabled');
$(your_input_selector).removeAttr('disabled');

Categories