1

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.

1 Answer 1

2

Change the event handler to look like this:

$(document).ready(function () {
    $('#submit').click(function () {
        alert('hello, world!');
    });
})

In your case, replace the alert with a call to setStructure()

Fiddle: https://jsfiddle.net/mwatz122/ztc78z1e/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.