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>
</select>
<input type="image" name="itemid" value="<?=$itemid?>" src="add.png" onclick="window.parent.newAddItem(this.value,form1.elements["option1"].value)" />
</form>
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!
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);
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.
Native:
var onclick = function() { alert('you clicked me!'); };
var element = document.getElementById('some_element');
document.addEventListener ? element.addEventListener('click', onclick, false) : element.attachEvent('onclick', onclick);
jQuery
$('#some_element').click(function() { alert('you clicked me!'); });