How to make default selection of the radio button?

classic Classic list List threaded Threaded
9 messages Options
Reply | Threaded
Open this post in threaded view
|

How to make default selection of the radio button?

     </s:iterator>

The above code is generating a group of radio buttons for each list.
But there is no default selection made. i need to make the first value in each list to be selected by default.

Thanks in Advance!!

shree-2
Hi,

I have a list over which I iterate to generate a group of radio buttons.
How to make the first value(option) in each group of the list as the default?

See below my piece of code
Here abc is of type ArrayList<ArrayList<String>>

<s:iterator value="abc" status="rowstatus">
 
                     
      <s:radio name="select[%{#rowstatus.index}]" list="%{abc[#rowstatus.index]}" />
     
 
Reply | Threaded
Open this post in threaded view
|

Re: How to make default selection of the radio button?

sajidbigler
Hi Friends,

Please help me to resolve same issue i wanna make one  default selection for radio button

<s:radio label="Subscription Type" list="#{'Predefined': 'predefined', 'Dynamic': 'dynamic'}" name="subscription_shedule_type"></s:radio>

how can i make one defual to b selected? plz reply to sajidbigler@gmail.com

Thanks & Regards,

Sajid
Reply | Threaded
Open this post in threaded view
|

Re: How to make default selection of the radio button?

DustFrog
Try adding this:

value="'Predefined'"

to your <s:radio> tag.
Reply | Threaded
Open this post in threaded view
|

Re: How to make default selection of the radio button?

sajidbigler
In reply to this post by sajidbigler
Thanks but still i am facing the same problem .it works for  simple jsp but mine is ajax implementation.please  find files below

smssubscription.jsp


<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="sx" uri="/struts-dojo-tags" %>
<html>
<head>
<title>Compose SMS Subcription</title>
<link href="<s:url value='/css/main.css'/>" rel="stylesheet"
        type="text/css" />
<sx:head cache="true" debug="true" parseContent="true"/>
</head>
<script language="JavaScript" type="text/javascript"> function getExcelSheetSubscription(SubscriptionId) { if(dojo.string.trim(SubscriptionId).length>0) { dojo.io.bind({ url: "<s:url value='/ajaxEditSMSSubscriptionAction.action'/>?SubscriptionId="+SubscriptionId, load: function(type, data, evt) { var contentDiv = dojo.byId("divContent"); contentDiv.innerHTML=data; }, mimeType: "text/html" }); } } </script>
<body>
<div id="content">

<s:actionerror /> <s:fielderror /> 
<s:form action="SMSSubscription"
        method="POST" enctype="multipart/form-data" id="form" >

 
        <s:doubleselect
                                                label="Service Provider: Subscription"
                                                doubleOnclick="javascript:getExcelSheetSubscription(this.value);return false;"
                                                cssStyle="width: 150px;" doubleEmptyOption="true"
                                                doubleHeaderKey="-1" doubleCssStyle="width: 150px;" name="selectSO"
                                                doubleName="selectSO_Sub" list="serviceOwners"
                                                doubleList="subscriptions_sms" listKey="serviceOwnerId"
                                                doubleListKey="subscriptionId" listValue="serviceOwnerName"
                                                doubleListValue="subsriptionName" value="defaultItem"
                                                doubleValue="doubleDefaultItem" />
        <s:div id="divContent" name="divContent"></s:div>                               
        <s:file name="upload" label="Replace File"  id="upload" />

        <s:submit align="center" />

</s:form>

</div>

</body>
</html>

dynamicContentForSMSSubscription.jsp


<%@taglib prefix="s" uri="/struts-tags"%>

<%@ taglib prefix="sx" uri="/struts-dojo-tags"%>

<html>
<head>
<sx:head cache="true" debug="true" parseContent="true"/>
<s:head />

</head>

<body>
<ul>
   
    <li>
        <s:url var="url" action="saveExcelSheet">
        <s:param name="SubscriptionId" value="%{SubscriptionId}"></s:param>
        </s:url>
        <s:a href="%{url}">Download <s:property value="%{FileName}" /> file to do modification.</s:a> 
         
    </li>
    </ul>
<sx:datetimepicker  name="StartDate" label="Strat Date" value="%{StartDate}"/>
<s:radio disabled="true" value="'%{SubscriptionSheduleType}'" label="Subscription Type" list="#{'Predefined': 'predefined', 'Dynamic': 'dynamic'}" name="SubscriptionSheduleType"></s:radio>
<s:textfield name="SubscriptionKeyword" label="KeyWord" disabled="true" value="%{SubscriptionKeyword}" />
<s:textfield name="SubscriptionShortCode" label="Short Code" disabled="true"value="%{SubscriptionShortCode}"  />

</body>
</html>


EditSMSSubscriptionAction.java

package com.teleparadigm.mms.application.smssubcription.edit;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.ValidationAware;
import com.teleparadigm.mms.application.common.Owner;
import com.teleparadigm.mms.application.common.ServiceOwnerAndSuscriptionDetails;
import com.teleparadigm.mms.application.common.SubscriptionDetails;

import com.teleparadigm.mms.application.smssubcription.compose.SMSSubscriptionDAO;
import com.teleparadigm.mms.application.utills.Configuration;
public class EditSMSSubscriptionAction  extends ActionSupport implements ServletRequestAware,ServletResponseAware,ValidationAware,Preparable
{
        //Subscription id which is being selected
        String SubscriptionName;
        String SubscriptionId;
        long ProviderId;
        Date StartDate;
        String SubscriptionKeyword;
        String SubscriptionSheduleType;
        String SubscriptionShortCode;
       
        private String selectSO_Sub;
        private String selectSO;
        Workbook workbook;
        private File upload;
        private String uploadContentType;
        private String uploadFileName;
        byte[] junk = new byte[1024];
        int bytesRead = 0;
        Cell cell=null;
        int i=0,result=0,record=0;
        String pathToStore=null;
        List <ServiceOwnerAndSuscriptionDetails> ServiceOwners;
        List <SubscriptionDetails> Subscriptions;
        private long providerid;
        HttpSession session=null;
       
        private HttpServletRequest request;
        private HttpServletResponse response;
       
       
        public void setServletRequest(HttpServletRequest request){
                this.request = request;
        }

        public HttpServletRequest getServletRequest(){
                return request;
        }

        public void setServletResponse(HttpServletResponse response){
                this.response = response;
        }

        public HttpServletResponse getServletResponse(){
                return response;
        }


        public void prepare() throws Exception {
                session=request.getSession(false);
                ServiceOwners=(List<ServiceOwnerAndSuscriptionDetails>) session.getAttribute("ServiceOwners");
                Subscriptions=(List<SubscriptionDetails>) session.getAttribute("Subscriptions");
        }
        public String execute() throws Exception {


                session=request.getSession(false);
                if(session==null ){

                        addActionError("Invalid Session! Please Relogin!");
                        return ERROR;
                }
                Owner ownerobj=(Owner)session.getAttribute("ownerobj");
                if(ownerobj==null){

                        addActionError("Invalid User Session!");
                        return ERROR;
                }

                selectSO_Sub=getSelectSO_Sub();
                selectSO_Sub=selectSO_Sub.replaceAll(",", "");
                selectSO=getSelectSO();
                selectSO=selectSO.replaceAll(",", "");
                providerid=Long.parseLong(selectSO);



                try {

               
                        MultiPartRequestWrapper multipartRequest = (MultiPartRequestWrapper) ServletActionContext.getRequest();
                        Enumeration enumeration=multipartRequest.getParameterNames();
                        while(enumeration.hasMoreElements()){
                                String name=(String)enumeration.nextElement();
                                System.out.println("<----name-->"+name);
                                String value= multipartRequest.getParameter(name);
                                System.out.println("<----value--->"+value);
                        }



                        System.out.println("\n\n Upload Images");
                        System.out.println("files:");
                        if(upload!=null){
                                System.out.println("files:upload.length:"+upload.length());
                                long nooffiles=upload.length();

                        }else{
                                addActionError("Please upload atleast one file with right content type");
                                return ERROR;
                        }


                } catch (Exception e) {
                        e.printStackTrace();
                        addActionError(e.getMessage());
                        return ERROR;
                }
                // the first four lines of request header are junk, so we need to remove them

                InputStream is= new FileInputStream(upload);
                FileInputStream fs = new FileInputStream(upload);
                //workbook = Workbook.getWorkbook(upload);
                /* bytesRead = is.readLine(junk, 0, junk.length);
                bytesRead = is.readLine(junk, 0, junk.length);
                bytesRead = is.readLine(junk, 0, junk.length);
                bytesRead = is.readLine(junk, 0, junk.length);*/
                workbook = Workbook.getWorkbook(is);

                //out.println("The Workbook is loaded and ready to work upon..");
                //out.println("The file has "+workbook.getNumberOfSheets()+" work Sheets");
                Sheet sheet = workbook.getSheet(0);
                System.out.println("Number of columns in table are : "+sheet.getColumns());
                System.out.println("Number of Rows in table are : "+sheet.getRows());
                int r=sheet.getRows();
                int c=sheet.getColumns();
                EditSMSSubscriptionDAO editsmsuploaddao=new EditSMSSubscriptionDAO();
                //As we know which excel sheet to update using selectSO_Sub we replace excel sheet
                boolean inserted=editsmsuploaddao.editRESOURCE_EXCEL_DATA(fs,uploadContentType, uploadFileName, providerid,Long.parseLong(selectSO_Sub));
                //here goes one more insert for your insersion of parsed data from excelsheet how ever you decide to make ur table
               
                System.out.println("<--inserted-->"+inserted);
               
                return SUCCESS;

        }
        public File getUpload() {
                return upload;
        }
        public void setUpload(File upload) {
                System.out.println("upload : "+upload);
                this.upload = upload;
        }
        public String getUploadContentType() {
                return uploadContentType;
        }
        public void setUploadContentType(String uploadContentType) {
                System.out.println("uploadContentType : "+uploadContentType);
                this.uploadContentType = uploadContentType;
        }
        public String getUploadFileName() {

                return uploadFileName;
        }
        public void setUploadFileName(String uploadFileName) {
                System.out.println("uploadFileName : "+uploadFileName);
                this.uploadFileName = uploadFileName;
        }

        public String getSelectSO() {
                return selectSO;
        }
        public void setSelectSO(String selectSO) {
                this.selectSO = selectSO;
        }
        public List<ServiceOwnerAndSuscriptionDetails> getServiceOwners() {
                return ServiceOwners;
        }
        public void setServiceOwners(
                        List<ServiceOwnerAndSuscriptionDetails> serviceOwners) {
                ServiceOwners = serviceOwners;
        }
        public List<SubscriptionDetails> getSubscriptions() {
                return Subscriptions;
        }
        public void setSubscriptions(List<SubscriptionDetails> subscriptions) {
                Subscriptions = subscriptions;
        }
        public String getSelectSO_Sub() {
                return selectSO_Sub;
        }

        public void setSelectSO_Sub(String selectSO_Sub) {
                this.selectSO_Sub = selectSO_Sub;
        }

        public String getSubscriptionName() {
                return SubscriptionName;
        }

        public void setSubscriptionName(String subscriptionName) {
                SubscriptionName = subscriptionName;
        }

        public String getSubscriptionId() {
                return SubscriptionId;
        }

        public void setSubscriptionId(String subscriptionId) {
                SubscriptionId = subscriptionId;
        }

        public long getProviderId() {
                return ProviderId;
        }

        public void setProviderId(long providerId) {
                ProviderId = providerId;
        }

        public Date getStartDate() {
                return StartDate;
        }

        public void setStartDate(Date startDate) {
                StartDate = startDate;
        }

        public String getSubscriptionKeyword() {
                return SubscriptionKeyword;
        }

        public void setSubscriptionKeyword(String subscriptionKeyword) {
                SubscriptionKeyword = subscriptionKeyword;
        }

        public String getSubscriptionSheduleType() {
                return SubscriptionSheduleType;
        }

        public void setSubscriptionSheduleType(String subscriptionSheduleType) {
                SubscriptionSheduleType = subscriptionSheduleType;
        }

        public String getSubscriptionShortCode() {
                return SubscriptionShortCode;
        }

        public void setSubscriptionShortCode(String subscriptionShortCode) {
                SubscriptionShortCode = subscriptionShortCode;
        }

        public HttpServletRequest getRequest() {
                return request;
        }

        public void setRequest(HttpServletRequest request) {
                this.request = request;
        }

        public HttpServletResponse getResponse() {
                return response;
        }

        public void setResponse(HttpServletResponse response) {
                this.response = response;
        }




}
Reply | Threaded
Open this post in threaded view
|

Re: How to make default selection of the radio button?

sajidbigler
Components after Ajax call like

<sx:datetimepicker  name="StartDate" label="Strat Date" value="%{StartDate}"/>
<s:radio disabled="true" value="'%{SubscriptionSheduleType}'" label="Subscription Type" list="#{'Predefined': 'predefined', 'Dynamic': 'dynamic'}" name="SubscriptionSheduleType"></s:radio>
<s:textfield name="SubscriptionKeyword" label="KeyWord" disabled="true" value="%{SubscriptionKeyword}" />
<s:textfield name="SubscriptionShortCode" label="Short Code" disabled="true"value="%{SubscriptionShortCode}"  />

wont populate correctly.we dont get date picker too values are not set in value stack or i cant able to access it
Reply | Threaded
Open this post in threaded view
|

Re: How to make default selection of the radio button?

sajidbigler
In reply to this post by DustFrog
plz find attached screen shot.where i am not able to get date picker and radio button not checked.and i wonder why its applying simple theme plz help me to make all rows in order too how can i make it?resultjsp.JPGresultjsp.JPG
Reply | Threaded
Open this post in threaded view
|

Re: How to make default selection of the radio button?

sajidbigler
In reply to this post by sajidbigler
i got resolved few things but still
<sx:datetimepicker  name="StartDate" label="Strat Date" value="%{StartDate}"/> is troubling me a lot

dynamicContentForSMSSubscription.jsp


<%@taglib prefix="s" uri="/struts-tags"%>

<%@ taglib prefix="sx" uri="/struts-dojo-tags"%>

<html>
<head>
<sx:head cache="true" debug="true" parseContent="true"/>
<s:head />

</head>

<body>
<ul>
   
    <li>
        <s:url var="url" action="saveExcelSheet">
        <s:param name="SubscriptionId" value="%{SubscriptionId}"></s:param>
        </s:url>
        <s:a href="%{url}">Download <s:property value="%{FileName}" /> file to do modification.</s:a> 

    </li>
    </ul>
<sx:datetimepicker  name="StartDate" label="Strat Date" value="%{StartDate}"/>
<s:radio disabled="true" value="%{SubscriptionSheduleType}" label="Subscription Type" list="#{'Predefined': 'predefined', 'Dynamic': 'dynamic'}" name="SubscriptionSheduleType"></s:radio>
<s:textfield name="SubscriptionKeyword" label="KeyWord" disabled="true" value="%{SubscriptionKeyword}" />
<s:textfield name="SubscriptionShortCode" label="Short Code" disabled="true"value="%{SubscriptionShortCode}"  />

</body>
</html>

please find attached screen shot

resultjsp2.JPG
Reply | Threaded
Open this post in threaded view
|

Re: How to make default selection of the radio button?

DustFrog
In reply to this post by sajidbigler
Here's an excerpt from "Struts 2 in Action".  This should help you understand the principles:

Prepopulation With Collection-Backed Components

Prepopulation of the collection-backed components may not seem straightforward at first glance. For starters, we'll call it preselection, as that more accurately describes what'll happen. It works just as the prepopulation of the simple component tags; the value attribute points to a property on the ValueStack that'll be used as the current value when preselecting one of the options. Remember, you'll frequently leave the value attribute unset, allowing the framework to infer it from the name attribute, as we've seen.

With simpler components, like the textfield, the value will directly populate the input field. With collection-backed components, we don't have a simple input field; we have a selection of options. Each of these HTML options has a value attribute that represents the value of the component if that option is selected. The trick, then, is to use the value attribute of the Struts 2 tag to match one of those option values. When a match occurs, that option is preselected. Let's demonstrate how this preselection works.

To do so, we'll modify the PortfolioHomePage to automatically select one of the artists as the default choice. Let's imagine that, each week, the Struts 2 Portfolio will feature the work of one artist by making that artist the default choice. In order to have one of the options preselected, we must provide a property on the ValueStack that holds the username, our key, of the default artist. We've implemented a method on our PortfolioService that returns the username of the currently featured artist. We'll retrieve this and set it on a defaultUsername property on the action. To make things clearer, we'll specify the component's value attribute separately from the name attribute, rather than letting the framework infer it. The following snippet shows the code from the PortfolioHomePage action's execute() method, which does the necessary work:


First, we set the collection of users that'll be used to create the collection-backed component . Then, we retrieve the username of the featured artist, and we set this on the defaultUsername JavaBeans property on the action itself. This'll make it available on the ValueStack. Now, let's see how this works with our radio component.

<s:form action="SelectPortfolio" >
  <s:radio name="username" list='users' value="defaultUsername"
    listKey="username" listValue="username" label="Select an artist" />
  <s:submit value="Browse"/>
</s:form>


Just as in the previous examples, we point the component to our collection of Users and tell it to use each User's username as both the listKey and listValue. Then, we preselect our artist of the week by pointing the value attribute at our defaultUsername property. At the moment, our featured artist is the user Chad. So the following markup is generated by our tag and action logic:

<input type="radio" name="username" value="Jimmy"/>
<input type="radio" name="username" value="Charlie Joe"/>
<input type="radio" name="username" checked="checked" value="Chad"/>
<input type="radio" name="username" value="Mary"/>


As you can see, the username of the featured user was Chad, so the radio button with that value was checked. Note that you can easily go back and reimplement this to stash the featured artist's username in a property on the action called username. Then you wouldn't have to manually specify the value attribute separately from the name attribute. This would've been confusing in our example, since our listKey and listValue attributes are also usernames. How can this be? Consider that the listKey and listValue are used during the iterative cycle of the collection-backed components. During this cycle, each of the Users in the collection is pushed onto the ValueStack. Thus, the listKey and listValue hit the property as found on the current User object. But when the name attribute resolves, the iteration hasn't started; the top object on the ValueStack is the action, not one of the Users. This subtlety explains how the same OGNL, username, can mean different things depending upon the state of the ValueStack. This is admittedly tricky. But once you master the ValueStack, it'll all seem elegant and powerful.

This same preselection process works for all of the collection-backed components. We should make a point about multiple selection before moving on. If you're working with a multiple-selection component, such as the select component with the multiple attribute set to true, your value attribute can point to a property that contains more than one choice, such as an array of usernames in our case. The component will select each of those values.

That does it for the components that we expect all developers will need to use on a regular basis. We'll round out the chapter by pointing you toward some rich components that would enhance any page.
Reply | Threaded
Open this post in threaded view
|

Re: How to make default selection of the radio button?

     </s:iterator>

The above code is generating a group of radio buttons for each list.
But there is no default selection made. i need to make the first value in each list to be selected by default.

Thanks in Advance!!
Steve H.
In reply to this post by shree-2
This has been driving me nuts for most of today.

Solution to a simple use case allowing a user to select CSV or XML radio buttons follows.
The CSV button is populated by default.

<s:radio name="fileType" value="{'CSV'}" list="{'CSV'}"/>
<s:radio name="fileType" list="{'XML'}"/>

The selected value is populated on the action by calling setFileTyle ("CSV") or setFileType ("XML") depending on the user choice.

I have used two tags to force the radio buttons to be aligned vertically,

Steve
shree!!! wrote
Hi,

I have a list over which I iterate to generate a group of radio buttons.
How to make the first value(option) in each group of the list as the default?

See below my piece of code
Here abc is of type ArrayList<ArrayList<String>>

<s:iterator value="abc" status="rowstatus">
 
                     
      <s:radio name="select[%{#rowstatus.index}]" list="%{abc[#rowstatus.index]}" />