I have a view in MVC and it contains a button that should call a javascript function when clicked. The problem is the function is running when the view is loaded instead of when the button is clicked.
<label for="structureParameter">Choose a structure parameter</label><select id="structureParameter" name="structureParameter">
<option disabled="disabled" selected="selected">...</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<input type="button" id="submit" value="submit" />
<script type="text/javascript">
function setStructure() {
var selectElement = document.getElementById("structureParameter");
var pageType = selectElement.value
return pageType;
}
$(document).ready(function () {
$('#submit').onclick = setStructure();
})
</script>
The function setStructure() is being run at load instead of when the button is clicked, so document.getElementById("structureParameter") is not yet set. How can only run setStructure() once the button is clicked?
I tried moving $('#test').onclick = setStructure(); outside of document.ready and it doesn't help.