I have 2 <span>s loaded from 2 different ajax scripts upon selection from a dropdown box; so my code is something like this:

<span id='room_rate'>1, 000</span> // loaded by an ajax script
<span id='total_misc'>500</span> // loaded by another ajax script

<input type='text' id='total'/>

<button type='button' id='compute_total'>Compute</button>

Question:

How to use event delegation to get the values from the 2 <span> and display it in the input text total after clicking the compute button ?


What I've tried:

$(document).ready(function () {
    $(this).on('click', 'span', function () {
        var room_rate = $('#room_rate').val();
        var total_misc = $('#total_misc').val();

        alert(room_rate + total_misc);
    });
});

What I get:

I don't get the alert and also I don't get an error in the console (F12).

有帮助吗?

解决方案

Read the fine manual...

.val()

The .val() method is primarily used to get the values of form elements such as input, select and textarea.

You probably want .text()

I'd also add the delegation to your button, not the spans, ie

$(document).on('click', '#compute_total', function(e) {
    e.preventDefault();

    $('#total').val($('#room_rate').text() + $('#total_misc').text());
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top