简体   繁体   中英

javascript add value to id based on select option value conditional

First off, I know I should know this. I am just not connecting the dots.

I have jquery working with a select menu so that when an option is selected, it's value is added to a hidden id in my form.

What I need, is that when an option is selected in this same select menu, depending on which option is selected, an email becomes the value in a different hidden id in the form.

I have an if conditional in my jsfiddle but it is not working. Any help is appreciated. Thanks! Peter T

        jQuery(document).ready(function() {
      // pass the title of the selected topic option to a hidden 'topic' form field
      jQuery('select#recipient_email').change(function() {
          var topic = jQuery('select#recipient_email option:selected').attr('title')
            // set the hidden input's value
            jQuery('#college2').val(topic);
            //var topic_var = jQuery('#college2').val(topic);
            if ((jQuery('#college2').val(topic)) == "Var 1")
            {
                $("#recipient_email_user").val("John.Doe@mail.com");
            }
            if ((jQuery('#college2').val(topic)) == "Var 2")
            {
                $("#recipient_email_user").val("Jane.Doe@mail.com");
            }
      })
    }) 

jsfiddle

This line is wrong

if ((jQuery('#college2').val(topic)) == "Var 1")

You are setting the value and it returns the jQuery object, it is the equivilant of jQuery('#college2') == "Var 1"

If should just be

if (topic == "Var 1")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM