2

ORIGINALLY; I had a button trying to call a function but nested inside of a form, the button will trigger submit form event by default: The advice was to add a to the button tag and I was able to get past my original problem.

My new problem is:

So I have these buttons: j

And I want to have these buttons trigger whether or not a date field is hidden or not.

    else if (question.Expected_Answer_Type == "Date")
{
    <input type="button" value="Add a Date @ViewBag.QuestionID" onclick="makeDateVisible(#@ViewBag.QuestionID)">

    @Html.TextBoxFor(m => m.QuestionnaireAnswers[i].Answer, Model.Date.ToString("M/d/yyyy"), new { @class = "form-control date hidden", @id = ViewBag.QuestionID }) if (Model.QuestionnaireAnswers == null)

    {
        <script>
            $(document).ready(function () {
                    $('#@(ViewBag.QuestionID)')
                        .val("@(DateTime.Today.ToShortDateString())");
                }

            );
            function makeDateVisible(@ViewBag.QuestionID) {
                alert("Hello");
            } 

        </script>
    }
}

I can't seem to get the Alert inside the makeDateVisible to trigger.

inside the browser.... I get the error: Uncaught SyntaxError: Invalid or unexpected token and the red line appears at the end of this line:

  <input type="button" value="Add a Date @ViewBag.QuestionID" onclick="makeDateVisible(#@ViewBag.QuestionID)">
2
  • 1
    buttons inside a form I believe innately submit. You could use event.preventDefault on each button element, or you can simply change the markup and replace the button tags with input tags with a type of button Commented Mar 20, 2019 at 19:08
  • 1
    Add type=“button” to the buttons. They do not need to be inputs for this to work. This should prevent the behaviour explained by zfrisch. Commented Mar 20, 2019 at 19:16

2 Answers 2

1

You should pass #@ViewBag.QuestionID in quotes then it will be treated as string argument

Otherwise, it is treated as variable thus error is generated.

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

Comments

1

Instead of a Button tag use an input tag, and add type=“button” to the tag and this should fix your issue. I linked a website for reference.

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/button

1 Comment

I've updated the question... if you are able to let me know what you think is going on here--I'd be glad to mark this as the accepted answer. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.