i’m new into JS. I have done 2 simple functions to change value and onclick-event for an input-button.
function doAjaxRequest(url, divID, buttonID) {
$(divID).html('<img src="images/loader.gif" />');
setTimeout(function(){ $(divID).load(url); }, 600);
setTimeout(function(){ $(buttonID).attr({
value: 'Schliessen',
onClick: 'clear_div(\''+url+'\', '+divID.id+', '+buttonID.id+')'
});}, 600);
};
function clear_div(url, divID, buttonID) {
$(divID).empty();
$(buttonID).attr({
value: 'Mehr...',
onClick: 'doAjaxRequest(\''+url+'\', '+divID.id+', '+buttonID.id+')'
});
};
functions call is
<div id="div1"></div>
<input type="button" id="button1" onClick="doAjaxRequest('test.html', div1, button1);" value="More..."/>
the doctype i’m using for my homepage is
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
the functions both work correctly in IE but in FF they only work if i set the doctype to
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
i also tryed the “loose.dtd” with no effect.
What am i doing wrong with JS?
Hope someone can help me.
Greets
Joe
The problem is probably that
onClickshould beonclick(case is significant in attributes in XHTML). But there are a couple of problems.In your markup here:
You haven’t put quotes around
div1orbutton1, which means you’re relying on the browser dumping those symbols in the global namespace because they’re the IDs of your elements. That’s fairly common (IE and some others do it), but it’s not universal. Instead, I’d pass strings and then look them up properly.Since you’re using jQuery, there’s no reason to (and several reasons not to) use
onclickattributes.So:
And similarly, your button hookup originally should be:
…rather than using the
onclickin the HTML. That code needs to appear after the button in the HTML (it’s fairly common to recommend puttingscripttags at the bottom of the document, just before the closing</body>tag), or you can wrap it in a jQueryreadyhandler:…so it runs only when the DOM has loaded.
Notes:
unbindto remove all previousclickhandlers before adding our new one.And finally: Rather than removing the old
clickhandler and putting in a new one, I think I’d probably just have the click handler change its behavior based on some flag.