jim
jim

Reputation: 1137

jquery cross browser copy text to textbox issue

Dropdown

In my site I have a set of SELECT dropdowns that are set up like this.

<OPTION class="addTitleTag">400</OPTION>

Search Box

There is also a search box that is like the following.

input type="text" class="textbox" onblur="search_SearchBlock_blur()" onfocus="search_SearchBlock_focus()" value="Search" name="g2_form[searchCriteria]" size="18" id="searchCriteria"

The Javascript

    jQuery(function() {
    jQuery('.addTitleTag').click(function() {
        titleText = jQuery(this).attr('text');
        jQuery("#searchCriteria").val(titleText);
        //$('#go_button').click(); //acts as if the search "go" button was clicked.
    });
});

The idea is when the Dropdown option is selected from the OPTION's, it takes the text of that option and copies it into the searchbox. The user then press's go on the searchbox to search for the text.This works fine in firefox. However, it does not fare well in Safari.I'm wondering what the issue is with it. I know that in a previous setup I did I used list tags (li) inside of an unordered list and safari seemed to be able to grab the text value fine. However, it does not grab the text from inside of the OPTION tag and I need to use the option tags in this case. I'm wondering if there is some sort of work around. Thank you!

Upvotes: 4

Views: 966

Answers (2)

Josh Mein
Josh Mein

Reputation: 28645

In order to get the selected text of a ddl with jquery you need to do the following:

$("#yourdropdownid option:selected").text();

.val will only get you the selected value

This would be in the case that your Value and Text are different of course

This can be seen from the question jquery-get-selected-text-from-dropdownlist asked on StackOverflow

Upvotes: 0

Sampson
Sampson

Reputation: 268364

You'll want to get the select element's current value when the select's change event fires:

$(".myselect").change(function(){
  $(".search").val( $(this).val() );
});

Online Demo: http://jsbin.com/apuba/edit

Note that this method doesn't require adding onblur or onfocus event-logic in your HTML itself. Instead, this will bind on its own provided you give it adequate selectors.

<input type="text" name="search" class="search" />

<select class="myselect" name="foo">
  <option>100</option>
  <option>200</option>
  <option>300</option>
</select>

Nothing further is needed in the HTML.

Update

You can bind multiple dropdowns to do this too. Suppose you have the following:

<select id="product_1">
  <!-- options -->
</select>

<select id="product_2">
  <!-- options -->
</select>

You could bind up both of these with the following:

$("#product_1, #product_2").change(function(){
  $(".search").val( $(this).val() );
});

Note that I add new drop-downs merely by modifying the selector.

Upvotes: 4

Related Questions