We help IT Professionals succeed at work.

Detect Value in Select Using JavaScript Only (No jQuery)!

If you go to https://apply.essexcredit.com/ on the first page, you'll see a select "What type of loan are you interested in? ". I need to set an event listener on this element and grab the value being selected.(RV or Boat).  Javascript only. Please see image

Screenshot of select
*** I can't touch/change the code on the page. I have to use a TMS to inject my code. ***

Thanks!
Comment
Watch Question

Daniel PineaultPresident / Owner CARDA Consultants Inc.
CERTIFIED EXPERT
Distinguished Expert 2018

Commented:

I think this is what you are after


BLINK LINK REMOVED

Author

Commented:

Hi Daniel,

Unfortunately that won't work. It is a SPA and I'm using a TMS.  I have to attach an event listener to it once it loads and then detect the value selected. Once the virtual page changes, I will detach the listener. 

Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019
Commented:
window.addEventListener("click",function() {

    var found = document.evaluate("//form/div/div/div/div/div/div/div/div/div/div/div/div/div/div/div[@class='option-selected']", document, null, XPathResult.ANY_TYPE, null).iterateNext();
    if(found) {
        var title = found.getAttribute("title" );
        if( title == "RV" || title == "Boat" ) {
            alert("RV or BOAT selected");
        }
    }

});

Open in new window


Capture-d-e-cran-2020-02-26-a--08.11.png

Author

Commented:

Leakim,

Did you mean for the second function to be a "remove"?


Thanks,

MJ

Author

Commented:

Thank you both!

leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
the second function?
your post said you want to detect a value when it change

the following line get the value and set it to title
do what you want with it
I use it to do an alert

var title = found.getAttribute("title" );

Open in new window

Author

Commented:

Hi,

No, originally your code was duplicated? It is not there any longer.


Thanks!

leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
you right, bad copy/paste copy/paste copy/past/... copy/paste
Michel PlungjanIT Expert
CERTIFIED EXPERT
Top Expert 2009

Commented:

Here is a shorter jQuery version


It will work as long as the select is the 4th in the page and needs to be tested to see if the value changed


 $(document).on("click", function() { console.log($("div select:eq(3)").val()) })