user_v12
user_v12

Reputation: 589

How to use selected in option attribute in name attribute using Javascript or jQuery?

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.

Upvotes: 5

Views: 153

Answers (6)

Buggxs
Buggxs

Reputation: 31

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

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

Upvotes: 2

digout
digout

Reputation: 4252

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

Codepen

Upvotes: 1

shankar upadhyay
shankar upadhyay

Reputation: 941

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');

Upvotes: 1

Frost
Frost

Reputation: 11

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> 

Upvotes: 1

Gagandeep Singh
Gagandeep Singh

Reputation: 1005

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.

Upvotes: 0

DarkBee
DarkBee

Reputation: 15639

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>

Upvotes: 3

Related Questions