Friday 19 May 2017

How to get button action for dynamically created buttons in node js?

I am a newbie to express js(and node js). I am trying to implement an onclick listener onto dynamically created buttons. Here is my code

Native.pug

doctype html
html
    head
        title="div dude"
    body
        div.main#main(style="height:300px;width:800px;border-style: solid;border-color: #ff0000 #0000ff;padding:10px")
            each prod in product_name
                //
                   Created by krishna on 19/5/17.
                div.child1#child1(style="float:left;height:280px;width:30%;border-style: solid;border-color: #ff0000 #0000ff;margin:10px")
                    p.greetings#people1 Hello World!
                    p.id#id #{prod.id}
                    p.name#name #{prod.name}
                    p.price#price #{prod.price}
                    button.send#send(onclick='senddata()') Add to Cart

script(src='/javascripts/try.js')

try.js

function senddata() {
    document.getElementById("send").innerHTML = "YOU CLICKED ME!";
}

index.js

var express = require('express');
var app = express({mergeParams: true});

var products = [
    {
        place1:[
            {id: 1, name: "choc1", price: 20},
            {id: 2, name: "choc2", price: 30}
        ],
        place2:[
            {id: 1, name: "coffee", price: 50}
        ],
        place3: [
            {id: 1, name: "oil1", price: 10},
            {id: 2, name: "oil2", price: 60},
            {id: 3, name: "oil3", price: 70}
        ]
    }
];

app.get('/:place/:id([0-9]{1,})', function(req, res){
    if (products[0][req.params.place] === undefined)
        res.send("place doesnt exist");
    else {
        if (products[0][req.params.place][req.params.id - 1] === undefined)
            res.send ("id doesnt exist");
        else {
            console.log(products[0][req.params.place][req.params.id-1]);
            res.render('small_div.pug', {product_name:products[0][req.params.place][req.params.id-1]});
        }
    }
});

app.get('/:place', function (req, res) {
   res.render('native.pug', {product_name:products[0][req.params.place]});
});

module.exports = app;

When I click on the button, only the first button works. rest of them do not work. No error is shown either.

please help.

Thanks



via krishna

No comments:

Post a Comment