Using onClick to call a JavaScript Function - using form element values...?

Go To


I am having some issues with using javascript to get form element values and then using those values to call a function using the 'onClick' attribute.

<form name="form1">
<select name="option1">
<option value="1">Option 1</option>
<input type="image" name="itemid" value="<?=$itemid?>" src="add.png" onclick="window.parent.newAddItem(this.value,form1.elements["option1"].value)" />

I swear this should work? Can anyone advise me if this is something I should be doing, or is there a "best practice" method that is different.

Thanks in advance!

2012-04-03 21:12
by Ryan
What's oForm set to - scottheckel 2012-04-03 21:15
form1 - sorry, I missed that, it's set above in the onload. I tried to trim the code to something that was just the issue...! doh - Ryan 2012-04-03 21:20


Your problem probably comes because you're trying to access a 'value' property of the 'select' element instead of the selected option. Try this instead:

// On your onclick event handler:
var option1 = form1.elements["option1"];
var selectedOption = option1.options[option1.selectedIndex];
window.parent.newAddItem(this.value, selectedOption.value);
2012-04-03 21:25
by Zecc
Zecc! Thank you for that. Worked perfectly! : - Ryan 2012-04-03 21:37
You're welcome. You can get the option's text using selectedOption.text btw - Zecc 2012-04-03 21:41


From what you've posted, oForm is undefined.

Avoid in-line event handlers like you've got there. Instead, bind the event handler centrally. This keeps JS out of your HTML.


var onclick = function() { alert('you clicked me!'); };
var element = document.getElementById('some_element');
document.addEventListener ? element.addEventListener('click', onclick, false) : element.attachEvent('onclick', onclick);


$('#some_element').click(function() { alert('you clicked me!'); });
2012-04-03 21:19
by NoName
Hi Andrew, thanks for your response. My issue is that the input boxes whose data I wish to access is in a jQuery fancybox, which is then closed... so that data would be lost I think? oForm is defined earlier. apologies, I missed that. replace oForm with form1 if it makes it clearer... I'll edit above.. - Ryan 2012-04-03 21:26