0

I have a drop-down-menu with a list from my C# model. Now I want to change a value based on what I choose from the menu.

$(document).ready(function() {
  $("#Bereich").val('@Model.Bereich').change('click', function() {
    $("select option:selected").each(function() {
      if ($(this) == "Something") {
        $('#kst').val(123);
      }
      
      if ($(this) == "Somethingelse") {
        $('#kst').val(345);
      }
    });
  }).change();
});

I am quite new to jQuery so I am not sure how to get an element from a list.

0

1 Answer 1

1

There's two main issues in your code. Firstly change('click', fn) isn't valid syntax. Given that we're dealing with a select element I assume you're trying to create a change event handler so the code should be on('change', fn) instead.

Secondly, $(this) will give you a jQuery object. This will never be equal to a string value so the conditions never hit. I assume you're trying to test the values of the selected items to use val() for this.

Note in the following example that I stored #kst in a jQuery object and referenced it repeatedly where needed to save accessing the DOM, which is where most performance is lost in JS. Also note that you can access val() directly from the select element - you don't need to retrieve the option:selected element within it.

jQuery($ => {
  let $kst = $('#kst');

  $("#Bereich").val('@Model.Bereich').on('change', function() {
    $("select").each(function() {
      let value = $(this).val();
      
      if (value === "Something") {
        $kst.val(123);
      } 
      
      if (value === "Somethingelse") {
        $kst.val(345);
      }
    });
  }).change();
});
Sign up to request clarification or add additional context in comments.

3 Comments

Unfortunately the answer didn't work for me. Can the Problem be the id or that use @Html.DropDownListFor? @Html.DropDownListFor(m => m.SelectedBereich, Model.Bereich, "Bereich auswählen", new { @id = "Bereich", @class = "form-control", @Required = true })
That MVC control will still generate a standard HTML select element so the above should work. Could you please copy the HTML output from the browser and paste it in to your question so we can create a working example of the issue
Thanks for reminding me to look at the HTML output. The values weren't strings but numbers. "Something" had the Value 1 so instead of comparing it to the Value "Something" I should have compared it like this: value === "1" That change fixed it.

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.