开发者

Webkit checkbox default value is null?

开发者 https://www.devze.com 2023-01-27 05:45 出处:网络
When using a WebKit b开发者_运维技巧rowser (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\".

When using a WebKit b开发者_运维技巧rowser (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!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号