ponder275 ponder275 - 11 months ago 35
Javascript Question

Saving page field values with Struts2 using javascript with a link

I know from a previous question (page values are not loaded) I can't use a link to submit a form. I either need to make a button look like a link or use JavaScript. I have the following link inside of an iterator.

<s:iterator value="chosenShipperViewList">
<div class="col-sm-3 col-xs-12 text-left">
<s:url var="deleteLink"><s:param name="shipperName" value="%{organizationInfo.orgName}"></s:param></s:url>
<s:a id="deleteShipper" onclick="deleteShipperFromChosenShipperViewList();" href="%{deleteLink}" >
<img src="/llr/theme/delete.gif" width="16" height="16" alt="Map Red X" >

The JavaScript function is

function deleteShipperFromChosenShipperViewList(){
var oldAction = document.getElementById("shipment").action;
var url = oldAction.replace("shipment","shipment"+"_deleteShipperFromChosenShipperViewList");
document.forms[0].action = url;


The only field value which makes it to the java action page is the
which is passed as a parameter so I obviously am not using the JavaScript function correctly with the link. Any help would be appreciated.

Answer Source

For future googler's this is what I did to solve my problem. I was using the link so I could access the orgid of the shipper the user wanted to delete but I couldn't figure out a way to save all of the page field values the user had entered before he deleted a shipper. So I took the advice Aleksandr M. gave on a previous question here and changed the link to a submit which I displayed as an image (a red X).

<s:iterator value="chosenShipperViewList" status="status">
        <div class="col-sm-2 col-xs-12 "><label class="pull-right"><s:text name="name"></s:text>:</label></div>
        <div class="col-sm-9 col-xs-12  text-left"><s:property value="organizationInfo.orgName"/></div>  
        <div class="col-sm-1 col-xs-12  text-left">
            <s:submit action="shipment_deleteShipperFromChosenShipperViewList" type="image" 
                        onclick="clearDirtyFlag();deleteShipperFromChosenShipperViewList('%{organizationInfo.orgId}');" />

Passing '%{organizationInfo.orgId}' to the deleteShipperFromChosenShipperViewList() function allowed me to pass the orgId for the shipper the user wanted to delete to the function. Using a <s:submit> instead of a link meant Struts would take care of saving any values the user had entered. To get the value to the Java action page deleteShipperFromChosenShipperViewList() stored it in a hidden field as follows:

function deleteShipperFromChosenShipperViewList(orgIdOfShipperToRemove){
    document.getElementById('shipment_deleteOrgId').value = orgIdOfShipperToRemove;

where the hidden field is:

<s:hidden name="deleteOrgId"></s:hidden>  

and is inside the <s:form action="shipment"> form which is why the id of the hidden form is shipment_deleteOrgId.