简体   繁体   中英

How to assign an ID to a dynamic dropdown select?

I want to assign a session ID (this will be hidden) whenever the first select dropdown is used. The session ID is the number 300, 301, etc. after the "day".

When a user selects something from the "preferred" dropdown it should assign the "300" value to the "sessionid" dropdown and simultaneously change the value of the "day" dropdown (which works already btw)

How do I do implement it properly?

Please see code below:

<select id="preferred" class="preferred" name="preferred">
  <option value="">- Select -</option>
  <option value="Mountain Dew">Mountain Dew</option>
  <option value="Seven Up">Seven Up</option>
</select>
<select id="day" class="day" name="day">
  <option value=""></option>
</select>
<select id="sessionid" class="sessionid" name="sessionid">
  <option value=""></option>
</select>

$(function() {
  var selectValues = {
   "Mountain Dew": {
   "Monday": "300"
  },
   "Seven Up": {
   "Tuesday": "301"
  }
};

var $preferred = $('select.preferred');
var $day = $('select.day');
var $sessionid = $('select.sessionid');

$preferred.change(function() {
  $day.empty().append(function() {
   var output = '';
   $.each(selectValues[$preferred.val()], function(key, value) {
   output += '<option value="' + key + '">' + key + '</option>';
  });
  return output;
  });
 }).change();
});

example : http://jsfiddle.net/creativemix/5ZWrE/2/

You can use Element.id = 'id' to set an id in javascript.

https://developer.mozilla.org/en-US/docs/Web/API/Element.id

In your code that would probably be something like this at the point where you want to assign the id:

$sessionid[0].id = $day.val();

But please note an id must start with a letter and numbers are generally bad practice even if it does work.

Putting the value you need in a hidden field is probably preferable over this solution.

Try this if you want to set the value of session id dropdown. Include this after setting the output variable in your fiddle.

$sessionid.empty()
     .append($("<option></option>")
     .attr("value",value)
     .text(value));

Here's a link to the fiddle.

But, as others already suggested, why not use a hidden text field to store the value?

To store the value in a hidden field,

<input type="hidden" id="hdnSessionId" />

And add this to the script.

$('#hdnSessionId').val(value);

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