Webkit checkbox default value is null? - javascript

When using a WebKit browser (Chrome or Safari), if I try to get the default value of a checkbox, it returns "". However, the same javascript in Firefox or IE will return "on".
So lets say I have this checkbox on a page:
<input type="checkbox" id="chkDefaultValue">
I use this javascript to return all "input" elements on a page
var elems = document.getElementsByTagName('input');
Then I go through a loop that gets the value like this
elems[i].getAttribute('value')
When elems[i] is that checkbox, in Chrome or Safari it returns "", but Firefox or IE it returns "on".
Is there any way to use Javascript to return the "on" value in Safari or Chrome? In Chrome I use a jquery call that uses .val() and that actually returns "on", but I need a way to do this using Javascript in Safari.
Thanks!
EDIT:
I'm actually looking for the "value" attribute specifically since the "value" of a checkbox can be anything, like "cat" or "bike".

Use checked instead to see if a checkbox or radio input is selected.
If what you really want to do is get the value attribute, and not see if the checkbox is selected, then you need to set a value for the checkbox first. If nothing is set then you getting null is the normal behavior.
You can also replicate the Firefox and IE behavior by assigning on yourself as a default value:
var myVal = elems[i].getAttribute('value');
if(myVal === null)
myVal = 'on';

I think that it's because elems[i].getAttribute('value') is not what you should be using to get the state of a checkbox.
Try using elems[i].getAttribute('checked') or just elems[i].checked to get the state.
By the way, elems[i].getAttribute('value') can be shortened to just elems[i].value.
Just read your comment on another answer...
Here's the source for the .val() statement from the jQuery repo:
getVal = function(elem)
{
var type = elem.type, val = elem.value;
if (type === "radio" || type === "checkbox")
{
val = elem.checked;
} else if (type === "select-multiple") {
val = elem.selectedIndex > -1 ? jQuery.map( elem.options, function( elem ) {return elem.selected;}).join("-"):"";
} else if (elem.nodeName.toLowerCase() === "select") {
val = elem.selectedIndex;
}
return val;
}
That is pretty simple JavaScript, and you can just omit the .map() function.
Also, why not just test for the existence of the value property?
function niceValue(element)
{
if (element.value != '')
{
return element.value;
} elseif (element.checked) {
if (element.checked)
{
return 'on';
} else {
return 'off';
}
}
}
Good luck!

Related

Detecting an html attribute's value with a userscript?

I am trying to make myself a personal user script, but I need to detect an html attribute's value. For example:
<div id="a">Stuff</div>
<div id="b" value="false"></div>
How could I create an if statement in the script, that triggers if the "value" attribute of element b turns to true?
element = document.getElementById("b");
if(element != null) {
if (element.value == "true") {
// do something
}
}
Check out this link... it says that you can import JQuery into your userscript.
youtube video
You can then get the value of any attrubute using jquery API for attr
Jquery Api attr
which can be done like
var bAttrValue = $("#b").attr("value");
You then coulld write a function which takes in an Id and an attribute like
function GetAttributeValue(elemId, attribute)
{
//Todo: write checks to ensure the elemId exists and that it as the attribute;
var elemAttrValue = $("#"+elemId).attr(attribute);
return elemAttrValue;
}
You could then consume it like
var DivbValue = GetAttributeValue("b", "value")
if(DivbValue) //true
{
//do something
}
else //false
{
//do something
}
alternatively write this in JavaScript
function GetAttributeValue(elemId, attribute)
{
//Todo: write checks to ensure the elemId exists and that it as the attribute;
element = document.getElementById(elemId);
return element[attribute];
}

Simple jQuery form Validation: Checking for empty .val() failing in ie9 due to placeholder polyfill

New Issue / Answer
I am using an HTML5 placeholder polyfill which is causing ie9 to set the input's placeholder text as the value. So while in HTML5 browsers the val attribute is empty, in the below code ie9 is seeing it as filled in.
I'm using jQuery to make sure all fields are filled in. This works fine in ie10, webkit, and mozilla but fails in ie9.
What am I doing wrong here, and why won't this code work in ie9?
Thank you!
$('#quoteform .button.next').on('click',function(){
var $me = $(this),
$myParent = $me.parent(),
$nextStep = $myParent.nextAll('fieldset:not(.disabled)').first(),
validate;
// If we're on step2, make sure all fields are filled in
if($me.is('#quote-step2 .button') || $me.is('#quote-step1 .button')) {
$me.parents('fieldset').find('input:visible').each(function(){
var $me = $(this),
myVal = this.value;
if(myVal === '') {
$me.parent().addClass('warning');
validate = false;
return;
} else {
if(typeof validate === 'undefined')
validate = true;
}
});
}
if(validate === false) {
alert('Please fill out all fields before continuing.');
return false;
}
switchView($nextStep, $myParent);
});
I ran into a similar issue and my workaround was to also test the value against the placeholder string in addition to testing for an empty value. Since the polyfill replaces the input's value with the placeholder string the empty value is the value of the placeholder in IE9.
$me.parents('fieldset').find('input:visible').each(function(){
var $me = $(this),
myVal = this.value,
myPlaceholder = $me.attr('placeholder');
if(myVal === '' || myVal === myPlaceholder) {
$me.parent().addClass('warning');
validate = false;
return;
} else {
if(typeof validate === 'undefined')
validate = true;
}
});

jQuery 'OR' not working when looping through required input elements

I'm writing a small required HTML5 attribute fallback for various inputs. It's going pretty well so far, but I'm having trouble when checking a radio button is ':checked' and using the 'OR' || operator in the loop:
if (self.val() === '' || self.is(':not(:checked)')) {
For some reason when I add this it breaks the script slightly and will indicate that the input fields (type=text) are empty when they're not. Is there a better way at all to loop through and indicate the difference between an input type 'text' and 'radio'?
Here's the loop:
var reqClass = $('.required')
reqClass.each(function(){
var self = $(this)
// if empty
if (self.val() === '' || self.is(':not(:checked)')) {
// if it doesn't have require-checked class
if (!self.hasClass('require-checked')) {
self.addClass('require-checked')
self.parent().append('<span class="form-error">This field is required.</span>')
}
e.preventDefault()
//$('.form-submit').attr('disabled', true)
// if it's been checked, but there is a value now
} else if (self.hasClass('require-checked') && !(self.val() === '')) {
self.siblings('.form-error').hide()
}
})
Classes are obviously present for 'fallback' browsers and changed on the fly. Here's a JSFiddle, thank you for any help:
http://jsfiddle.net/cyncV/2/
A text box is indeed :not(:checked) (even if it has text in it), so the text boxes are showing as empty when they are not.
Perhaps something like
if (self.val() === '' || self.is(':checkbox:not(:checked)') || self.is(':radio:not(:checked)')
var self = this;
var empty = self.type=='checkbox' ? !self.checked : self.value=='';
if (empty) {
// do stuff
}
FIDDLE
There is a solution :
var checked = (self.is(':checkbox') || self.is(':radio')) ? self.is(':not(:checked)') : false;
if (self.val() === '' || checked) {}
Just add a little condition that if input is checkbox or radio, it look if it's checked, else it return false. Then pass the result into the if condition.

How to test if users has made any changes to a form if they haven't saved it

Basically the same functionality as stackoverflow when posting a question, if you start writing a post then try to reload the page. You get a javascript alert box warning message.
I understand how to check if the form has been changed, although how do I do the next step.
I.E: How to I check this when leaving the page, on here you get "This page is asking you to confirm that you want to leave - data you have entered may not be saved."?
EDIT: found correct answer here to another question https://stackoverflow.com/a/2366024/560287
I'm very sure that if you search, 'jQuery detect form change plugin', you will find something much more usable than this semi-pseudo code i'm about to write:
formChanged = function(form) {
form.find('input[type="text"], textarea').each(function(elem) {
if (elem.defaultValue != elem.value) {
return true;
}
});
// repeat for checkbox/radio: .defaultChecked
// repeat for ddl/listbox: .defaultSelected
return false;
}
usage:
if (formChanged($('form')) { // do something }
Note that this is to detect changes against the original rendered value. For instance, if a textbox has a value = "x", and the user changes it to "y", then changes it back to "x"; this will detect it as NO change.
If you do not care about this scenario, you can just do this:
window.formChanged = false;
$(':input').change(function() {
window.formChanged = true;
});
Then you can just check that value.
Yes, it is JavaScript as HTML is just a markup language.
Yes, jQuery can be used for this. It's preferable over vanilla JavaScript as it makes things easier, although it does add some overhead.
There are a number of ways to check if any of a form's controls have changed.
To check for changes from the default, most can be checked against the defaultValue property. For radio buttons, you should always have one checked by default, so check if it's still selected or not. Similarly for selects, set the selected attribute for the default option and see if it's still selected, and so on.
Alternatively, if all your form controls have an ID or unique name, you can collect all their values onload and then check their values when the form is submitted.
Another method is to listen for change events on each form control, but that is a bit over the top.
Here's a POJS version that takes the same approach as rkw's answer:
/*
Check if any control in a form has changed from its default value.
Checks against the default value for inputs and textareas,
defaultChecked for radio buttons and checkboxes, and
default selected for select (option) elements.
*/
function formChanged(form) {
var control, controls = form.elements;
var tagName, type;
for (var i=0, iLen=controls.length; i<iLen; i++) {
control = controls[i];
tagName = control.tagName.toLowerCase();
type = control.type;
// textarea
if (tagName == 'textarea') {
if (control.value != control.defaultValue) {
return true;
}
// input
} else if (tagName == 'input') {
// text
if (type == 'text') {
if (control.value != control.defaultValue) {
return true;
}
// radio and checkbox
} else if (type == 'radio' || type == 'checkbox') {
if (control.checked != control.defaultChecked) {
return true;
}
}
// select multiple and single
} else if (tagName == 'select') {
var option, options = control.options;
for (var j=0, jLen=options.length; j<jLen; j++) {
option = options[j];
if (option.selected != option.defaultSelected) {
return true;
}
}
}
}
// Not really needed, but some like the return value to
// be a consistent Type
return false;
}
Note that you need to be careful with select elements. For a single select, you should always set one option to selected, as if there is no default selected, some browsers will make the first option selected and others wont.

Simple way to check if placeholder is supported?

I want to use the HTML5 "placeholder" attribute in my code if the user's browser supports it otherwise just print the field name on top of the form. But I only want to check whether placeholder is supported and not what version/name of browser the user is using.
So Ideally i would want to do something like
<body>
<script>
if (placeholderIsNotSupported) {
<b>Username</b>;
}
</script>
<input type = "text" placeholder ="Username">
</body>
Except Im not sure of the javascript bit. Help is appreciated!
function placeholderIsSupported() {
var test = document.createElement('input');
return ('placeholder' in test);
}
I used a jQuery-ized version as a starting point. (Just giving credit where it's due.)
Or just:
if (document.createElement("input").placeholder == undefined) {
// Placeholder is not supported
}
Another way without making an input element in memory that has to be GC'd:
if ('placeholder' in HTMLInputElement.prototype) {
...
}
If you are using Modernizr, quick catch following:
if(!Modernizr.input.placeholder){
...
}
http://html5tutorial.info/html5-placeholder.php has the code to do it.
If you're already using jQuery, you don't really need to do this though. There are placeholder plugins available ( http://plugins.jquery.com/plugin-tags/placeholder ) that will use the HTML5 attribute where possible, and Javascript to simulate it if not.
I'm trying to do the same... here i wrote this
if(!('placeholder'in document.createElement("input"))){
//... document.getElementById("element"). <-- rest of the code
}}
With this you should have an id to identify the element with the placeholder...
I don't know thought if this also help you to identify the element ONLY when the placeholder isn't supported.
Hi there this is an old question but hopefully this helps someone.
This script will check the compatibility of placeholders in your browser, and if its not compatible it will make all input fields with a placeholder use the value="" field instead. Note when the form is submitted it will also change your input back to "" if nothing was entered.
// Add support for placeholders in all browsers
var testInput = document.createElement('input');
testPlaceholderCompatibility = ('placeholder' in testInput);
if (testPlaceholderCompatibility === false)
{
$('[placeholder]').load(function(){
var input = $(this);
if (input.val() == '')
{
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
});
$('[placeholder]').focus(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur().parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
}
A bit late to the party, but if you're using jQuery or AngularJS you can simplify the method suggested above without using any plugins.
jQuery
typeof $('<input>')[0].placeholder == 'string'
AngularJS
typeof angular.element('<input>')[0].placeholder == 'string'
The checks are very similar, as AngularJS runs jQlite under the hood.
NOTE: Placeholder DO NOT work in internet explorer in a way, it should work.
document.createElement("input").placeholder == undefined
Doesnt work in internet explorer 11 - document.createElement("input").placeholder return empty string
var testInput = document.createElement('input');
testPlaceholderCompatibility = ('placeholder' in testInput);
Doesnt work in internet explorer 11 - return true
'placeholder'in document.createElement("input")
Doesnt work in internet explorer 11 - return true
In theory, Internet explorer 11 is supposed to support placeholder, but in fact - when input get focus placeholder disappear. In Chrome placeholder showed until you actually type something, no matter on focus.
So, feature detection doesnt work in this case - you need to detect IE and show Labels.

Categories