I want to set the selection state when adding pulldown items (option elements) in jQuery.

Asked 1 years ago, Updated 1 years ago, 42 views

Thank you for your help.
I have a problem creating a form-related page, so I would like to ask you a question.

Enter each item in one form and move to the next page.
Then, when you return to the original page from the transition destination, you can enter a select box or
You may want to retain and re-display the selected value for the pulldown box.

This time
for pulldown items (option elements) that dynamically retrieve values The selected setting for the selected item when retrieving the displayed or configured values is
I'm sorry that I couldn't reflect it well.

Use jquery to generate display and input values for the option element as shown below.

//value value, generated with text
$("#select_test").append($("<option>").val(hogeCd).text(hogeName)));

I have been able to reflect it so far, but when I try to reflect the selected condition further, it doesn't reflect well.
When I looked into it, I found out that

In terms of html, I want to reflect it like this.

<select id="select_test">
   <option value="1" selected="selected">Option 1</option>
</select>

This
selected="selected"
I would like to reflect the part when I use jquery to generate input values.

//value value, generated with text
$("#select_test").append($("<option>").val(hogeCd).text(hogeName)));

Is there a way to reflect the selected="selected" part in this description?

I would appreciate it if you could you help me?Thank you for your cooperation.

javascript html jquery css

2022-09-30 18:42

1 Answers

.prop will do it.

$("#select_test").append($("<option>").val(hogeCd).text(hogeName).prop("selected", true));

Below is a sample.

$(function(){
  $("#select_test").append($("<option>").val("1").text("value 1"));
  $("#select_test").append($("<option>").val("2").text("value 2").prop("selected", true));
  $("#select_test").append($("<option>").val("3").text("value 3"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select id="select_test">
<option value="">Please select</option>
</select>
</form>


2022-09-30 18:42

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.