简体   繁体   中英

using select and option javascript/jquery getting the wrong data-value using (this).data(“value”)

I have this code that send that data value to my server

$("#choiceamountmonthly").change(function () {
    var monthamountblock = $(this).data("value");
    alert("maandelijks pakket gekozen");

    $.getJSON(
        "server/ajax.php",
        {request:"addMonthsToCart", MonthsToCart: monthamountblock},
        function (data) {
            switch(data.response){
                case "success":
                    alert("Met succes toegevoegd");
                    break;
            }
        }
    );
});

Here it gets the data-value.

<select id="choiceamountmonthly" data-value="1000" name="subscription_choice" title="subscription_choice">
    <option data-value="0" >-Kies het aantal maanden-</option>
    <option data-value="3">3 maanden</option>
    <option data-value="5">6 maanden</option>
    <option data-value="9">12 maanden</option>
</select>

In my code here it takes the data-value of the select so it sends 1000 to my server. But I want to send the data-value of the option to my server. How can I do this?

Instead of:

var monthamountblock = $(this).data("value");

What you need is:

var monthamountblock = $(':selected', this).data("value");

This grabs the selected option's data from the select, rather than the select's data itself.

Hope this helps!

you can also use only value (instead of data-value ) for select options:

<select id="choiceamountmonthly" 
        data-value="1000" 
        name="subscription_choice" 
        title="subscription_choice">
  <option value="0" >-Kies het aantal maanden-</option>
  <option value="3">3 maanden</option>
  <option value="5">6 maanden</option>
  <option value="9">12 maanden</option>
</select>

than you can grab it like this:

var monthamountblock = $(this).val();

plunker: http://plnkr.co/edit/jtMdP3E2LJMBs6CzBzLQ?p=preview

from what i can see, you dont need the data-value on the select. This seems to be overriding the data-value of the options. The select should just need the name, no value.

IE:

`<select id="choiceamountmonthly" name="subscription_choice" title="subscription_choice">
    <option data-value="0" >-Kies het aantal maanden-</option>
    <option data-value="3">3 maanden</option>
    <option data-value="5">6 maanden</option>
    <option data-value="9">12 maanden</option>
</select>
`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM