简体   繁体   中英

Getting select value then add to custom html attribute

IS there a way i can get the selection a customer would make then add it to a custom html5 attribute?

I have a select mnu dynamically coming from a database which produces the following HTML:

  <select name="options">
    <option value="2 Tier &pound;250.00">2 Tier &pound;250.00</option>
    <option value="3 Tier &pound;350.00">3 Tier &pound;350.00</option>
    <option value="4 Tier &pound;450.00">4 Tier &pound;450.00</option>
   </select>

So basically if a customer selects option one I want to grab the value strip out the text and just get the numbers, and not refreshing the page or moving anywhere else (just yet) add this value to a custom attribute I;m using for a jQuery shopping cart.

 <div class="item" data-id="123" data-name="Some product name" data-price="VALUE_HERE">

I would presume jQuery to do this but not sure how so looking for some help, examples on how to do this please.

Is this something you are looking at ?

FIDDLE

 <select name="options">
    <option value="2 Tier &pound;250.00">2 Tier &pound;250.00</option>
    <option value="2 Tier &pound;250.00">3 Tier &pound;350.00</option>
    <option value="2 Tier &pound;250.00">4 Tier &pound;450.00</option>
   </select>
 <div class="item" data-id="123" data-name="Some product name" data-price="VALUE_HERE">

Javascript

$("select").change(function(){
   selectedValue = $(this).val();     
//alert(selectedValue);
var p = selectedValue.indexOf("£");
rest = selectedValue.substring(p+1);
$(".item").attr("data-price",rest)}).change();

Here you go :

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("select[name=options]").change(function() {
        var element = $(this).attr("rel");
        var tmp = $(this).val().match(/[-+]?[0-9]*\.?[0-9]+/g);
        var value = tmp[tmp.length-1];

        $('#'+element).attr('data-price',value);
    })
});
</script>
</head>
<body>
<select name="options" rel="item-1">
    <option value="2 Tier &pound;250.00">2 Tier &pound;250.00</option>
    <option value="3 Tier &pound;350.00">3 Tier &pound;350.00</option>
    <option value="4 Tier &pound;450.00">4 Tier &pound;450.00</option>
</select>

<div class="item" id="item-1" data-name="Some product name" data-price="" />
</body>
</html>

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