views:

235

answers:

4
var check = function(){
   return false;
}
var submit = document.createElement("input");
submit.type = "image";
submit.src = "submit1.gif";
submit.onclick = check;
_submitSpan.appendChild(submit);

i created a form and append a input button, but i found it can't work in IE6, when click the button, the form auto submitted. can anybody help me.thank you.

A: 

For IE you might have to use the addAttribute method instead of .onclick()

submit.addAttribute('onclick', check);
Ben Rowe
i tried setAttribute(), but it doesn't work in firefox,the element is translated into <input type="image" src="submit1.gif" onclick="function () { alert('test'); }"/>
CunruiLi
@CunruiLi if(submit.setAttribute) { submit.setAttribute(); } else {submit.onclick = ;}. Differences in browsers mean this is unavoidable
Ben Rowe
the setAttribute is defined in all browsers,so the test "submit.setAttribute" may not work. but it would work with just a few modifications. thank you very much.
CunruiLi
A: 

From W3C HTML 4.01 Specs:

image

Creates a graphical submit button. The value of the src attribute specifies the URI of the >image that will decorate the button. For accessibility reasons, authors should provide >alternate text for the image via the alt attribute.

Do not use an <input type="image"> like a checkbox. The best way to make an image-checkbox is something like:

<label for="input">
<input id="input" style="display:none;" type="checkbox">
<img src="img.gif" alt="Check">
</label>

The label will treat the image as a checkbox, and automatically check the hidden checkbox if the image is clicked.

digitalFresh
+1  A: 

It might be an idea to hook into a 3rd party lib to handle event inconsistencies et al, YUI does a fine job, as does jquery.

Danjah
+1  A: 

Instead of explicitly setting the onclick attribute, try binding dynamically to the nodes' onclick event instead. Or perhaps you should be looking at the onsubmit event of the form.

function bindEvent(target, event, handler) {
    if (typeof target.addEventListener != 'undefined') {      
        target.addEventListener(event, handler, false);
    } else if (typeof target.attachEvent != 'undefined') {
        target.attachEvent('on' + event, handler); 
    } 
}


function check(e) {
   // Cancel W3 DOM events
   if (typeof e.preventDefault != 'undefined') {
        e.preventDefault();
   }
   // Cancel for old IE event model
   e.returnValue = false;

   return false;
}

var submit = document.createElement("input");
submit.type = "image";
submit.src = "submit1.gif";

_submitSpan.appendChild(submit);

// Bind click event to submit button...
bindEvent(submit, 'click', check);

// ...or perhaps you want to bind submit event to form
bindEvent(submit.form, 'submit', check);
nikc