I can't get the data from the input of the form, it seems like the only function of the submit button is to refresh the page.
const Form = document.querySelector('.broadcast-form')
Form.addEventListener('submit', (e) => {
e.preventDefault()
const cliente = Form.querySelector('#clienti').options[clienti.selectedIndex].text
console.log(cliente)
})
<form class="container broadcast-form">
<select multiple class="form-control" id="clienti" style="height: 150px" onchange="selectCustomer()">
<!--
<% for(var i=0; i<clienti.length; i++) {%>
<option><%= clienti[i]["Cliente"] + " CL: " + codiceLisa[i]["Codice_Lisa"] %></option>
<% } %>
-->
<option>Foo CL: ABC</option>
<option>Bar CL: DEF</option>
<option>Baz CL: GHI</option>
</select>
<input type="submit" class="btn btn-primary btn-lg" value="Genera XML" />
</form>
When you look at the JavaScript console of your browser, you'll see that it complains about not being able to read a property of undefined. This is caused by clienti not being defined in your JavaScript code, in the clienti.selectedIndex part. Defining it seems to resolve your issue.
As a bonus: you may want to consider using selectedOptions to find all selected options in the select, given that it has the multiple attribute. The selectedIndex will only give you the first one.
function selectCustomer() {
/* defined only to prevent errors when changing the value of the select */
}
const form = document.querySelector('.broadcast-form');
form.addEventListener('submit', (e) => {
e.preventDefault()
let clienti = form.querySelector('#clienti'),
cliente = (clienti.selectedIndex < 0 ? null : clienti.options[clienti.selectedIndex].text);
console.log(cliente);
// bonus:
for (let clienteEl of clienti.selectedOptions) {
console.log(`bonus: ${clienteEl.text}`);
}
})
<form class="container broadcast-form">
<select multiple class="form-control" id="clienti" style="height: 150px" onchange="selectCustomer()">
<!--
<% for(var i=0; i<clienti.length; i++) {%>
<option><%= clienti[i]["Cliente"] + " CL: " + codiceLisa[i]["Codice_Lisa"] %></option>
<% } %>
-->
<option>Foo CL: ABC</option>
<option>Bar CL: DEF</option>
<option>Baz CL: GHI</option>
</select>
<input type="submit" class="btn btn-primary btn-lg" value="Genera XML" />
</form>
Related
I would like to make a drop-down list with the data from my MySQL database, in this case I am trying to make when filling out my "create budgets" form to extract the names from the "customer" table and place them in a select option, I'm using EJS. However, I also have problems when passing EJS data since it gives me an error in the browser (Data not defined)
This is my controller to save data:
controller.save = function(req, res, next) {
const data = req.body;
req.getConnection((err, conn) => {
conn.query('SELECT nombre FROM clientes', (err, row) =>{
res.render('presupuestos_create', {
datos: row
})
});
conn.query('INSERT INTO presupuestos set ?', [data], (err, row) => {
res.redirect('/presupuestos');
});
});
};
And this is mi EJS:
<form action="/presupuestos/add" method="POST">
<div class="mb-3">
<label for="cliente" class="form-label">Cliente</label>
<select class="form-select" id="cliente" name="cliente" tabindex="1" required>
<option>----</option>
<%for(var i=0; i < datos.length; i++){%>
<option value="<%= datos[i] %>"><%= datos[i] %></option>
<%}%>
</select>
</div>
to populate from db > ejs
<select class="form-select" id="cliente" name="cliente" value="<%= datos%>" tabindex="1" required>
<% for(var i=0; i < datos.length; i++) { %>
<option
<%= datos[i].datos %>
</option>
<%}%>
I have a bootstrap list box containing a number of options. Each option is a medical test and has a value attribute. This value attribute has many values init separated by comma e.g it has Test Name, Test Code and Test Rate, etc. In onchange function of the dual list box, I want to get only Test Rate from all the other values present inside the value attribute.
Note: I cannot put the only Test Rate inside value attribute because I need other values also.
Html Code of my dual list box
<div class="form-group row">
<label class="col-sm-2 text-right col-form-label no-padding-top" for="Test">Test </label>
<div class="col-sm-10">
<select class="form-control" multiple="multiple" size="4" name="test_id" onchange="add_total()" id="duallist">
<% tests.forEach(test => { %>
<option value="<%- test.ID %> , <%- test.Code %> , <%- test.Name %> , <%- test.Type %> , <%- test.TemplateID%> , <%- test.Rate %>"><b><%- test.Code %></b> <%- test.Name %></option>
<% }) %>
</select>
</div>
</div>
Onchange function of the dual list box is bellow. Here I want to get only Test Rate.
function add_total() {
var sum = 0.0;
$('#duallist option:selected').each(function() {
//Want to get only Rate here not the whole value attribute how can I do that
var total = parseInt($(this).attr('value'));
sum = (sum + total);
document.getElementById("subtotal").value = sum;
});
}
In your case, you can separate specific data(Test Rate) from all other data of your value attribute by placing your specific data(Test Rate) inside value2 attribute while all other data remains inside value attribute as
<div class="form-group row">
<label class="col-sm-2 text-right col-form-label no-padding-top" for="Test">Test </label>
<div class="col-sm-10">
<select class="form-control" multiple="multiple" size="4" name="test_id" onchange="add_total()" id="duallist">
<% tests.forEach(test => { %>
<option value="<%- test.ID %> , <%- test.Code %> , <%- test.Name %> , <%- test.Type %> , <%- test.TemplateID %>" value2="<%- test.Rate %>"><b><%- test.Code %></b> <%- test.Name %></option>
<% }) %>
</select>
</div>
</div>
Now inside onchange function for the dual list box, you can access you specific data(Test Rate) easily as
function add_total() {
var sum = 0.0;
$('#duallist option:selected').each(function() {
var total = parseInt($(this).attr('value2'));
sum = (sum + total);
document.getElementById("subtotal").value = sum;
});
}
All the other data is still available to you inside the value attribute as you needed so
I am trying to make a multiple choice questionnaire in node. I have a forEach loop printing the form for the questions and answer fields. Problem is that I can not get the correct variable in my jQuery file where I am doing the comparison.
Using a forEach loop in an EJS and checking it in a jQuery file.
jQuery File:
$(document).ready(function(){
$('.bcheck').click(function(){
var on = 1;
var ans = $(this).attr('realanswer');
var theirAns = $("input[placeholder=Answer]").val();
console.log(ans);
if(ans == theirAns){
//DO SOMETHING
}
});
});
The value for var theirAns = $("input[placeholder=Answer]").val(); stays the first element in the iteration. Could I use the this function to get value of something that is not an element of the item I am clicking?
HTML for the EJS file:
<% topic.questions.forEach(function(question){ %>
<% if(question.difficulty == 10){ %>
<form action="/lesson/<%= lesson._id %>/topic/<%= topic._id %>/course/<%= question._id %>/quest?_method=PUT" method="POST">
<div class="quest_info questionf">
<%= question.question %>?
<div class="text_input">
<input type="hidden" name="res[_id]" value="<%= question._id %>">
<input type="hidden" name="realAnswer" value="<%= question.answer %>">
<input id="correct" type="hidden" name="res[correct]" value="<%= false %>">
<% if(question.question_type == "multiple"){ %>
<% var ran = ranNumber(0, 3) %>
<% var n = 0; %>
<% question.wrong_answers.forEach(function(wAns){ %>
<div class="bw btn btn-success" value="<%= wAns %>"> <%= wAns %> </div>
<% if(ran == n){ %>
<div class="ba btn btn-success "><%= question.answer %></div>
<% }; %>
<% n += 1; %>
<% }); %>
<input type="hidden" name="res[answer]" value="<%= question.answer %>" placeholder="Answer">
<% }else{%>
<input type="text" name="res[answer]" placeholder="Answer" >
</input>
</div>
<% }; %>
<div class="text_input">
<div class="bcheck btn btn-primary pull-right" realanswer="<%= question.answer %>" >Check Answer</div>
</div>
<% x += 1 %>
<div class="text_input">
</div>
</div>
<% }; %>
<% }); %>
You're trying to use $("input[placeholder=Answer]").val() - it will return the first value indeed.
If you want to check every element matching a selector $("input[placeholder=Answer]").each() will help. Here is an example based on your code snippet.
$(document).ready(function() {
$('.bcheck').click(function() {
var ans = $(this).data('realanswer');
$("input[placeholder=Answer]").each(function() {
var theirAns = Number($(this).val());
if (ans === theirAns) {
console.log('Nice');
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="bcheck" data-realanswer="42">check</button>
<input placeholder="Answer" type="text">
<input placeholder="Answer" type="text">
<input placeholder="Answer" type="text">
I am using JavaScript Selectize dropdown. I want to change payment types as per the selection of reseravtion type in my code.
Code is as following,
$(document).ready(function () {
$("#reservationType").change(function () {
managePaymentTypes();
});
});
var $reservationTypeObj = $('#reservationType').selectize({
sortField: {
field: localStorage.getItem("selectizeField"),
direction: localStorage.getItem("selectizeDirection")
},
dropdownParent: localStorage.getItem("selectizeDropdownParent")
});
var $paymentTypeObj = $('#paymentType').selectize({
sortField: {
field: localStorage.getItem("selectizeField"),
direction: localStorage.getItem("selectizeDirection")
},
dropdownParent: localStorage.getItem("selectizeDropdownParent")
});
function managePaymentTypes(){
var resType = $('#reservationType :selected').val();
if(resType==202){
//remove option 2 - Salary deduct in selectize.
}else if(resType==101) {
//remove option 1 - Credit in selectize.
}else{
////
}
}
<label class="col-md-1 control-label firstcol" for="type" style="text-align:left">Reservation Type : </label>
<div class="col-md-2" id="reservationTypeDiv" data-toggle="tooltip" data-container="body" data-placement="bottom">
<select class="demo-default selectized" id="reservationType" name="reservationType" tabindex="7" opacity: 1" data-toggle="tooltip" data-container="body" data-placement="bottom">
<%
for (int l = 0; l < reservationTypes.size(); l++)
{
%>
<option value="<%=reservationTypes.get(l).getId()%>"><%=reservationTypes.get(l).getDescription()%></option>
<%
}
%>
</select>
</div>
<label class="col-md-1 control-label firstcol" for="payment" style="text-align:left">Payment Type : </label>
<div class="col-md-2" data-toggle="tooltip" id="paymentTypeDiv" data-container="body" data-placement="bottom">
<select class="demo-default selectized" id="paymentType" name="paymentType" tabindex="7" opacity: 1" data- toggle="tooltip" data-container="body" data-placement="bottom">
<%
for (int l = 0; l < reservationPaymentTypes.size(); l++)
{
%>
<option value="<%=reservationPaymentTypes.get(l).getId()%>"><%=reservationPaymentTypes.get(l).getDescription()%></option>
<%
}
%>
</select>
</div>
I have two selectize dropdowns.
For reservation type
For payement type
Values are getting from database.
Reservation types drop-down screenshot,Payment types drop-down screenshot
When reservation type changes I want to change the payment types.
Therefore onchange of reservation type I have called a method named managePaymentTypes(). I want to remove Credit payment option when reservation type is Individual(101). And I want to remove Salary deduct option when reservation type is Coporate(202). Individual should be default selection. This is my requirement. Someone please help me to solve this.
I have came up with the following solution.
$(document).ready(function () {
<%
for(SportsCenterReservationPaymentType paymentType : reservationPaymentTypes){
%>
paymentTypes.push({id: <%=paymentType.getId()%>, desc: '<%=paymentType.getDescription()%>'});
<%
}
%>
$("#reservationType").change(function () {
loadResourceTable();
managePaymentTypes();
});
});
function managePaymentTypes(){
var resType = $('#reservationType :selected').val();
$('#paymentType')[0].selectize.clearOptions();
if(resType==202&& resType!=101){
$.each(paymentTypes, function (idx, obj) {
if(obj.id!=333){
$('#paymentType')[0].selectize.addOption({value:obj.id,text:obj.desc})
}
});
}
if(resType==101&&resType!=202){
$.each(paymentTypes, function (idx, obj) {
if(obj.id!=222){
$('#paymentType')[0].selectize.addOption({value:obj.id,text:obj.desc})
}
});
}
}
I would like to form data parameter correctly inside ajax call.
<script type="text/javascript">
$(document).ready(function() {
$('#call').click(function ()
{
$.ajax({
type: "post",
url: "books", //this is my servlet
data: <<< my data here >>>
});
});
});
</script>
This is part of my jsp:
<form action="books" method="post">
<table width="70%" border="1">
<%
List<Book> books = (List<Book>) request.getAttribute("books");
for (int i = 0; i < books.size(); i++) {
%>
<tr>
<td>
<input type="checkbox" name="book<%=i%>"
value="<%= books.get(i).getBook_id()%>"> <%= books.get(i).getName() %>
</td>
</tr>
<%
}
%>
</table>
<select name="user_name">
<%
List<User> users = (List<User>) request.getAttribute("users");
for (int i = 0; i < users.size(); i++) {
%>
<option value="<%=users.get(i).getName()%>"><%=users.get(i).getName()%></option>
<%
}
%>
</select>
<input type="submit" name="submit" value="Purchase">
<input type="button" value="Call Servlet" name="Call Servlet" id="call"/>
</form>
I would like to pass everything that normally passes by form above.
Could you please show me around ajax technology by this example?
Give an instance id to the form and use with the serialize() method
$('#form').submit(function ()
{
$.ajax({
type: "post",
url: "books", //this is my servlet
data: $(this).serialize()
});
});
<form id="form" action="books" method="post">
<table width="70%" border="1">
<%
List<Book> books = (List<Book>) request.getAttribute("books");
for (int i = 0; i < books.size(); i++) {
%>
<tr>
<td>
<input type="checkbox" name="book<%=i%>"
value="<%= books.get(i).getBook_id()%>"> <%= books.get(i).getName() %>
</td>
</tr>
<%
}
%>
</table>
<select name="user_name">
<%
List<User> users = (List<User>) request.getAttribute("users");
for (int i = 0; i < users.size(); i++) {
%>
<option value="<%=users.get(i).getName()%>"><%=users.get(i).getName()%></option>
<%
}
%>
</select>
<input type="submit" name="submit" value="Purchase">
<input type="button" value="Call Servlet" name="Call Servlet" id="call"/>
</form>