I'm running an .each() loop on all my form elements. I cannot find a way to determine the input type (whether it's a checkbox, text, select, textarea etc...).
Any ideas?
// When submitting
$("input[name='event_form_submit']").click(function() {
$("form[name='tepg_form_processor'] :input").each(function() {
console.log($(this).attr("type"));
// Determine whether this is a select, input etc?
});
return false;
});
$("form[name='test'] :input").each(function() {
if(this.tagName == "INPUT") {
console.log(this.tagName + ": " + this.type);
}
else
console.log(this.tagName);
});
Fiddle: http://jsfiddle.net/samliew/YSsvp/8/
Available Input Element Types
I'd suggest:
$("form[name='test'] :input").each(function() {
/* gets the type of the element ('checkbox','text','radio', etc
if there's no 'type' then it retrieves the tagName of the
element instead 'select','textarea', etc */
var inputType = this.type || this.tagName.toLowerCase();
console.log(inputType);
/* then does uses a switch to do something depending
on what you want to do */
switch (inputType) {
case 'text':
// do something with text-inputs
break;
case 'radio':
// do something with radio-inputs
break;
case 'select':
// do something with select-elements
break;
// ...etc...
default:
// do something with other elements, element-types
break;
}
});
JS Fiddle demo.
Try this (jsfiddle):
$("form[name='test'] :input").each(function() {
alert(this.type);
});
Related
I have a form with textfield, textareas and radio buttons. I want to make sure everything inside the div is selected, therefore i have disabled the submit button until everything is selected. But i can't seem to get it to work. I have a jquery functions which works, when i check on all the required input fields, but it doesn't work on radio buttons. Here is what is working:
$(document).ready(function(){
function checkInputs() {
var validInputs = true;
$('input').filter('[required]').each(function() {
if ($(this).val() === '') {
validInputs = false;
return false;
}
});
if(validInputs) {$('#speichern').prop('disabled', false)}
return validInputs;
}
//Enable or disable button based on if inputs are filled or not
$('input').filter('[required]').on('keyup',function() {
checkInputs();
})
checkInputs();
});
How can i include the radio buttons inside this function?
Try this inside checkInputs()
$('input').filter('[required]').each(function() {
var elm = this,
$elm = $(elm);
switch (elm.type) {
case 'text':
if ($elm.val() === '') {
validInputs = false;
return false;
}
break;
case 'radio':
if (!elm.checked) {
validInputs = false;
return false;
}
break;
case 'checkbox':
// handle checkbox
break;
default:
// handle others
break;
}
});
Is it possible to check via jQuery or vanilla JS if an element has a specific style?
In my case I want to check if any input-fields on the page have a red border — applied via an external CSS-File. No inline-css and no style-attr is available, styling is completely external.
For my initial testing I got the following code from this StackOverflow-Answer: https://stackoverflow.com/a/29659187
$('.formValidation input[type=submit]').on('click',function(e){
e.preventDefault();
var res = $('.formValidation input[type=text],.formValidation input[type=email],.formValidation input[type=url],.formValidation input[type=password]').toArray().some(function(el){
return $(el).css('border-color') === 'rgb(255,0,0)'
});
if (res) {
console.log('Still at least one field to go!');
} else {
console.log('You can submit!');
}
});
… but .css seams to only test inlineStyles.
Update
I can't change HTML, the markup has to stay «as is». The red border is coming through css only. Like this: https://jsfiddle.net/z3t6k04s/
Try it like this:
$('.formValidation input[type=submit]').on('click',function(e){
// Prevent Default Form Submit
e.preventDefault();
// Define Global if Invalid Fields Exist
var hasInvalidInputs = false;
// Run Through all to check Input Fields
$('input').filter(function(index){
// Check if Invalid Inputs already got detected. If not - check if this field is red
if( !hasInvalidInputs )
hasInvalidInputs = $(this).css('border-color') == 'rgb(161, 0, 0)'; // If field is red -> update global var to true
});
// Check if Invalid Fields are set to true
if (hasInvalidInputs) {
console.log('Still at least one field to go!');
} else {
console.log('You can submit!');
}
});
You could use
Window.getComputedStyle()
The Window.getComputedStyle() method gives the values of all the CSS properties of an element after applying the active stylesheets and resolving any basic computation those values may contain.
Example:
var inp = document.getElementsByTagName('input')[0];
var style = window.getComputedStyle(inp, null);
console.log(style.getPropertyValue("border-color"))
input[type='text'] {
border: 1px solid rgb(255, 0, 0);
}
<input type="text" value="Foo" />
Create a one class which has a red color
like
.red-color{
border-color:red;
}
$('.formValidation input[type=submit]').on('click',function(e){
e.preventDefault();
var res = $('.formValidation input[type=text],.formValidation input[type=email],.formValidation input[type=url],.formValidation input[type=password]').toArray().some(function(el){
return $(el).hasClass('red-color');
});
if (res) {
console.log('Still at least one field to go!');
} else {
console.log('You can submit!');
}
});
I hope this will helpful to you.
You can use below code
$('.formValidation input[type=submit]').on('click',function(e){
e.preventDefault();
var isValid;
$("input").each(function() {
var element = $(this);
if (element.val() == "") {
isValid = false;
element.css('border-color','red');
}else{
isValid = true;
element.css('border-color','');
}
});
if (isValid==false) {
console.log('Still at least one field to go!');
} else {
console.log('You can submit!');
}
});
my question is simple:
I have an input file field, and i want to limit it to only accept .GIFs via Jquery , and if the format is wrong, set the input value blank.
The problem is that on IE9, the .val('') does not work. Any ideas?
My jQuery:
$('input[type=file]').change(function() {
var val = $(this).val();
switch (val.substring(val.lastIndexOf('.') + 1).toLowerCase()) {
case 'gif':
break;
default:
// error message here
alert("Wrong Format");
$(this).val('');
break;
}
});
From IE8 it is readonly try:
$("input[type='file']").replaceWith($("input[type='file']").clone(true));
Picked from here : SO Anwser
I have two scripts for clearing my form and using input hints. The input hints are not returning AFTER I execute the clear function.
function clear_form_elements(ele) {
$(ele).find(':input').each(function() {
switch(this.type) {
case 'password':
case 'select-multiple':
case 'select-one':
case 'text':
case 'textarea':
$(this).val('');
$(" .bx4a").removeAttr("style");
$(" .bxTXTa").removeAttr("style");
$(" .bxTXTa2").removeAttr("style");
$(" .bx4a2").removeAttr("style");
$(" .bx").removeAttr("style");
$(" .ts").removeAttr("style");
$(" .button-toggle-on").removeAttr("style");
$(" .gnM").removeAttr("style");
$(" .gnF").removeAttr("style");
break;
case 'checkbox':
case 'radio':
this.checked = false;
}
});
}
// jQuery Input Hints plugin
// Copyright (c) 2009 Rob Volk
// http://www.robvolk.com
jQuery.fn.inputHints=function() {
// hides the input display text stored in the title on focus
// and sets it on blur if the user hasn't changed it.
// show the display text
$(this).each(function(i) {
$(this).val($(this).attr('title'))
.addClass('hint');
});
// hook up the blur & focus
return $(this).focus(function() {
if ($(this).val() == $(this).attr('title'))
$(this).val('')
.removeClass('hint');
}).blur(function() {
if ($(this).val() == '')
$(this).val($(this).attr('title'))
.addClass('hint');
});
};
$(document).ready(function() {$('input[title],textarea[title]').inputHints();});
The strategy for hint text is really simple: set the default value of the input to the hint text that you want, then when it gets focus set the value to ''. Then onblur, if the value is still '', set the value to the default value. e.g.
<label for="userName">Name:<input name="userName" id="userName"
value="Your full name…" class="hint"></label>
<script>
function hintFocus() {
if (this.value == this.defaultValue) this.value = '';
}
function hintBlur(el) {
if (this.value == '') this.value = this.defaultValue;
}
// Add the listeners
var el = document.getElementById('userName');
el.onfocus = hintFocus;
el.onblur = hintBlur;
</script>
Use a standard reset button for the form and give it a listener so it adds the hint class to input type text and textarea (as appropriate) when the form is reset.
I think there is a bug in RobG's answer, if the user type in text exactly same as the hint(Your full name…), then and then click somewhere and click the input, then what the user type in will disappear.
i need help on this one....i want to trigger the alert() e.g some code to execute after the change event on both input boxes....here is my code..
Millimeter: <input type="text" id="millimeter" class="filter"/>
Inch: <input type="text" id="inch" class="filter"/>
<script type="text/javascript">
$(document).ready(function(){
$(".filter").change(function(){
var value = this.value;
var id = this.id;
var convert = "";
switch(id)
{
case "millimeter":
convert = (value / 25.4).toFixed(2); //converts the value of input(mm) to inch;
$("#inch").val(convert).change();
break;
case "inch":
convert = (value * 25.4).toFixed(2); //converts the value of input(inch) to mm;
$("#millimeter").val(convert).change();
break;
default:
alert('no input has been changed');
}
alert(id+" triggered the change() event");
//some code here....
});
});
</script>
what i want is to trigger the alert() 2 twice...the result would be look like this..."Millimeter triggered the change() event"...and then when the other input box changes its value...."Inch triggered the change() event"....vice versa...i'm new to javascript and jquery...any help would be much appreciated..
The problem with your code is that in the change event of the first textbox you are triggering the change event of the second and thus entering in an endless loop. You should only use the following:
$("#inch").val(convert);
and:
$("#millimeter").val(convert);
in order to set the value of the other field but do not trigger change again.
Running your script on jsFiddle got me a "Maximum call stack size exceeded" error. This is because you're calling your .change() function inside of itself. I removed it, and it works fine.
Fiddle: http://jsfiddle.net/EwdLs/
$(".filter").change(function() {
var value = this.value;
var id = this.id;
var convert = "";
switch (id) {
case "millimeter":
convert = (value / 25.4).toFixed(2); //converts the value of input(mm) to inch;
$("#inch").val(convert);
break;
case "inch":
convert = (value * 25.4).toFixed(2); //converts the value of input(inch) to mm;
$("#millimeter").val(convert);
break;
default:
alert('no input has been changed');
}
alert(id + " triggered the change() event");
//some code here....
});
If you want each input's change to also trigger the other input's change, but don't want to get in an endless loop, try some variation on the following:
$(document).ready(function(){
function applyChange(el, changeOther) {
var value = el.value;
var id = el.id;
var convert,
other = "";
if (changeOther) {
switch(id) {
case "millimeter":
convert = (value / 25.4).toFixed(2);
other = "#inch";
break;
case "inch":
convert = (value * 25.4).toFixed(2);
other = "#millimeter";
break;
default:
alert('no input has been changed');
break;
}
if (other != "") {
$(other).val(convert);
applyChange($(other)[0], false);
}
}
alert(id+" triggered the change() event");
//some code here....
}
$(".filter").change(function(){
applyChange(this, true);
});
});
In case it's not obvious, I basically took your existing change handler and put it in a new function, applyChange, which has a parameter to tell it whether or not to recurse. The code as is is clunky, but it should give you the general idea of one way to do what you seem to be asking.
P.S. Be sure to add in some validation that what the user entered is really a number.