Request variable from forEach loop jQuery - javascript

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">

Related

SyntaxError: Left hand side of operator '=' must be a reference

I hope someone could help as I have no clue on how to proceed with this error.
I am in the process of upgrading my existing site. My temp new site, tempsite, and plugins were all working fine until I upgraded to Wordpress 5.2.2–en_CA.
Now I get the following error :
`SyntaxError: Left hand side of operator '=' must be a reference`
Here is the instance code for the mini calendar.
<div class="clndr-controls">
<div class="current-month"><%= month %> <%= year %></div>
<div class="clndr-nav clndr-clearfix">
<div class="clndr-previous-button">‹</div>
<div class="clndr-next-button">›</div>
</div>
</div>
<div class="clndr-grid">
<div class="days-of-the-week clndr-clearfix">
<% _.each(daysOfTheWeek, function(day) { %>
<div class="header-day"><%= day %></div>
<% }); %>
</div>
<div class="days clndr-clearfix">
<% _.each(days, function(day) { %>
<div class="<%= day.classes %>" id="<%= day.id %>"><span class="day-number"><%= day.day %></span></div>
<% }); %>
</div>
</div>
<div class="event-listing">
<div class="event-listing-title">Events</div>
<% _.each(eventsThisMonth, function(event) { %>
<% if (event.url) { %><a target="<%= event.url_target %>" href="<%= event.url %>" <% } else { %><div <% } %> class="event-item clndr-clearfix">
<span class="event-item-date">
<% if (event.end != event.start) {
startMY = moment(event.start).format("MM YY");
endMY = moment(event.end).format("MM YY");
if (startMY === endMY) { %>
<%= moment(event.start).format("D") %>–<%= moment(event.end).format("D MMMM") %>
<% } else { %>
<%= moment(event.start).format("D MMMM") %> – <%= moment(event.end).format("D MMMM") %>
<% }
} else { %>
<%= moment(event.start).format("D MMMM") %>
<% } %>
</span>
<span class="event-item-name"><%= event.title %></span>
<% if (event.time) { %>
<span class="event-item-time"><%= event.time %></span>
<% } %>
<% if (event.location){ %>
<span class="event-item-time"><%= event.location %></span>
<% } %>
<span class="event-item-time">With: <%= event.speaker %></span>
<span class="event-item-desc"><%= event.desc %></span>
<% if (event.url) { %></a><% } else { %></div><% } %>
<% }); %>
</div>
Here is the js object options
doneRendering: function() {
var day=1, week=1, thisCLNDR = $(this)[0]["element"];
//make the background rows alternate colour
thisCLNDR.find(".day").each(function() {
if (day == 8) { day = 1; week++; }
if (week % 2 === 0) { $(this).addClass("alternate-bg"); }
day++;
});
//display a notice if there are no events for a month
var thisMonthEvents = thisCLNDR.find(".event-item").length;
if (thisMonthEvents == 0) {
thisCLNDR.find(".event-listing").append(
"<div style='text-align:center;' class='event-item'>No events found</div>"
);
}
},
weekOffset: 1

EJS syntax error : unexpected token ; while compiling ejs

I have a syntax error when I trie to render this part of my template with EJS (on a node server).
The error is in this code part, I'm sure I have a pb with tags "<%" but I don't understand where.
<p>
<% tasks.map(task => ( %>
<%= task %>
<% )) %>
</p>
Here is my full template :
<h1>My todolist</h1>
<p><% tasks.map(task => ( %>
<%= task %>
<% )) %>
</p>
<form method="post" action="/task">
<input type="text" placeholder="Add task" name="newTask" />
<button type="submit">Add</button>
</form>
Thanks for your answer. I finally solved the problem. "task" wasn't the trouble.
It seems I can't use ES6 syntax to quickly return something
I changed this :
<p><% tasks.map(task => ( %>
<%= task %>
<% )) %>
</p> %>
with this :
<p><% tasks.map(task => { %>
<%= task %>
<% }) %>
</p>
And now it works perfectly !
Try this:
<h1>My todolist</h1>
<p>
<% tasks.map(task => {
%> <%=task %><%});%>
</p>
<form method="post" action="/task">
<input type="text" placeholder="Add task" name="newTask" />
<button type="submit">Add</button>
</form>

Form ajax data on jsp example

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>

How to load rails form partials with jquery and submit as one form

In an attempt to make my rails html more readable I extracted several parts of it into partials. I then use jquery to render the partials. The issue is that now the form has come all "unhooked" so to speak, meaning when I attempt to submit the form it acts as though the partials don't exist. I suspect I am not understanding quite how forms work, because it seems like in other answers related to this the form builder isn't even addressed.
This SO question seems related to what I want to do but I think I'm too inexperienced to grasp it properly
The code I have thus far goes as follows:
/assets/javascripts/work_order.js
$(document).ready(function(){
$('.best_in_place').best_in_place();
$('#work_order_dueDate').datepicker();
$.datepicker.setDefaults({ dateFormat: 'dd-mm-yy'});
var selection_made = false
$('#work_order_project_type_id').change(function(){
if (!selection_made){
selection_made = true
var selection = $(this).find('option:selected').text();
if (selection == "Variable Data Mailing"){
$.get('/presort_informations/new');
$.get('/printing_instructions/new');
}
else if (selection == "Mailing"){
$.get('/presort_informations/new');
}
else if (selection == "Print Job"){
$.get('/printing_instructions/new');
}
}
});
});
and then
/views/work_orders/_form.html.erb
<%= form_for(#workorder) do |f| %>
<% if #workorder.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#workorder.errors.count, "error") %> prohibited this workorder from being saved:</h2>
<ul>
<% #workorder.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<fieldset class="general-info">
<legend>General</legend>
<div class="col-md-12">
<div class="col-md-3">
<div class="form-group">
<%= f.label :Job_Title, class: "control-label" %>
<%= f.text_field :title, class:"form-control" %>
</div>
<div class="form-group">
<%= f.label :Project_Type, class: "control-label" %>
<%= f.collection_select(:project_type_id, ProjectType.all, :id, :name, {:prompt => true}, {:class => "form-control"}) %>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<%= f.label :Rep, class: "control-label" %>
<%= f.text_field :rep, class:"form-control" %>
</div>
<div class="form-group">
<%= f.label :Labels, class: "control-label" %>
<%= f.collection_select(:labels_id, Labels.all, :id, :name, {:prompt => true}, {:class => "form-control"}) %>
</div>
</div>
<div class="col-md-3">
<div class= "form-group">
<%= f.label :Due_Date, class: "control-label" %>
<%= f.text_field :dueDate, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :Project_Description, class: "control-label" %>
<%= f.text_area :projectDescription, class: "form-control" %>
</div>
</div>
</div>
</fieldset>
<fieldset class="presort-information">
</fieldset>
<div class="col-md-6 printing">
</div>
<fieldset class="production-details">
<legend>Production</legend>
<%= f.fields_for :production_details, ProductionDetails.new do |ff| %>
<%end%>
</fieldset>
<%= f.hidden_field(:number, :value => #workorder.number) %>
<%= f.hidden_field(:client_id, :value => #workorder.client_id) %>
<%= f.submit(class: "btn btn-default") %>
<% end %>
and as an example of one of the partials:
/app/views/presort_informations/new.js.erb
$('.presort-information').append( '<%= j render("presort_informations/form") %>' );
/app/views/presort_informations/_form.html.erb
<legend>Mailing</legend>
<%= fields_for :presort_information, PresortInformation.new do |ff| %>
.
.
.
<% end %>
I'm not really sure how to tie this all together so that I can load the partials based on the select box, but then submit them all as one form.
Edit:
I found this SO question which deals with the same issue, but I suspect that because I am rendering the partial after the page has been loaded I no longer have access to the form builder variable.
$('.presort-information').append( '<%= j render("presort_informations/form", f: f) %>' );
gives an undefined variable error when it's called. I'm still not sure how to bridge this gap between jquery and rails.
Turns out it was a relatively (if new conceptually to me) easy fix
First, load each DOM partial in along with hidden sections.
<%= form_for(#workorder) do |f| %>
<% if #workorder.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#workorder.errors.count, "error") %> prohibited this workorder from being saved:</h2>
<ul>
<% #workorder.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<fieldset id="general-info-partial">
<%=render("genInfo", f: f)%>
</fieldset>
<fieldset id="presort-information-partial">
<%=render("presort_informations/form", f: f)%>
</fieldset>
<div class="col-md-6">
<fieldset id="printing-information-partial">
<%=render("printing_instructions/form", f: f)%>
</fieldset>
</div>
<fieldset id="production-details-partial">
<%=render("production_details/form", f: f) %>
</fieldset>
<%= f.hidden_field(:number, :value => #workorder.number) %>
<%= f.hidden_field(:client_id, :value => #workorder.client_id) %>
<input type="submit" value="Submit" class="btn btn-default">
<% end %>
<div id="hidden-general-info" class="hidden"></div>
<div id="hidden-presort-information" class="hidden"></div>
<div id="hidden-printing-information" class="hidden"></div>
Then the Javascript to move things in and out of the form:
$(document).ready(function(){
$('.best_in_place').best_in_place();
$('#work_order_dueDate').datepicker();
$.datepicker.setDefaults({ dateFormat: 'dd-mm-yy'});
var presortFields = $('#presort-information-partial');
var printingFields = $('#printing-information-partial');
var presortHidden = $('#hidden-presort-information');
var printingHidden = $('#hidden-printing-information');
presortHidden.html(presortFields.html());
presortFields.html('');
printingHidden.html(printingFields.html());
printingFields.html('');
$('#work_order_project_type_id').change(function(){
var selection = $(this).find('option:selected').text();
if (selection == "Variable Data Mailing"){
if (printingFields.html() == '' && presortFields.html() == ''){
printingFields.html(printingHidden.html()).hide().slideDown();
presortFields.html(presortHidden.html()).hide().slideDown();
}
else if(printingFields.html() == '' && !(presortFields.html() == '')){
printingFields.html(printingHidden.html()).hide().slideDown();
}
else if(!(printingFields.html() == '') && presortFields.html() == ''){
presortFields.html(presortHidden.html()).hide().slideDown();
}
}
else if (selection == "Mailing"){
if(!(printingFields.html() == '')){
printingFields.slideUp();
printingFields.html('');
presortFields.html(presortHidden.html()).hide().slideDown();
}else{
presortFields.html(presortHidden.html()).hide().slideDown();
}
}
else if (selection == "Print Job"){
printingFields.html(printingHidden.html()).hide().slideDown();
presortFields.slideUp();
presortFields.html('');
}
});
Basically, the idea was to load everything in as if I was going to use it all, and then just move the partials into a hidden section of the DOM, and then use JS to put them back in when the user makes a selection

How to validate list of input tag using bootstrap validator

How to validate list of input tag using bootstrap validator
I am using spring, jquery and bootstrap
Here is my html :
<form id="myForm" class="form-horizontal" method="post" action="/hello">
<input class="form-control" type="text" name="myobject[0].descripton />
<input class="form-control" type="text" name="myobject[1].descripton />
<input class="form-control" type="text" name="myobject[2].descripton />
<input class="form-control" type="text" name="myobject[3].descripton />
</form>
Here is my validator :
$('#myForm').bootstrapValidator({
feedbackIcons : {
valid : glyphicon glyphicon-ok,
invalid : glyphicon glyhicon-remove
validating : glyphicon glyphicon-refresh
},
fields : {
myobject[].description : { // <---name of tag.
validators : {
notEmpty : {
message : 'this is required'
}
}
}
}
});
In rails,bootstrap validator plugin first Download the bootstrap-toggle-master file and copy and past validator.js or validator.min.js file in your project.
And add the following code in your view
{<%= form_tag({controller: "facebook", action: "post_message", method: "post"}, :data => {:toggle => "validator"},:class => "facebook-post") do %>
<div class="form-group">
<label for="exampleInputEmail1">Please write something for your status and our wall</label>
<%= text_area_tag :status_message, nil, class: "form-control", :rows => 3, :required => 'true', :data => {:error => "Please write something for both your status and our wall. E.g. Thanks very much for a great night."}%><div class="help-block with-errors"></div>
<% if #venue_location.present? %>
<small>- at </small><%= link_to #venue_location, #fb_page, target: '_blank' %>
<% end %>
</div>
<% if ((#package == 'package3') && !(#fb_page.blank?)) %>
<div class="facebook-like">
<div class="fb-like"
data-href="<%= current_venue.facebook_page %>"
data-layout="standard"
data-action="like"
data-show-faces="false"
style="overflow: hidden">
</div>
</div>
<% end %>
<div class="btn-next text-right">
<%= image_submit_tag("customer/icon-forward.png") %>
</div>
<% end %>}

Categories