Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Select list, selected text value rather than the value

building on my last question jQuery getting values from multiple selects together

I have the select list like:

  <select name="access" class="change" id="staff_off"  runat="server">
                <option value="8192">Off</option>
                <option value="8192">On</option>
  </select>

And I basically want to add or subtract the value of the options if it's off, subtract if it's on add it. It's going to be stored in a cookie (it uses bitwise)

The jquery I have is:

<script>

        $(document).ready(function(){
           var currentAccess = $.cookie("access");
        })

        $("select").change(function () {
            var currentText = $(this).text()
            var value = $(this).val()

              $.cookie("access", value, { expires: 24 });

              alert(currentText);

              alert( $.cookie("access") );

            })

    </script>

I'll do the addition in the change function. The thing I can't work out is how to get the text of the select to do an if statement (so if it's yes, add the value, if it's no, subtract the value)

Tom

like image 247
MissCoder87 Avatar asked Feb 08 '12 13:02

MissCoder87


People also ask

How do I get the text value of a selected option jQuery?

We can select text or we can also find the position of a text in a drop down list using option:selected attribute or by using val() method in jQuery. By using val() method : The val() method is an inbuilt method in jQuery which is used to return or set the value of attributes for the selected elements.

How do I get selected text option in select?

Use the selectedIndex Property We can get the index of the selected item with the selectedIndex property. Then we can use the text property to get the text of the selected item. We create the getSelectedText function that takes an element as the parameter. Then we check if selectedIndex is -1.


2 Answers

If you're looking for the inner text of the selected <option> element, you can use the :selected selector to match it, then call the text() method:

var currentText = $(this).find(":selected").text();

Or, alternatively:

var currentText = $(":selected", this).text();
like image 154
Frédéric Hamidi Avatar answered Oct 08 '22 06:10

Frédéric Hamidi


To get the text of the selected item:

var value = $("#staff_off :selected").text();

I'd also suggest (if you're using HTML5) that using the data-x attribute to store the flag whether to add or subtract the value would be more semantic. Like this:

<select name="access" class="change" id="staff_off"  runat="server">
    <option value="8192" data-factor="-1">Off</option>
    <option value="8192" data-factor="1">On</option>
</select>

Then to get your final value to apply to the total you simply multiply the value by the data-factor attribute.

like image 44
Rory McCrossan Avatar answered Oct 08 '22 07:10

Rory McCrossan