Ryan
Ryan

Reputation: 89

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

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!

Upvotes: 0

Views: 1855

Answers (2)

Zecc
Zecc

Reputation: 4340

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);

Upvotes: 1

user736788
user736788

Reputation:

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!'); });

Upvotes: 0

Related Questions