2

I am creating a bilingual form in which I have a select tag with multiple option tags inside. I wanna get that option with class "blah" and with value "1" and then select it as "selected" option.

I selected it based on class and then select based value but the result is null. Here is my code:

$('select').each(function (e, item) {

             var selectedEnglish = $(item).children("option[class='English']")
             var englishItem = selectedEnglish.find("option:selected").val();

             var farsiList = $(item).children("option[class='Farsi']")
             var farsiItem = farsiList.find("[value='" + englishItem + "']");

             farsiItem.attr('selected', 'selected');
    });

Whats more how can I get with one chain of statements?

this selected is populated in jquery:

$("#TitleId").html("");
            $("#TitleId")
                .html("<option value='' class='Farsi'>عنوان</option><option value='' class='English'>Title</option>");
            $.each(titles,
                function (key, value) {
                    $("#TitleId")
                        .html($("#TitleId").html() +
                            "<option class='Farsi' value='" +
                            value.Id +
                            "'>" +
                            value.Name +
                            "</option>"+
                            "<option class='English' value='" +
                            value.Id +
                            "'>" +
                            value.EnName +
                            "</option>");
                });
3
  • Can you provide some html for this code? Commented Jan 22, 2017 at 8:12
  • just to clarify, do you have one select for english and one select for farsi? Commented Jan 22, 2017 at 8:12
  • @changepicture I have multiple select element. in each "select", there is 2 options with same value for every Item ,but with different class and text. I am going to switch between languages by showing/hiding based on their class. Commented Jan 22, 2017 at 8:15

1 Answer 1

3

If you want to get the option with class "blah" and value "1", this is your query:

$('select option[class=blah][value="1"]')

If you want to select that option you can simply do:

$('select option[class=blah][value="1"]').attr('selected', 'selected');
Sign up to request clarification or add additional context in comments.

2 Comments

for first time it changes the selected item. but not for second time.
Unless you are changing the class or value, it should continue to work correctly. In case you are changing the class or value, you need to update the query accordingly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.