0

In my project I want the user to select a radio button, then based on the value of the radio button I want to display a unique page. I have to use an ejs template and I don't understand how to pass the value of the button to the ejs template.

<input name="imagePick" value="1" type="radio" id="one">
<label for="one">
   <img src="images/aries.png" alt="aries" height="150" width="auto">
</label>

<input name="imagePick" value="2" type="radio" id="two">
<label for="two">
    <img src="images/taurus.png" alt="taurus" height="150" width="auto">
</label>

$("input[name='imagePick']").on("change", function() {
    var sign = $('input[name="imagePick"]:checked').val();
    console.log("the sign is: " + sign);
});

var theSign = sign;

res.render('template.ejs', {theSign : theSign});

</head>
    <body>
        <% for (var i = 0; i < allTheData.length; i++) { %>
        <h1>Hi <span id="first"><%=allTheData[i].first%></span><br/><br/></h1>
        <% } %>

        <h1> sign: <span id="sign"><%=theSign%></span></h1><br/> 
        <h2> what a great webapp </h2> 
    </body>
</html>

2 Answers 2

1

Since the form is part of the client-side DOM and the EJS is being converted to HTML by server-side code: You need to send the data to the server in an HTTP request.

Put the form controls in a <form>, set the action to a URL handled by a route in your Express code, then read it from the query string or request body depending on if you chose to use GET or POST. Process the data however you like, and then pass it in an object as the argument to render().

Sign up to request clarification or add additional context in comments.

Comments

0

There are some ways to pass values to other page. One of them is making a GET request submitting form fields:

<!-- view1.ejs -->
<form method="get" action="someRoute">
    <input name="imagePick" value="1" type="radio" id="one">
    <input name="imagePick" value="2" type="radio" id="two">
    <input type="submit" value="Submit" />
</form>

Map the form route ("someRoute") and get submitted values:

var express = require('express');
var app = express();
app.get('someRoute', function (req, res) {
    var radioButtonVal = req.query.imagePick;
    res.render('myView', { myData: radioButtonVal /* <<< passing received data to view */ });
});

Render view:

<!-- view2.ejs -->
<body>
    <% if (myData == "1") { %>
        <div></div>
    <% } else if (myData == "2") { %>
        <div></div>
    <% } else { %>
        <div></div>
    <% } %>
</body>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.