Forum Moderators: open

Message Too Old, No Replies

Getting an image alt value from an innerHTML form

How can I grab the alt value and not the entire image uri?

         

JS_Harris

12:08 pm on Nov 20, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Here is the basic code:

<html>
<head>
<script type="text/javascript">
function word(object){
document.forms.test.one.value = object.innerHTML;
document.forms.test.two.value = "SOME TEXT!";
}
</script>
</head>
<body>
<div id ="somediv" onclick="word(this);">
Image
</div>
<form name="test">
<input type="text" name="one"></input>
<input type="text" name="two"></input>
</form>

Its simple, clicking on the Image inside of the div sends multiple values to multiple form input boxes HOWEVER the object.innerHTML command grabs the image uri in full and drops it any input box named "one". How can I make it grab the image alt text only instead of the entire image uri?

I need to change the "onclick="word(this);" to something like "onclick="word(this.?);" but the? is eluding me at 4 am.

penders

1:14 pm on Nov 20, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



How can I make it grab the image alt text only instead of the entire image uri?

I assume you mean image element?

To return the value of the alt attribute of the IMG element contained within the DIV (which you are passing to your function) you really need to traverse the DOM.

Assuming your DIV contains just one IMG, then your can modify your function:

function word(object){ 
// Get the value of the alt attribute of the first IMG element contained in 'object'
var alttext = object.getElementsByTagName('img')[0].getAttribute('alt');
document.forms.test.one.value = alttext;
document.forms.test.two.value = "SOME TEXT!";
}

(Not tested)

JS_Harris

2:04 pm on Nov 20, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Tested, Thanks penders. Works like a charm. You think I'd have the document object models memorized by now, then again tonight has been the usual. Code till 6am, work the regular job at 8am. I'm not sure what i'd do without webmasterworld!

Now I need to build an array on that. One text input box, multiple images. Tommorow night...