Catch value of the data-atrabus and apply as text in another html element

1

I have a series of checkboxes in an interface that are already configured to display / hide other elements of the interface conditionally. In this same interface I have a div set to display messages to the user also conditionally depending on the checkbox selected.

I made this example in jsfiddle based on another script, which uses .each in the function to check inputs with a certain class and "print" the label text of these inputs in another element, in this case a <span>

It happens that in the "final" interface the elements checkbox and radio are customized and use the <label> tag to define their styles, which in turn, does not allow me to insert texts in <label> elements and so I can not use this function ...

Would there be another, simpler and more coherent way of displaying conditional messages extracted perhaps from the data- attribute?

Here is the code mentioned in the jsfiddle link.

    
asked by anonymous 20.05.2015 / 00:43

1 answer

3

Yes it does. check out this jsfiddle .

Just put, as you mentioned, data-<elemento> and use it. Note that in this case, data-text was used and to iterate over it, just use the jquery element $.data() by retrieving the tag text ie $.data("text") .

See HTML below:

<input type="checkbox" id="money" class="paymethods cash">
<label data-text="cash from data" for="money">In Cash</label>

<input type="checkbox" id="card" class="paymethods ccard">
<label data-text="card from data" for="card">Credit Card</label>

<div class="messages">You have chosen to pay <span class="pay-method" data-cash="In cash" data-card="Credit Card" data-paymix="In cash & Credit Card"></span> for your order upon delivery</div>

Note that in each label a data-text was placed with the value to be displayed in $.foreach() of the javascript code.

Next, see the code javascipt:

$(".paymethods").on("change", function(){
    var paymethods = [];
    $('.paymethods:checked').each(function(){        
        var payTypes = $(this).next().data("text");
        paymethods.push(payTypes);
    });
    $(".pay-method").html(paymethods.join(" & "));
})

The solution presented here, however, was preserved, however, if you retrieve the values of each label using $.text() , $.data("text") is used.

    
20.05.2015 / 00:53