Trigger event of auto popup list selection via jav

2019-07-29 17:49发布

I have previously entered value 1111, 1222, and 1333 into a HTML text input. Now if I enter 1 to the text input, it should popup a list with value 1111, 1222, and 1333 as available options. How do you trigger an event when any one of these options is selected?

I have a javascript function that performs a calculation on values entered into the text input via "onkeyup" event. This works very well if the user just enter value via keyboard. However, it does not work if the user is selecting a previously entered value from the auto popup list.

I know we can turn off the auto popup list by adding autocomplete="off" to the form/text input. But is there any solution to make it work with the auto popup list? I have tried all available event options including "onchange", but none of those works.

The HTML code is very simple:

<input id="elem_id_1" name="output" type="text" value="0" onkeyup="update();"/>

The js function is very simple too:

function update() {
  var a = $('elem_id_1').value;
  $('elem_id_2').value = a / 100;
}

1条回答
淡お忘
2楼-- · 2019-07-29 18:51

Have you tried the onchange event? I'm not sure if it fires for auto-complete selection, but you could also try the onpropertychange event and check for the value property:

textInput.onpropertychange = function ()
{
    if (event.propertyName == "value")
        doCalculation();
}

This would also work on right-click->paste or right-click->cut, which wouldn't fire your calculation using your current method.

EDIT

It looks like you might have to use a combination of events and timers. Set an interval on focus of the edit and clear it on blur. I'd also use the onpropertychange for IE to make it more efficient and keep the keyup event to make it rather quick too.

//- If it's IE, use the more efficient onpropertychange event
if (window.navigator.appName == "Microsoft Internet Explorer")
{
    textInput.onpropertychange = function ()
    {
        if (event.propertyName == "value")
            doCalculation();
    }
}
else
{
    var valueCheck, lastValue = "";
    textInput.onkeyup = function ()
    {
        doCalculation();
    }
    textInput.onfocus = function ()
    {
        valueCheck = window.setInterval(function ()
        {
            // Check the previous value against (and set to) the new value
            if (lastValue != (lastValue = textInput.value))
               doCalculation();
        }, 100);
    }
    textInput.onblur = function ()
    {
        window.clearInterval(valueCheck);
    }
}

If your calculation routine is tiny (like a simple mathematical equation), I would just leave out the previous value check and run the calculation every 100ms.

查看更多
登录 后发表回答