Update text input field dynamically using two select menus with Javascript

风格不统一 提交于 2019-12-24 20:29:29

问题


I am trying to figure out how to dynamically update a text input field when a user changes the option in one or two HTML select menus. I have included my code below showing how it currently works.

$('tickets').addEvent('change', function() {
    if($('tickets').value > 0)
    {
        var cells = $$('.ticket2');
        cells.each(function(cell) { cell.setAttribute('style','display:none;');});
        var cells = $$('.ticket3');
        cells.each(function(cell) { cell.setAttribute('style','display:none;');});
        var sumValue = '$' + (100 * $('tickets').value + 10 * $('fiftytickets').value) + '.00';
        $('ordertotal').value = sumValue;
        $('ticket1heading').setHTML('Ticket(s)');
    } else {
        var cells = $$('.ticket2');
        cells.each(function(cell) { cell.setAttribute('style','');});
        var cells = $$('.ticket3');
        cells.each(function(cell) { cell.setAttribute('style','');});
        $('ticket2heading').setAttribute('style','text-align:center; font-weight:bold;');
        $('ticket3heading').setAttribute('style','text-align:center; font-weight:bold;');
        $('ordertotal').value = '$' + 250 + '.00';
        $('ticket1heading').setHTML('Ticket 1');
    }
});

The tickets select menu correctly affects the ordertotal text input field, but the fiftytickets select menu does not. I need the two to work independently of each other, but when each is changed, to affect the value of the ordertotal text input field.

Any assistance is greatly appreciated.

Thank you.

Mike


回答1:


as said by JoDev, the select element's object is referenced with $('#tickets') and not just $('tickets'). also, I don't think that there is a value property in jquery for a select element. you can get the value with the val() function.

Created a little fiddle for you here here

$('#tickets').change(function() {
   $('#output').val($(this).val() + " - " + $('#fiftytickets').val());
});
$('#fiftytickets').change(function() {
   $('#output').val($('#tickets').val() + " - " + $(this).val());
});


来源:https://stackoverflow.com/questions/17045981/update-text-input-field-dynamically-using-two-select-menus-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!