Vivek
Vivek

Reputation: 11028

how can i find closest span?

let's say i am having fallowing html structure-

<div data-theme="a" class="ui-btn ui-btn-icon-right ui-btn-corner-all ui-shadow ui-btn-up-a">
    <span class="ui-btn-inner ui-btn-corner-all">
        <span class="ui-btn-text">Select One</span>
        <span class="ui-icon ui-icon-arrow-d ui-icon-shadow">
        </span>
    </span>
    <select onchange="selectState(this,'ADDR_SHIP_STATE')" id="ADDR_SHIP_STATE" name="ADDR_SHIP_STATE"> 
        <option>Hi</option>
        <option>Hello</option>
        <option>How</option>
        <option>are</option>
        <option>you</option>
    </select>   
</div>  

what i am trying to do is on change of select box, take the text of selected option and place it inside span(replace select one with this data) having class name ui-btn-text

below is the code which i ahve tried so for without any luck

function selectState(id,stateId){
var selectedState = $("#"+stateId+" option:selected").text();
$(id).closest("ui-btn-text").text(selectedState);
}

Please suggest me how can i do this..

Upvotes: 3

Views: 5435

Answers (3)

ipr101
ipr101

Reputation: 24236

Try -

function selectState(id, stateId) {
    var selectedState = $("#" + stateId + " option:selected").val();
    $(id).parents('div').find(".ui-btn-text").text(selectedState);
}

This will -

  1. Find the parent 'div' of the 'select' element
  2. Use find to get the .ui-btn-text element contained in the parent div

Demo - http://jsfiddle.net/H2pea/1

Upvotes: 2

JMax
JMax

Reputation: 26591

.closest()ref will progress up the DOM but won't get down like .parents() does (btw, you didn't add the . (dot) for the class search but this is probably a typo)

Here is a try:

$(id).parent().find(".ui-btn-text").text(selectedState);

Upvotes: 5

dfsq
dfsq

Reputation: 193261

Using attributes like onchange is not really unobtrusive way if you use jQuery. This is better:

$('#ADDR_SHIP_STATE').change(function() {
    $(this).prev().find('.ui-btn-text').text($(this).val());
});

Upvotes: 1

Related Questions