I'm trying to get the text (not the value) of of an HTML element using node.js
. Note that I am not allowed to change the value of options.
index.html
<select id=agee name="age" onchange="myNewFunction();">
<option value="0">Select</option>
<option id=17 value="no">17 or less</option>
<option id=18 value="99">18 years old</option>
<option id=19 value="105">19 years old</option>
<script src="fetch.js" charset="utf-8"></script>
</select>
fetch.js
var jsdom = require('jsdom');
const { JSDOM } = jsdom;
const $ = require('jquery')(new jsdom.JSDOM().window);
module.exports.myNewFunction = myNewFunction;
function myNewFunction() {
var selectedText = $( "#agee option:selected" ).text();
console.log("your selected text is" selectedText);
return selectedText ;
}
app.js
const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");
const https = require("https");
const date = require(__dirname "/public/fetch.js")
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
$ = require('jquery')(new jsdom.JSDOM().window);
app.use(
bodyParser.json(),
bodyParser.urlencoded({ extended: true }))
app.get("/",function(req,res){
res.sendFile(__dirname "/index.html");
})
app.post("/", function(req,res){
var age = date.myNewFunction();
console.log("this is my age : " age);})
The problem here is that my terminal doesn't show me the value of age, the console prints only "this is my age", but in the same time, the web console shows me the value of selectedText. I don't understand my error or how this is even possible ?
I am a beginner so thanks so much for your time and help !
CodePudding user response:
Express requires middleware to view the body of the request, and you have the body-parser
installed which is the middleware for viewing the body of a request, but you aren't telling Express to use it.
You can fix that by simply adding
app.use(
bodyParser.json(),
bodyParser.urlencoded({ extended: true }))
CodePudding user response:
Your JS is working if you remove the module stuff
function myNewFunction() {
var selectedText = $("#agee option:selected").text();
console.log("your selected text is " selectedText);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id=agee name="age" onchange="myNewFunction();">
<option value="0">Select</option>
<option id=17 value="no">17 or less</option>
<option id=18 value="99">18 years old</option>
<option id=19 value="105">19 years old</option>
</select>