Vicky
Vicky

Reputation: 767

Find anchor tag using href value and change href value with new href value

This is the html code:

<td>
<a class="buttontext" href="/kkdmpcu/control/MilkDeliveryScheduleReport.txt?shipmentId=10306&amp;reportTypeFlag=milkDeliverySchedule" target="_blank" onclick="javascript:setSelectedRoute(this, 10306);" title="Milk Delivery Schedule">Delivery Schedule</a>
</td>
<td>
<a class="buttontext" href="/kkdmpcu/control/KVGenerateTruckSheet.txt?shipmentId=10306&amp;reportTypeFlag=abstract" target="_blank" onclick="javascript:setSelectedRoute(this, 10306);" title="Abstract Report">Route Abstract Report</a>
</td>

I have the href value. Using href value I should find the anchor tag and change the href value to new value using jQuery. This is the code I currently have which is not working:

$('a[href$=(existingUrl)]'); // existingUrl is the href value I have
    .attr('href', resultUrl);  // resultUrl is the url that I need to replace with existingUrl.
  
//The whole code I have Right now

function setSelectedRoute(existingUrl, shipmentId) {
         
        var updatedUrl = existingUrl.toString();
        var facilityIndex = updatedUrl.indexOf("facilityId");
        
        if(facilityIndex > 0){
            updatedUrl = updatedUrl.substring(0, facilityIndex -1);
        }
        var form = $("input[value=" + shipmentId + "]").parent();
        var routeId = form.find("option:selected").text();
        var resultUrl = updatedUrl + "&facilityId=" + routeId;
        alert(resultUrl);
        
        $('a[href='+existingUrl+']').attr('href', resultUrl);   
    }

Upvotes: 1

Views: 4244

Answers (2)

code-jaff
code-jaff

Reputation: 9330

this is not the href attribute, it is the a tag itself, that is first mistake, therefore existingUrl will get the object instead.

change the code like

function setSelectedRoute(existingUrl, shipmentId) {

        var updatedUrl = $(existingUrl).attr('href'); // first instance
        // or var updatedUrl = existingUrl.getAttribute('href');

        var facilityIndex = updatedUrl.indexOf("facilityId");

        if(facilityIndex > 0){
            updatedUrl = updatedUrl.substring(0, facilityIndex -1);
        }
        var form = $("input[value=" + shipmentId + "]").parent();
        var routeId = form.find("option:selected").text();
        var resultUrl = updatedUrl + "&facilityId=" + routeId;
        alert(resultUrl);

        $('a[href="'+$(existingUrl).attr('href')+'"]').attr('href', resultUrl);  //second instance
    }

for the second instance, you can directly use existingUrl

$(existingUrl).attr('href', resultUrl);

Upvotes: 0

Ram
Ram

Reputation: 144689

You should not use semicolon between the selector and the attr method, also if existingUrl is a variable you should concatenate it, try this:

$('a[href="'+existingUrl+'"]').attr('href', resultUrl);

Upvotes: 1

Related Questions