user1688181
user1688181

Reputation: 494

Set HTML attribute value using java Script

I have html drop down list,which has country list. Now I want to set current country as a default value of list. I found the JavaScript code for get country using Geolocation.

My code:

function getCountry(var name) {
    if(name==geoip_country_name()) {
        return "selected";
    }
}

Then I need to set the selected attribute of the option list.

I tried this:

<option value="Sri Lanka" selected="getCountry('sri Lanka')">Sri Lanka</option>

But this is not correct.
Basically I want to set selected attribute value using JavaScript function

How do I do that?

Upvotes: 0

Views: 1586

Answers (4)

closure
closure

Reputation: 7452

If you are using JQuery following line should solve your problem:

$('select').val(geoip_country_name());

If geoip_country_name returns names in lower case, While initializing the select list, value for each option be in lower case.

Upvotes: 0

MrCode
MrCode

Reputation: 64526

Use the window.onload event, and just set the dropdown's value. Keep in mind that your hard coded country names may differ from the geo service.

<script>
    window.onload = function(){
        document.getElementById("country").value = geoip_country_name();
    }
</script>

<select id="country" name="country">
<option value="Sri Lanka">Sri Lanka</option>
<option value="UK">UK</option>
<option value="USA">USA</option>
<select>

Upvotes: 4

user1726343
user1726343

Reputation:

The selected attribute is not automatically evaluated as JS code. Assuming you have stored the desired country name in the variable country, could try this instead:

var country = "Sri Lanka";
var select = document.getElementById('myselect'); //Change to the ID of your select element
for (var i = 0; i < select.options.length; i++){
    if(select.options[i].value == country)
        select.selectedIndex = i;
}

Upvotes: 0

Adrian
Adrian

Reputation: 2388

Basically you can do it like this:

<html>
<body>
  <select id="country">
  <option id="germany" value="Germany">DE</option>
  <option id="uk" value="UK">UK</option>
  <option id="usa" value="USA">USA</option>
</select>
<script>
  var selectedCountry =  'uk'; //getCountry
  var index = document.getElementById(selectedCountry).index;
  document.getElementById("country").selectedIndex=index;
</script>

Start the script after your select is rendered.

Note, that this example might not be best practice. I'm also not sure if it works in all browsers (Opera works). You might use an appropriate framework like JQuery, Mootools, ...

Upvotes: 0

Related Questions