Mr.SH Mr.SH - 5 months ago 9
HTML Question

Jquery changing value of text with select LI

I have one drop down box with UL & LI like below:

<ul class="dropdown-menu" id="rmenu" role="menu">
<li><a href="#" data-value="photo">photo</a></li>
<li><a href="#"data-value="video">video</a></li>
<li><a href="#"data-value="audio">audio</a></li>
</ul>
<input type="hidden" name="search_param" value="all" id="search_param">


I also have one hidden field as show above, now I want to change value and also name of hidden field based on value select in LI.

I write
jquery
code as below:

<script type='text/javascript'>
$("#rmenu").on("click", "a", function(e){
e.preventDefault();
var $this = $(this).parent();
$("#search_param").val($this.data("value"));
$("#search_param").name($this.data("value"));
});
</script>


But it is not working and not changing even value of name, I have tried all options but no luck.

Answer

There is no method name() in jQuery. For changing name attribute use attr() method instead.

$("#search_param").attr('name',$this.data("value"));

Also there is no need to get parent element, since data attribute set to a tag not to li.

var $this = $(this);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="dropdown-menu" id="rmenu" role="menu">
  <li><a href="#" data-value="photo">photo</a>
  </li>
  <li><a href="#" data-value="video">video</a>
  </li>
  <li><a href="#" data-value="audio">audio</a>
  </li>
</ul>
<input type="hidden" name="search_param" value="all" id="search_param">
<script type='text/javascript'>
  $("#rmenu").on("click", "a", function(e) {
    e.preventDefault();
    var $this = $(this);
    $("#search_param").val($this.data("value"));
    $("#search_param").attr('name', $this.data("value"));
  });
</script>