Select all checkboxes - ruby-on-rails

In my Rails app I've created a set of checkboxes as follows:
<div class="form_row">
<label for="features[]">Features:</label>
<% ['scenarios', 'news', 'role_profiles', 'private_messages', 'chatrooms', 'forums', 'polls'].each do |feature| %>
<br><%= check_box_tag 'features[]', feature, (#features || {}).include?(feature) %>
<%= feature.humanize %>
<% end %>
</div>
I'd like to know how to create a button that would "Select All".

Using jQuery;
<script type="text/javascript">
function selectAll(){
$("input:checkbox").each(function(){
$(this).attr('checked', true);
});
return false;
}
</script>
HTML button:
Select All

If you use the Prototype JS, you might find this blog post helpful. It gives a fairly concise way to perform a select all.
http://www.ryboe.com/2008/07/10/select-all-checkboxes-with-prototype-js.html
In your view you could use the following snippet to create a "Select All" link:
<%= link_to_function("Select All","checkboxes.each(function(e){ e.checked = 1 })") %>
In addition, you'd need the following Javascript code somewhere on the same page (or maybe even abstracted out to the public/javascripts/application.js file
var checkboxes = [];
checkboxes = $$('input').each(function(e){ if(e.type == 'checkbox') checkboxes.push(e) });
var form = $('options'); /* Replace 'options' with the ID of the FORM element */
checkboxes = form.getInputs('checkbox');
Here's the full source of a working example, if this doesn't work you might need to check to make sure your JS libraries are loading properly.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="http://www.google.com/jsapi" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
var checkboxes;
google.load("prototype", "1.6");
google.setOnLoadCallback(function(){
checkboxes = [];
checkboxes = $$('input').each(function(e){ if(e.type == 'checkbox') checkboxes.push(e) });
var form = $('options'); /* Replace 'options' with the ID of the FORM element */
checkboxes = form.getInputs('checkbox');
});
</script>
</head>
<body>
<form id="options">
<fieldset><input type="text" value="test"></fieldset>
<fieldset><input type="checkbox" value=0> 0</fieldset>
<fieldset><input type="checkbox" value=1> 1</fieldset>
<fieldset><input type="checkbox" value=2> 2</fieldset>
<fieldset><input type="checkbox" value=3> 3</fieldset>
</form>
Select All
</body>
</html>

I think you can use query like that
<script>
$('#check_all').on("click", function(){
var check = $('input[type="checkbox"]');
check.prop("checked", !check.prop("checked"));
});
</script>
and the html will be something like
<%= button_tag 'select / unselect all', id: 'check_all', class:'b' %>

Related

Use Stimulus Controller in multiple places

I want to be able to use a Stimulus Controller in multiple places in a web app. I want do something like this:
<div data-controller="mycontroller">
<OneComponent />
</div>
<SomeOtherComponent />
<div data-controller="mycontroller">
<NewComponent />
</div>
But the controller just seem to connect to the first Component and not in the second. Is it possible to use it as I'm intending to?
Thanks!
Stimulus controllers can be reused. See this sample.
Possible problems that may prevent this from working is if there is a JS error, or that you expect elements in nested components to be used in the parent component, if they have not been rendered yet.
const application = Stimulus.Application.start()
application.register("hello", class extends Stimulus.Controller {
connect() {
console.log("connect to", this.element.getAttribute("data-language"))
}
static get targets() {
return [ "name" ]
}
greet() {
if (this.element.getAttribute("data-language") == "es-ES") {
console.log(`¡Hola, ${this.nameTarget.value}!`);
} else {
console.log(`Hello, ${this.nameTarget.value}!`);
}
}
})
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="https://unpkg.com/stimulus/dist/stimulus.umd.js"></script>
</head>
<body>
<div data-controller="hello" data-language="en-US">
<input data-hello-target="name" type="text" value="John">
<button data-action="click->hello#greet">Greet</button>
</div>
<div data-controller="hello" data-language="es-ES">
<input data-hello-target="name" type="text" value="Jose">
<button data-action="click->hello#greet">Saudar</button>
</div>
</body>
</html>

Class 'App\Http\Controllers\Flash' not found in Laravel 5.1

I tried lot,googling even took help from laracast.com/discuss but could not solve the issue. why the session flash is not working? please drop your suggestion. Here is my code of all_controll.php
<?php
namespace App\Http\Controllers;
use DB;
use App\Quotation;
use App\Model\students;
use Illuminate\Http\Request;
//use Auth;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests;
use App\Http\Controllers\Session;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
class all_control extends Controller
{
public function index()
{
return view('index');
}
public function insert_students(Request $request)
{
$std = new students();
$std->name = $request->input('name');
$std->email = $request->input('email');
$std->save();
return redirect('/index');
}
public function getform()
{
return view('form');
}
public function postform()
{
$roll = Input::get('roll');
$ct_number = Input::get('ct');
DB::table('test')->insert(array(
'name' => $roll,
'age' => $ct_number
));
Flash :: Session ("key",
"You have done successfully!!!!");
//Session::flash('message','You have done successfully!!!!');
return Redirect::route('getform');
//return redirect('/index');
}
}
and my form.blade.php code is given below
<!DOCTYPE html>
<html lang="en">
<head>
<title>Title</title>
<meta charset="UTF-8">
<meta name=description content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap CSS -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" media="screen">
</head>
<body>
<div class="container">
<h1>Form</h1>
<h3>
<?php
if(Session::has('key')){
echo Session::get('key');
}
?>
</h3>
<form action="{{ URL::route('postform') }}" method="post" role="form">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<legend>Form Title</legend>
<div class="form-group">
<label for="">name</label>
<input type="text" class="form-control" name="roll" id="roll" placeholder="Input...">
</div>
<div class="form-group">
<label for="">Marks of Physisc CT</label>
<input type="number" class="form-control" name="ct" id="ct" placeholder="Input...">
</div>
<button type="submit" class="btn btn-primary">Hit the Button</button>
</form>
</div>
</body>
</html>
You can use the built in redirect() helper which will flash the data to the session by using ->with().
public function postform(Request $request)
{
$roll = $request->roll;
$ct_number = $request->ct;
DB::table('test')->insert([
'name' => $roll,
'age' => $ct_number
]);
return redirect('index')->with('key', 'You have done successfully');
}
SIDENOTE:
Inject Request into your method and use it instead of Input. Input was used in laravel 4 while injecting the Request class is the recommended way in laravel 5.1
I have also faced same issue with you.
My solution is to include use Flash; on top of the controller that you wanted to use the Laracasts Flash plugin.
Hope this helps.
return redirect()->route('posts.index')->with('success_msg', 'Post deleted successfully');
Here Success_msg is used to display msg on redirected page.

Autocomplete textbox in MVC returning '[ ]' when values populated from databse and does not show the view with the textbox control placed in

I used the following code to implement autocomplete textbox in MVC. But when I debug the project it shows a pair of angle brackets in the browser. pls examine my code.
controller:
public ActionResult Autocomplete(string searchstr)
{
var tenders = db.farmas.Where(t => t.Itemname.ToLower()
.Contains(searchstr.ToLower())).Take(10)
.OrderBy(t => t.Itemname)
.Select(t => new { label = t.Itemname });
return Json(tenders, JsonRequestBehavior.AllowGet);
}
view:
<!DOCTYPE html>
<html>
<head>
<h2>Autocomplete</h2>
<link href="http://code.jquery.com/ui/1.10.1/themes/base/jquery-ui.css rel="stylesheet"
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js">
</script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.1/jquery-ui.js">
</script>
#Scripts.Render("~/bundles/javascript")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryui")
#Styles.Render("~/Content/themes/base/css")
<script type="text/javascript">
$(document).ready(function () {
$('#Itemname').autocomplete({
source: function (request, response) {
$.getJSON("/NewDefault1/Autocomplete?term=" + request.term, function (data) {
response(data);
});
},
minLength: 3,
delay: 100
});
});
</script>
</head>
<body>
<div id="main">
<div style="padding: 20px;">
pls type in the textbox
</div>
<div style="padding: 20px;">
Product: #Html.TextBox("Itemname")
</div>
</div>
<div id="footer">
</div>
</div>
</body>
</html>
before I had this error that downloaded the file with JSON extension.when the project is debug,which contained the same square brackets as its contents and now the same is shown on the browser . what is wrong in the code? where am I wrong? I also went through the jquery-ui website,but i am not able to make out how to populate the textbox values from database. any help will be appreciated. Thanks in advance.

Ajax Single Field Submission in form

I've created an order form, of which has a large array of fields. I'm now adding coupon functionality so that we can start to give customers discount codes etc.
What's the best way of submitting a single field (the coupon code) using ajax after a "apply coupon" button has been clicked so that the price can be updated on the front end probably using UJS(?) - obviously the final price calculation would happen on the backend?
Cheers.
I would recommend using a JS framework to do Ajax requests. If you JQuery, then you can use the example given to understand how to do a simple post.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<form action="/" id="searchForm">
<input type="text" name="s" placeholder="Search..." />
<input type="submit" value="Search" />
</form>
<!-- the result of the search will be rendered inside this div -->
<div id="result"></div>
<script>
/* attach a submit handler to the form */
$("#searchForm").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
term = $form.find( 'input[name="s"]' ).val(),
url = $form.attr( 'action' );
/* Send the data using post and put the results in a div */
$.post( url, { s: term },
function( data ) {
var content = $( data ).find( '#content' );
$( "#result" ).empty().append( content );
}
);
});
</script>
</body>
</html>

How to get TabIndex for the current selected tab?

All,
I have nested JQuery UI tabs. I want to implement a reloadTab functionality for a nested tab. Currently the following code has static fragments for nested tabs, but eventually they will have urls, so the tabs can behave as ajax tabs. How can I achieve the reloadTab functionality?
<html>
<head>
<link type="text/css" rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/ui-lightness/jquery-ui.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$('#tabContainer').tabs({ selected: 0 });
$('#fragment-1').tabs({ selected: 1 });
});
function reloadTab(tabindex)
{
var smalltabs = $('#fragment-1').tabs({cache:false, spinner:'',selected:0});
$('#tabContainer').tabs('load', smalltabs.tabs('option','selected'));
$('#fragment-1').tabs('load', tabindex);
}
</script>
</head>
<body>
<div id="tabContainer">
<ul>
<li><span>TAB1</span></li>
<li><span>TAB2</span></li>
<li><span>TAB3</span></li>
</ul>
<div id="fragment-1">
<ul class="innerNav" >
<li><span>INNERTAB1</span></li>
<li><span>INNERTAB2</span></li>
</ul>
<div id="fragment-1a" class="innerFragment">Content of inner tab 1</div>
<div id="fragment-1b" class="innerFragment">Content of inner tab 2
<br>Reload tab content</div>
</div>
<div id="fragment-2"></div>
<div id="fragment-3"></div>
</div>
</body>
</html>
Thanks
From the docs:
var $tabs = $('#example').tabs();
var selected = $tabs.tabs('option', 'selected'); // => 0
EDIT
I copied your file, and made the following changes:
Change the reload link to look like this:
href="#" id="reload"
(markdown keeps converting my anchor tag to a link)
Change the jquery to this:
$(function() {
$('#tabContainer').tabs({ selected: 0 });
$('#fragment-1').tabs({ selected: 0 });
$('#reload').click(function(){
var $tabs = $('#fragment-1').tabs();
reloadTab($tabs.tabs('option', 'selected'));
});
});
function reloadTab(tabindex) {
//alert(tabindex); //un-comment for proof.
var smalltabs = $('#fragment-1').tabs({cache:false, spinner:'',selected:0});
$('#tabContainer').tabs('load', smalltabs.tabs('option','selected'));
$('#fragment-1').tabs('load', tabindex);
}

Resources