0

I have a select element with several options like this:

<select onChange="foo(this)">
   <option value="ok" selected>..</option>
   ....
   <option value="no">..</option>

I'm working with django (don't know if that matters honestly..) and in my onChange event of the select tag I should put window.location.href=this.value but it's not what I want since i need to make some changes to this.value..

My idea was to create a foo function passing the select item and then modify the onChange event and fire it afterwards.

I searched for some help and I found several options.. 1) How can I trigger an onchange event manually?

2) Trigger "onchange" event

and other examples as well that I don't remember but I use down in the example. None of them are working for me.

This is what I tried so far in my foo function:

<script>
    function foo(obj)
    {
        if (condition)
        {
            obj.onChange = "window.location.href="+ obj.value;
            //obj.onChange(); //1 option I found on the net was to call onChange this way 
        }
        else
        {
            obj.onChange = "window.location.href="+ obj.value.replace('/A/', '/R/'); // this is the update I need to apply based on the condition

            //obj.fireEvent("onChange"); // another solution

            // another solution
            if ("createEvent" in document) {
                var evt = document.createEvent("HTMLEvents");
                evt.initEvent("change", false, true);
                obj.dispatchEvent(evt);
            }
            else {
                obj.fireEvent("onchange");
            }
        }
    }
</script>
  • "but it's not what I want since i need to make some changes to" - i read the entire question many times but i still dont understand what's your problem and this particular sentence. Explain please – lucifer63 Aug 28 '19 at 23:20
  • ```this.value``` could be modified based on some conditions (those in the foo function) so I can't simply put ```onChange=window.location.href=someval``` because that ```someval``` should be modified before the onChange event fires.. – user8565094 Aug 28 '19 at 23:23

1 Answers1

1

If I'm not missing anything, you don't have to manually trigger onchange, as it's already triggered. You just have to return the modified value from your foo function.

So instead of obj.onChange = try return and remove the whole createEvent code.

<script>
function foo(obj)
{
    if (condition)
    {
        return obj.value;
    }
    else
    {
        return obj.value.replace('/A/', '/R/');
    }
}

And on your foo call onchange="window.location.href=foo(this)"

Michalis Garganourakis
  • 2,872
  • 1
  • 11
  • 24