You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在EJS中点击按钮时将按钮值赋值给EJS变量?

How to Pass Frontend Button Value to an EJS Variable On Click?

Hey there! Let's break down your problem first, because there's a key concept you need to understand here to find the right solution.

The Core Issue: EJS vs. Client-Side JavaScript

EJS is a server-side templating engine. That means all your <% ... %> code runs on the server before the page is sent to the browser. Once the page loads in your user's browser, the EJS template has already been converted to static HTML—there's no more EJS code to execute on the client side.

So trying to run <% var b = 'LEXUS'%> directly from a client-side onclick event won't work: the server isn't there to process that EJS code anymore.


Solution 1: Communicate with the Server (For Server-Side Variable Updates)

If you need the selected brand value to exist as an EJS variable (e.g., to use it in server-side logic or re-render the page with that value), you'll need to send the value back to the server via an HTTP request. Here's how to do it with Fetch API:

Step 1: Update Your Frontend Code

<% for(var i=0; i<listBrand.length; i++) { %> 
<button class="btn btn-primary" value="<%= listBrand[i]%>" onclick="multiple(this.value);"> 
<%= listBrand[i]%> 
</button> 
<br/> 
<% };%>

<!-- Add a section to show the server-rendered selected brand -->
<div id="selectedBrandSection">
  <% if (typeof selectedBrand !== 'undefined') { %>
    <p>Server-side selected brand: <strong><%= selectedBrand %></strong></p>
  <% } %>
</div>

<script> 
function showList(id) { 
  var list = document.getElementById(id); 
  list.style.display = (list.style.display == 'block') ? 'none' : 'block'; 
}

function multiple(value) { 
  showList("listGallery"); 
  console.log(value);

  // Send the selected brand to the server
  fetch('/set-brand', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: `brand=${encodeURIComponent(value)}`
  })
  .then(response => response.text())
  .then(updatedHtml => {
    // Replace the section with the server's new rendered content
    document.getElementById('selectedBrandSection').innerHTML = updatedHtml;
    // Or refresh the whole page if you need: window.location.reload();
  })
  .catch(err => console.error('Failed to send brand to server:', err));
} 
</script>

Step 2: Add Server-Side Logic (Example with Express)

Assuming you're using Express.js, add a route to handle the request and pass the value to your EJS template:

app.post('/set-brand', (req, res) => {
  const selectedBrand = req.body.brand;
  // You can store this in a session, database, or just pass it directly to the template
  res.render('your-page-name', {
    listBrand: ['LEXUS', 'TOYOTA', 'FERRARI', 'MAYBACH', 'AUDI'],
    selectedBrand: selectedBrand
  });
});

Solution 2: Use Client-Side Variables (If No Server Logic Is Needed)

If you only need to use the selected brand value for frontend tasks (like showing it on the page or manipulating client-side elements), you don't need an EJS variable at all. Just use a regular JavaScript variable:

<% for(var i=0; i<listBrand.length; i++) { %> 
<button class="btn btn-primary" value="<%= listBrand[i]%>" onclick="multiple(this.value);"> 
<%= listBrand[i]%> 
</button> 
<br/> 
<% };%>

<p>Client-side selected brand: <span id="clientBrandDisplay"></span></p>

<script> 
let currentSelectedBrand = ''; // Client-side "variable"

function showList(id) { 
  var list = document.getElementById(id); 
  list.style.display = (list.style.display == 'block') ? 'none' : 'block'; 
}

function multiple(value) { 
  showList("listGallery"); 
  console.log(value);
  currentSelectedBrand = value;
  // Update the display with the selected value
  document.getElementById('clientBrandDisplay').textContent = currentSelectedBrand;
} 
</script>

Key Takeaways

  • EJS runs only on the server—once the page loads, you can't execute new EJS code from the browser.
  • To update an EJS variable, you need to send the value back to the server and re-render the template.
  • For frontend-only use cases, stick to client-side JavaScript variables instead of trying to use EJS.

内容的提问来源于stack exchange,提问作者STEPHEN bui

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:12:20