简体   繁体   中英

How to synchronize data-attr and select box vaule?

I have two elements like:

<select id="data">
  <option value=1>hoge</option>
  <option value=2>fuga</option>
  <option value=3>hogehoge</option>
</select>

<a href="#1" data-id="1">hoge</a>
<a href="#2" data-id="2">fuga</a>
<a href="#3" data-id="3">hogehoge</a>

if I pick hoge on select box, I want data-id="1" to be selected and do some stuff (changing background etc.) using jQuery. If I click a[data-id="3"] , select box option 'hogehoge' to be selected vice versa.

any help would be appreciated.

Have a look at the last line in the click listener. You can trigger a change on an element which will call the corresponding listener instead of duplicating code.

 $(function() { $("#data").on("change", function() { $("a").removeClass("active"); // remove active class from all <a> $("a[data-id='" + $(this).val() + "']").addClass("active"); // add active class to link with corresponding data-id }); $("a").on("click", function() { $("#data option[value='" + $(this).data("id") + "']").prop("selected", true); // change the selected value $("#data").trigger("change"); // trigger change on #data to keep active link synced }); }); 
 .active { background-color: cornflowerblue; color: white; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="data"> <option value=1>hoge</option> <option value=2>fuga</option> <option value=3>hogehoge</option> </select> <a href="#1" data-id="1" class="active">hoge</a> <a href="#2" data-id="2">fuga</a> <a href="#3" data-id="3">hogehoge</a> 

$(document).ready( function(){
    $('a').click(function(){
        var id = $(this).data('id');
        $('#data').find('option[value='+id+']').prop('selected',true);
    )};
)};

I implemented the function in JSFiddle https://jsfiddle.net/dphf267u/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM