user10404360
user10404360

Reputation:

Why I can't get the value of a select option html?

So I have listed a number of categories, each of these categories has a value of appropriate id, the idea is after the category is being changed to send ajax request to the server, but before that I have to get the id of the category I selected, the problem is that after each time I try to get the value I get this error message

app.js:1 Uncaught TypeError: Cannot read property 'toLowerCase' of undefined
at C.fn.init.val (app.js:1)
at sortByCategory (news:174)
at HTMLSelectElement.onchange (news:215)

The problem is that it returns me the whole window object and I don't know how to get just the value of the selected option.

html -

<select onchange="sortByCategory()" name="category">
                            @foreach($categories as $category)
                                <option value="{!! $category->id !!}">
                                    {{ $category->title }}
                                </option>
                            @endforeach
                        </select>

javascript -

 function sortByCategory(){
    var value = $(this).val();
    console.log(value);
    $.ajax({
        type:'POST',
        url:'/home/sortByCategory',
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        data : {
            category : 'bar'
        },
        success:function(data){
        }
    });
}

Upvotes: 0

Views: 3116

Answers (2)

Sarahshuffle
Sarahshuffle

Reputation: 182

when you want to get a value from a select you can to read its value from the html. In your case it would be something like: https://jsfiddle.net/jm4kLe65/11/

You need to pass the select object (this) to your sortByCategory() function, and from there you can access many of its properties. In your case you are only interested in its selected value which you can access by select.value

Upvotes: 1

Tibbelit
Tibbelit

Reputation: 1335

If you use an event handler (like "onchange") send this as an argument, like this:

function sortByCategory(el){
		alert($(el).val());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select onchange="sortByCategory(this)" name="category">
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
  <option value="4">Option 4</option>
</select>

A better solution would be to separate the JavaScript code from the HTML code like this:

$("#category").on("change", function() {
	alert($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select name="category" id="category">
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
  <option value="4">Option 4</option>
</select>

Upvotes: 1

Related Questions