How to change html attribute value with jquery

Tags: , ,



I have select tag of HTML I want to change /id/ with help jquery in data-ajax--url attribute

<select data-ajax--url="/live_search/Customer/id/name/name" class="form-control kt-select2 kt-live_search form-control-md" id="consignments_customername" data-placeholder="All">
                            <option></option>
                        </select>

Answer

Like this

NOTE Your attribute name is invalid.

$(function() {
  const $sel =  $("#consignments_customername");
  const dataurl = $sel.attr("data-ajax--url");
  $sel.attr("data-ajax--url",dataurl.replace(//id//,"/help/"));
  console.log($sel.attr("data-ajax--url"));
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select data-ajax--url="/live_search/Customer/id/name/name" class="form-control kt-select2 kt-live_search form-control-md" id="consignments_customername" data-placeholder="All">
  <option></option>
</select>

If you change the -- to an underscore, you could do this in plain JS

window.addEventListener("load",() => {
  const sel =  document.getElementById("consignments_customername");
  const dataurl = sel.dataset.ajax_url;
  sel.dataset.ajax_url = dataurl.replace(//id//,"/help/");
  console.log(sel.dataset.ajax_url);
})
<select data-ajax_url="/live_search/Customer/id/name/name" class="form-control kt-select2 kt-live_search form-control-md" id="consignments_customername" data-placeholder="All">
  <option></option>
</select>


Source: stackoverflow