user2820678
user2820678

Reputation: 33

How to show a default value in dropdown using JQuery when page loads

Now on page load I need to select United States as my default value.

The code for that I am writing is :

$(document).ready(function(){
    if ($("input[name='contactAddress.id']").val() == "") {

        $(contactAddress.country).find('option').filter(function() {
            return this.text == 'United States';
        }).attr('selected','selected');
        $(contactAddress.country).val('United States');
    }
});

Dropdown Code :

 <tr>
            <th><s:text name="contactAddress.country"/>:</th>
            <td>
                <v:list var="countries" action="country" namespace="/"/>
                <s:select name="contactAddress.country"
                    value="contactAddress.country.id"
                    headerKey="" 
                    headerValue="-- Please Select --" 
                    list="countries"
                    listKey="id" 
                    listValue="name"/>                                                      
                <s:fielderror><s:param>contactAddress.country</s:param></s:fielderror>              
            </td>
            <th><s:text name="contactAddress.zipPostalCode"/>:</th>
            <td><s:textfield name="contactAddress.zipPostalCode" /></td>
        </tr>

But this is not working. I have been googling and tried many different syntaxes for that matter but nothing is working. Where Am I going wrong .Please help

Upvotes: 0

Views: 2756

Answers (2)

Scott Selby
Scott Selby

Reputation: 9580

did you try

$("select[name='contactAddress.country']")

instead of

$(contactAddress.country)

also you know that just writing

$(document).ready(function(){
    if ($("input[name='contactAddress.id']").val() == "") {
       $("select[name='contactAddress.country']").val('United States');           
    }
});

handles changing of the dropdown selected item

note :

jquery isn't understanding this

$('#contactAddress.country') 

that is looking for the child of "contactAddress" with a class of "country"

Upvotes: 1

Dani
Dani

Reputation: 1250

this should work

$(document).ready(function(){
    if ($("input[name='contactAddress.id']").val() == "") {

    var element = document.getElementById('#contactAddress.country');
    element.value = 'United States';

    }
});

you might not need the # in the ID name

Upvotes: 0

Related Questions