Pregunta

This is kinda confusing but i will do my best...

So i am writing a program that when someone clicks on the text, it subtracts the amount from the total. For example my html would look like this....

<form>
<input type='number' name='namea' id='ida' step='0.01'>
</form>
<div id='diva></div>

and then the javascript/jquery looks like this...

$('input[name=namea]').change(function(){
    var itemvalue = this.value;
    $('#diva').prepend('<p class = "pa">Blah blah ' + itemvalue + 'blah blah.</p>');
});
var total = 100;

and then this is the part i am confused on..

$('.pa').click(function() {
    //I want to find itemvalue of the one that i click on and subtract it from total.
})

so i can find the current value of itemvalue... but how do i find it of a string that was prepend a few strings ago.

Thanks in advance for the help.

¿Fue útil?

Solución

Since you are clicking on the dynamically added element, you can store the itemvalue as data to the element

Ex

jQuery(function($){
    $('input[name=namea]').change(function(){
        var itemvalue = this.value;
        var pa = $('<p />', {
            class: 'pa',
            html: 'Blah blah ' + itemvalue + 'blah blah.'
        }).data('itemvalue', itemvalue).data('otherdata', 'othervalue')
        $('#diva').prepend(pa);
    });

    $('#diva').on('click', '.pa', function() {
        alert($(this).data('itemvalue'))
        alert($(this).data('otherdata'))
    })
})

It will give the values of itemvalue n time back

Demo: Fiddle

Otros consejos

try this

html+script :

<head>
    <script>
    function substract(){
        var a = document.forms.yourform.input.value;
        var total = document.forms.yourform.total.value;
        var b = total-a;
        document.yourform.hasil.value= b;
    }
    </script>
</head>
<body>
    <form name="yourform">
        <input name="total" type="text" oninput="substract(this.value)" >
        - <input name="input" type="text" oninput="substract(this.value)">=
        <input name="hasil" readonly="readonly" >
    </form>
</body>

may it helps you :D

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top