0

I am having some trouble .

I have the following view in my mvc application:

@model Radio_Management_Interface.Models.Blocks.blocks_create

@{
 ViewBag.Title = "Create Block";
 Layout = "~/Views/Shared/_Layout_main.cshtml";
}

<script>
 function getSelectedValue(sel) {
    window.alert("You change the combo box");
}
</script>


<div class="contenttitle">
  <h2 class="form"><span>Create A New Block</span></h2>
</div><!--contenttitle-->
@using (Html.BeginForm("Create", "Blocks", FormMethod.Post, new { @class = "stdform" }))
{
 @Html.AntiForgeryToken()
 <hr />
 @Html.ValidationSummary(true)

<p>
    <label>Select Network</label>
    <span class="field">
        <select name="select" onclick="getSelectedValue">
            @foreach (var item in Model.networks)
            {
                <option value="@item.networkID">@Html.DisplayFor(modelItem => item.name)</option>
            }
        </select>
    </span>
    @Html.ValidationMessageFor(model => model.block.start)
    <small class="desc">Name of the customer.</small>
</p>

The specific part of concern is:

<select name="select" onclick="getSelectedValue">

Why would this event not be being called? When I change the option in the select element on the site my JavaScript file doesn't run. Why could this be?

3 Answers 3

2

You want to be using the onchange event rather than onclick and pass it something as your method expects a parameter:

HTML:

<select name="select" onchange="getSelectedValue(this)">

JS:

function getSelectedValue(sel) {
    window.alert(document.getElementById(sel.value));
}
Sign up to request clarification or add additional context in comments.

Comments

1

I think you are missing the brackets, and also it should be the change event - onchange="getSelectedValue()"

Comments

0

A select uses the change event rather than onclick.

You can use jQuery to wire-up the event like this:

<script>
$( "select" )
  .change(function () {
    var str = "";
    $( "select option:selected" ).each(function() {
      str += $( this ).val() + " ";
    });
    window.alert( str );
  })
  .change();
</script>

http://api.jquery.com/change/

jQuery is unobtrusive so does not mix functionality up with html and gracefully handles errors rather than using the obtrusive method that is embedded into the html.

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.