I tried to execute the below lines of code and ended up with the below error message. Any code suggestions to clear this out?
<%= kindOfItems.forEach( function (item) { %>
<div class = "item">
<input type="checkbox">
<p>
<%= item.name %>
</p>
</div>
<%= }) %>
SyntaxError: Unexpected token ')' in D:\web development\todoList\Todo-List---EJS-master\Todo-List---EJS-master\views\list.ejs while compiling ejs
Not familiar with ejs but by the looks of it you are missing a return statement. After a quick google it seems you need to do the following
<%= kindOfItems.map( function (item) { %>
return <div class = "item">
<input type="checkbox" />
<p>
<%= item.name %>
</p>
</div>
<%= }) %>
Related
So basically, what I'm trying to do is show the value of status dropdown as [initial, started completed] when bug_type dropdown's value is bug, otherwise status dropdown should show [initial, started, resolved]
<div class="col">
<div class="form-group">
<%= form.select :bug_type, options_for_select([['Bug', 'bug'], ['Feature', 'feature']]) %> <br>
</div>
</div>
<div class="col">
<div class="form-group">
<% if #bug.bug_type == 'bug'%>
<%= form.select :status, options_for_select([['Initial', 'initial'], ['Started', 'started'], ['Completed', 'completed']]) %> <br>
<% else %>
<%= form.select :status, options_for_select([['Initial', 'initial'], ['Started', 'started'], ['Resolved', 'resolved']]) %> <br>
<% end %>
</div>
</div>
So far, I tried doing this but it doesn't work.
Also, I've used enums for bug_type and status. Please help me, if there's another approach to deal with this.
there are two ways for your requirement. One is client side you can change the dropdown value or you can send one server side request and render your required options.
For client side you can do like this:
<div class="col">
<div class="form-group">
<%= form.select :bug_type, options_for_select([["Bug", "bug"], ["Feature", "feature"]]) %>
</div>
</div>
<div class="col">
<div class="form-group">
<% if #bug.bug_type == "bug" %>
<%= form.select :status, options_for_select([["Initial", "initial"], ["Started", "started"], ["Completed", "completed"]]) %>
<% else %>
<%= form.select :status, options_for_select([["Initial", "initial"], ["Started", "started"], ["Resolved", "resolved"]]) %>
<% end %>
</div>
</div>
<script>
// Please change selector accoding to your DOM.
// This is bug type select dropdown
$('#bug_type_select').change(function() {
var selectedValue = $('#bug_type option:selected').val();
var bugOptions = {
'initial': 'Initial',
'started': 'Started',
'completed': 'Completed'
}
var featureOptions = {
'initial': 'Initial',
'started': 'Started',
'resolved': 'Resolved'
}
// Please change selector accoding to your DOM.
// This is status select dropdown
var $mySelect = $('#mySelect');
$mySelect.empty();
if (selectedValue === 'bug') {
$.each(bugOptions, function(key, value) {
var $option = $('<option/>', {
value: key,
text: value
});
$mySelect.append($option);
});
} else {
$.each(featureOptions, function(key, value) {
var $option = $('<option/>', {
value: key,
text: value
});
$mySelect.append($option);
});
}
});
</script>
I have a table "fundings" in which there is a field "status", for which i have a select field in the form. The options for this select field are ["approved", "declined", "pending"]. What i want is when "declined" is selected, a further text box shows to explain the reason for decline. Please help how can this be done.
<%= form_for([#parent, #child, #funding], :html => {class: "form-horizontal",role: "form"}) do |form| %>
<div class = "form-group">
<div class="control-label col-sm-2">
<%= form.label :status %>
</div>
<% if current_user.admin? %>
<div class="col-sm-8">
<%= form.select :status,['Pending', 'Approved', 'Declined'], class: "form-control" %>
</div>
<% else %>
<!-- Disabled for non-admin users -->
<% end %>
</div>
<!-- Submit button here -->
<% end %>
Update
<div class="form-group">
<%= "Status" %>
<%= form.select :status, ['Pending', 'Approved', 'Declined'], {}, id: "sample-status-select", class: "form-control" %>
</div>
<div class="form-group">
<%= "Decline Reason" %>
<%= form.text_area :decline_reason, class: "form-control hidden", id: "decline-reason-textarea" %>
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<%= form.submit "Apply", class: 'btn btn-primary btn-lg' %>
</div>
</div>
</div>
</div>
<% end %>
<script type="text/javascript">
<plain>
$(function() {
$("#sample-status-select").on("change", function() {
var select_val = $(this).val();
console.log(select_val);
if (select_val === 'Declined') {
$("#decline-reason-textarea").removeClass("hidden");
} else {
$("#decline-reason-textarea").addClass("hidden");
$("#decline-reason-textarea").val("");
}
});
});
</plain>
</script>
$(function() {
$("#sample-status-select").on("change", function() {
var select_val = $(this).val(); // this gets the value of the dropdown menu
console.log(select_val); // this just displays the selected value in the browser console (if you have the browser console open)
if (select_val === 'Declined') {
// if the 'Declined' option is chosen
// we remove the 'hidden' class from the textarea
$("#decline-reason-textarea").removeClass("hidden");
} else {
// if any other option is chosen
// we put back the 'hidden' class to the textarea
// also, we update the textarea value to BLANK (this part is optional, it depends if you want to keep the value of the textarea)
$("#decline-reason-textarea").addClass("hidden");
$("#decline-reason-textarea").val("");
}
});
});
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="https://httpbin.org/post" method="post">
Status
<select id="sample-status-select">
<option value="Pending">Pending</option>
<option value="Approved">Approved</option>
<option value="Declined">Declined</option>
</select>
<br>
<br> Decline Reason
<textarea id="decline-reason-textarea" class="hidden">
</textarea>
</form>
Check this snippet I made. It should work for you as well.
This is a basic html form so this works even without ruby on rails.
After you get the gist of this, you should be able to port for it to work with your rails app.
<script type="text/javascript">
$(function() {
$("#sample-status-select").on("change", function() {
var select_val = $(this).val();
console.log(select_val);
if (select_val === "Declined") {
$("#decline-reason-textarea").removeClass("hidden");
} else {
$("#decline-reason-textarea").addClass("hidden");
$("#decline-reason-textarea").val("");
}
});
});
</script>
I am creating a rails quiz .. i have done everything the problem is that i want to implement pagination and when the user goes to next page the previous page values are lost. i am new to rails.
view page -- that show question paper
<div class="navbar navbar-fixed-top">
<h3><% if #paper.timing!=0 %><div id="time" class="bg"></div><%end%></h3>
</div>
<br>
<%= form_for Result.new do |f| %>
<div id="content">
<div class="inputs">
<div>
<div>
<div>
<div>
<% #questions.each_with_index do |question , i | %>
<%= f.hidden_field :userchoice_id, :value => session[:id] %>
<%= f.hidden_field :exam_id, :value => session[:exam_id] %><br>
<h3> <%= i + 1 %>.<%= question.content %></h3><br>
<%count = 0%>
<% a=question.answers %>
<%#raise a.inspect%>
<% a.each do |sushil| %>
<%#raise sushil.inspect%>
<% if sushil.correct_answer?%>
<%count = count+1 %>
<%else %>
<%count = count+0 %>
<%end%>
<%end%>
<%#raise count.inspect%>
<%if count == 1 %>
<% for answer in question.answers %>
<%= radio_button_tag("result[question_id][#{question.id}]", answer.id ) %>
<%= answer.content %><br>
<%end%>
<%elsif count >= 2 %>
<% for answer in question.answers %>
<%= check_box_tag("result[question_ids][][#{question.id}]", answer.id ) %>
<%#= check_box_tag ("result[question_id][#{question.id}]", answer.id ) %>
<%= answer.content %><br>
<% params[:answer_id] = answer.id %>
<%end%>
<% end %>
<%# raise params[:answer_id].inspect%>
<% end %>
</div>
<div class="form-actions">
<center><%= f.submit "Submit", :class => 'btn btn-primary',:onclick => "if(confirm('Are you sure you want to Submit the Paper?')) return true; else return false;" %></center>
</div>
<% end %>
</div>
</div>
</div>
<div style='display:none' id="timeup"><% if #time==0 %>0<%else%>1<%end%></div>
<!-- Added javascript for back button-->
<script>
jQuery(document).ready(function($) {
if (window.history && window.history.pushState) {
window.history.pushState('forward', null, './#forward');
$(window).on('popstate', function() {
history.forward();
});
}
});
</script>
<!-- Added Timer Javascript in Test -->
<% if #paper.timing!=0 %>
<script>
$(document).ready(function(){
var now=new Date();
if($('#timeup').html()==0){
stopTest();
}
now.setMinutes(now.getMinutes()+<%=#min%>);
now.setSeconds(now.getSeconds()-<%=#sec%>);
$('#time').countdown({until:now, format: 'MS',onExpiry:stopTest});
});
function stopTest(){
$('#time').html('<center><h4>Time\'s up!</h4></center>');
$('#timeup').html('0');
// $('input.radio').attr("onclick","return false;");
$("#new_result").submit();
}
</script>
<%end%>
You should use kaminari or will_paginate gem...
Kaminari example:
Gemfile:
gem 'kaminari'
bash:
bundle
rails g kaminari:views default
products_controller.rb:
#products = Product.order("name").page(params[:page]).per(5)
config/locales/en.yml:
en:
hello: "Hello world"
views:
pagination:
previous: "< Previous"
next: "Next >"
truncate: "..."
products/index.html.erb:
<%= paginate #products %>
app/views/kaminari/_prev_span.html.erb
<span class="prev disabled"><%= raw(t 'views.pagination.previous') %></span>
Will_paginate example:
http://richonrails.com/articles/getting-started-with-will-paginate
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ens.ContactPerson>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Edit
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Edit</h2>
<%if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
{ %>
<%= Html.ValidationSummary("Edit was unsuccessful . Please correct the errors and try again.")%>
<% using (Html.BeginForm())
{%>
<fieldset>
<legend>Fields</legend>
<p>
<%= Html.Hidden("Id", Model.Id)%>
<%= Html.ValidationMessage("Id", "*")%>
</p>
<p>
<label for="FirstName">FirstName:</label>
<%= Html.TextBox("FirstName", Model.FirstName)%>
<%= Html.ValidationMessage("FirstName", "*")%>
</p>
<p>
<label for="MiddleName">MiddleName:</label>
<%= Html.TextBox("MiddleName", Model.MiddleName)%>
<%= Html.ValidationMessage("MiddleName", "*")%>
</p>
<p>
<label for="LastName">LastName:</label>
<%= Html.TextBox("LastName", Model.LastName)%>
<%= Html.ValidationMessage("LastName", "*")%>
</p>
<p>
<label for="DateOfBirth">DateOfBirth:</label>
<%= Html.TextBox("DateOfBirth", String.Format("{0:g}", Model.DateOfBirth))%>
<%= Html.ValidationMessage("DateOfBirth", "*")%>
</p>
<p>
<label for="ContactPersonType">ContactPersonType:</label>
<%= Html.DropDownList("ContactPersonType")%>
<%= Html.ValidationMessage("ContactPersonType", "*")%>
</p>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
<div>
<%=Html.ActionLink("Back to List", "All")%>
</div>
<%} %>
</asp:Content>
can i apply some javascript or jquery here such that after click on submit button, it must checks for the values are valid , if can do so.
pls give code for the validation of last name field...this should not be empty.
i tried with this function but it dindt work....
protected void ValidateContact(ens.ContactPerson contactToValidate)
{
if (contactToValidate.FirstName.Trim().Length == 0)
ModelState.AddModelError("FirstName", "First name is required.");
if (contactToValidate.LastName.Trim().Length == 0)
ModelState.AddModelError("LastName", "Last name is required.");
if (contactToValidate.MiddleName.Trim().Length == 0)
ModelState.AddModelError("MiddleName", "Invalid phone number.");
if (contactToValidate.DateOfBirth.ToString().Trim().Length == 0)
ModelState.AddModelError("Email", "Invalid email address.");
}
Probably, You can force validate entire form with Sys.Mvc.FormContext.getValidationForForm. Example: http://weblogs.asp.net/imranbaloch/archive/2010/07/11/asp-net-mvc-client-side-validation-with-dynamic-contents.aspx
You will need some JavaScript references. Follow this http://www.gregshackles.com/2010/02/validating-hidden-fields-in-asp-net-mvc-2/
After that, you can just call any javascript method on submit button, do javascript validation and then submit the form.
<script type="text/javascript" language="javascript">
function ValidateLastName(name) {
//all validation here
var form = document.forms[0];
form.action = '/AddressType/Create';
form.submit();
}
</script>
OR may be one of these may help,
http://forums.asp.net/t/1538157.aspx/1
My Own javascript validation + MicrosoftMvcValidation . Is it possible ? How
You are going to want to make the submit button a regular button and onclick call a javascript function that validates your fields. If the validation passes you can submit the form with $("#myForm").submit(). You can do something like var lastName = $("#LastName").val() to get the value in your last name textbox and then test the value in lastName.
I've got the following code in my aspx file:
<% using (Html.BeginForm())
{
int i = 0;
%>
<% foreach (var item in Model.Educations)
{ %>
<fieldset>
<input type="hidden" name="educations.Index" value="" />
<p>
<label for="PID">
PID:</label>
<%= Html.TextBox("educations["+i+"].PID", item.PID)%>
<%= Html.ValidationMessage("PID", "*")%>
</p>
<p>
<label for="EducationType">
EducationType:</label>
<%= Html.TextBox("educations["+i+"].EducationType", item.EducationType)%>
<%= Html.ValidationMessage("EducationType", "*")%>
</p>
<p>
<label for="SchoolName">
SchoolName:</label>
<%= Html.TextBox("educations["+i+"].SchoolName", item.SchoolName)%>
<%= Html.ValidationMessage("SchoolName", "*")%>
</p>
<p>
<label for="UniversityId">
UniversityId:</label>
<%= Html.TextBox("educations["+i+"].UniversityId", item.UniversityId)%>
<%= Html.ValidationMessage("UniversityId", "*")%>
</p>
<p>
<label for="Department">
Department:</label>
<%= Html.TextBox("educations["+i+"].Department", item.Department)%>
<%= Html.ValidationMessage("Department", "*")%>
</p>
<p>
<label for="Degree">
Degree:</label>
<%= Html.TextBox("educations["+i+"].Degree", String.Format("{0:F}", item.Degree))%>
<%= Html.ValidationMessage("Degree", "*")%>
</p>
<p>
<label for="YearOfGraduation">
YearOfGraduation:</label>
<%= Html.TextBox("educations[" + i + "].YearOfGraduation", String.Format("{0:F}", item.YearOfGraduation))%>
<%= Html.ValidationMessage("YearOfGraduation", "*")%>
</p>
<p>
<label for="ID">
ID:</label>
<%= Html.TextBox("educations[" + i + "].ID", item.ID)%>
<%= Html.ValidationMessage("ID", "*")%>
</p>
<input type="submit" name="silButton" value="Sil"/>
</fieldset>
<%
i++;
} %>
<p>
<input type="submit" name="ekleButton" value="Ekle" />
</p>
<% } %>
<div>
<%=Html.ActionLink("Back to List", "Index") %>
</div>
This way I'm able to dynamically add ("Ekle") more fields if user wants to enter additional education information (most probably from another university or another degree).
This code also give "Sil" button (which means delete), and I want to be able to detect exactly which "Sil" button was pressed and delete that Education entry from my "object" in session.
My action method looks like this:
public ActionResult Step3(string ekleButton, IList<Education> educations, IList<string> silButton)
{
if (educations != null)
{
_person.Educations.Clear();
_person.Educations.AddRange(educations);
}
if (ekleButton != null)
{
_person.Educations.Add(new Education());
}
if (silButton!=null){
//find index and delete it from _person.Edications
}
return View(_person);
}
In this way silButton != null if any of the "silButton" buttons was pressed and I can't detect which button was pressed. Is there a way to find this out?
You could put the index in the name of the button:
<input type="submit" name="silButton<%=i %>" value="Sil" />
And in your action method:
var silButton = Request.Params.AllKeys.FirstOrDefault(key => key.StartsWith("silButton"));
if (!string.IsNullOrEmpty(silButton))
{
var index = int.Parse(silButton.Replace("silButton", string.Empty));
}