Skip to content Skip to sidebar Skip to footer

Jquery Replace Text Without Erasing The List

The main idea is to make this code like the classic html select. The reason I do this is because I didn't figure out how to change the blue hover in option menu. Run code snippet

Solution 1:

Your inner-most statement should be:

$('#firstshow button b').text($(this).text());

The way you had it you used the a element object as the HTML code for the buttons text, but you don't want to assign the element, but its text. So:

  • Assign $(this).text()
  • Assign it with text() not with html() -- better practice.

Solution 2:

It's about the part .html(this) in your code. The this variable is a reference to the dom object that is being clicked. When you set this as the html of the displayed select value, it moves the dom object and replaces whatever was displayed.

To overcome this set the displayed value to the text value of the element that is being clicked.

jQuery(document).ready(function($){
  $("#firstshow .dropdown-menu li a").click(function(){		
        $('#firstshow button b').html($(this).text());
    });

});
<linkhref="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"rel="stylesheet"integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"crossorigin="anonymous"><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><divid="firstshow"><divclass="dropdown"><buttonclass="btn btn-default dropdown-toggle"type="button"data-toggle="dropdown"><b>36</b><spanclass="caret"></span></button><ulclass="dropdown-menu"><li><ahref="#">12</a></li><li><ahref="#">24</a></li><li><ahref="#">36</a></li></ul></div></div><scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"crossorigin="anonymous"></script>

Post a Comment for "Jquery Replace Text Without Erasing The List"