5

I want to use “selected” in option attribute in name attribute using Javascript or jQuery. It means I want to use name="1" option as selected one when the page is loaded. I tried with the below code. But it not workes.

Code:

<select id="countryselect" name="country">
  <option value="1" name="0">Afghanistan</option>
  <option value="2" name="0">Albania</option>
  <option value="3" name="0">Algeria</option>
  <option value="4" name="1">Malaysia</option>
  <option value="5" name="0">Maldives</option>
</select>

Jquery:

$("#countryselect").$('option[name="1"]')

Demo: http://jsfiddle.net/muthkum/zYRkC/

Thank you.

1
  • you need to add selected attribute to the element, please check the answer below, thanks :) Commented Jun 18, 2020 at 6:43

6 Answers 6

3

You can pass a second parameter to the selector to define the scope

$('#countryselect').val($('option[name="1"]', "#countryselect").val());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="countryselect" name="country">
<option value="1">Afghanistan</option>
<option value="2" name="1">Albania</option>
<option value="3">Algeria</option>
<option value="4">Malaysia</option>
<option value="5">Maldives</option>
</select>

Sign up to request clarification or add additional context in comments.

Comments

2

Just put this line of code in your script-tag and it will work like you want.

$('#countryselect option[name="1"]').attr('selected',true);

Comments

1

If you want to go with dynamic assignment, you can go with

$("#countryselect").val(1) .

If selection of option is static and only want for initial load, then selected can be used for this like

<option value="4" selected>Malaysia</option> 

Comments

1

You can try it out here Please click on the link to see the code code pen link here

<select id="countryselect" name="country">
    <option value="1" name="0">Afghanistan</option>
    <option value="2" name="0">Albania</option>
    <option value="3" name="0">Algeria</option>
    <option value="4" name="1">Malaysia</option>
    <option value="5" name="0">Maldives</option>
</select>

you ca use the selector to set the "selected" attribute like this:-

$("#countryselect option[name='1']").attr('selected', 'selected');

Comments

1
var nameVal = $('[name=1]').attr('value');
$("#countryselect").val(nameVal)

Codepen

Comments

0

You can try something like this

$("#countryselect option[value='3']").attr("selected","selected");

and if you want to select by name value then use

$("#countryselect option[name='0']").attr("selected","selected");

It will set the selected attribute on that option.

Comments

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.