I have a web application and I want to implement in it a Switch Button using this bootstrap example, so that the user can choose the language. Also, I need it to be submitted with a POST.
How can I code this type of toggle button, e.g.,
<div class="btn-group btn-toggle">
<button class="btn btn-xs btn-default">pt</button>
<button class="btn btn-xs btn-primary active">eng</button>
</div>
so that when the user clicks in one of them, a POST is submitted with "pt" or "eng" values?
EDIT: I just need a simple POST with redirect. I'm using Django and to translate documention suggests the use of this code:
<form action="{% url 'set_language' %}" method="post">{% csrf_token %}
<input name="next" type="hidden" value="{{ redirect_to }}">
<select name="language">
{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}
{% for language in languages %}
<option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}>
{{ language.name_local }} ({{ language.code }})
</option>
{% endfor %}
</select>
<input type="submit" value="Go">
</form>
but I don't want a dropdown and the "Go" button. I would prefer the switcher.
You can create a bootstrap form as follows. I have assumed you want to validate the form using a php script (send.php). Add the name attribute, which will help you fetch the values in the validation script.
<form class="form-horizontal" action="send.php" method="post">
<div class="btn-group btn-toggle">
<button class="btn btn-xs btn-default" name="pt">pt</button>
<button class="btn btn-xs btn-primary name="eng" active">eng</button>
</div>
</form>
Give the buttons names and values:
<button class="btn btn-xs btn-default" name="language" value="pt">pt</button>
<button class="btn btn-xs btn-primary active" name="language" value="eng">eng</button>
Then read the data just like you would from your <select>.
Sending only language option with a POST (through AJAX)
// only if pressed a non-active button
$("button", "#language-selection").click(function (event) {
var $btn = $(event.currentTarget)
// only if not already active
if (!$btn.hasClass('active')) {
// you can switch the button as soon as clicked or in AJAX callback
changeActiveButton($btn)
$.post('https://jsonplaceholder.typicode.com/todos/1', {lang: $btn.text()}, function (data) {
// do whatever you want with your API callback data
})
}
})
function changeActiveButton($btn) {
// reset active & button type on previous button
$("button.active", "#language-selection")
.removeClass('btn-primary active')
.addClass('btn-default')
// set active & button type on current button
$btn
.removeClass('btn-default')
.addClass('btn-primary active')
}
#import "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<div id="language-selection" class="btn-group btn-toggle">
<button class="btn btn-xs btn-default">pt</button>
<button class="btn btn-xs btn-primary active">eng</button>
</div>
Related
do you have some tips how to put buttons values to the Django sqlite database?
I have a page with some buttons with theirs values and some final button, which would send the buttons values to the database after the final button click.
Thanks.
Here is HTML intention:
<body>
<div class="row">
<form action="" method="post">
<div class="col-md-4">
<button type="button" class="btn btn-primary btn-lg overflow-hidden" value="1">Example1</button>
</div>
<div class="col-md-4">
<button type="button" class="btn btn-primary btn-lg overflow-hidden" value="2">Example2</button>
</div>
<div class="col-md-4">
<button type="button" class="btn btn-primary btn-lg overflow-hidden" value="3">Example3</button>
</div>
</div>
<input type="submit" value="Send to database">
</form>
</body>
class ValuesButtons(models.Model):
value = models.CharField(max_length=100, verbose_name="Value")
For Example: user clicks on example 1, next on Submit and it will send to database as value 1
If you are trying to submit the values in your buttons to your django database, you would have to first change your buttons by adding a name to them like this:
<button type="button" class="btn btn-primary btn-lg overflow-hidden" value="1" name="btn-1">Example1</button>
then inside your view, you could check to see if the button was pressed and there is a value in POST. Also, this won't work if your value is "0":
if (request.method == "POST):
if (request.POST.get('btn-1', False)):
new_value_button = ValueButtons(value=request.POST.get(
'btn-1'))
new_value_button.save()
This will get and save the values of the specific button pressed.
so i have modal to confirm delete action, but when the tabel data is null / dont have any data, got have an error because i dont have id to call? but if i have more than 1 data my delete modal code is works perfectly.. an error occurs when I delete the last data in the table.
i have already try :
the error message is :
Undefined variable $listproduct on --> index.blade.php)
Possible typo $listproduct
Did you mean $listproducts?
my loop function is #foreach($listproducts as $listproduct)
this is my button :
<td>
<a href="#" class="btn btn-danger delete"
data-toggle="modal"
data-target="#deleteModal"
productid="{{$listproduct->id}}"> Delete
</a>
</td>
this is my modal :
<!-- Delete Warning Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="Delete" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Delete Contact</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form action="{{ route('products.destroy', $listproduct->id ) }}" method="post">
#csrf
#method('DELETE')
<div class="modal-body">
<label for="id">
<input id="id" name="productid">
</label>
<h5 class="text-center">Are you sure you want to delete this contact?</h5>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-sm btn-danger">Yes, Delete Contact</button>
</div>
</form>
</div>
</div>
</div>
<!-- End Delete Modal -->
this is my script to get ID ( I use this when i write this code :
<form action="{{ url('delete', 'id' ) }}" method="post">
but still not works
) :
$(document).on('click','.delete',function(){
let id = $(this).attr('productid');
$('#id').val(id);
});
this is my Product Controller :
public function destroy($id): RedirectResponse
{
$deleteads = Product::findOrFail($id);
$deleteads->delete();
return redirect('products');
}
and this is my route (iam using Resource):
Route::group(['middleware' => ['auth']], function() {
***Route::resource('products', ProductController::class);***
Route::delete('/selected-products', [ProductController::class, 'deleteSelectedItem'])->name('products.deleteSelected');
});
First, you can't use your own productid attribute in HTML, thus you should use data attribute you save your information.
Second, your form in the modal doesn't get it's action attribute updated and thus only One product ID remains in the action attribute.
Try putting a # in the action first, and then when an item is clicked to be deleted, use JQuery to update your form's action and put the proper URL and the ID of the product.
Your ID should be saved in data attribute like below:
<td>
<a href="#" class="btn btn-danger delete"
data-toggle="modal"
data-target="#deleteModal"
data-productid="{{$listproduct->id}}"> Delete
</a>
</td>
Form in the modal:
<form action="#" method="post" id="delete_product_form">
#csrf
#method('DELETE')
<div class="modal-body">
<label for="id">
<input id="id" name="productid">
</label>
<h5 class="text-center">Are you sure you want to delete this contact?</h5>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-sm btn-danger">Yes, Delete Contact</button>
</div>
</form>
JQuery code for handling the form's action attribute update:
$(document).on('click','.delete',function(){
let id = $(this).data('productid');
$('#delete_product_form').attr('action', '/products/' + id);
});
I have a get form that works well on one view.
http://myurl.com/myapp/filter_objects/?risk__worktask=1&craft=3
I have another view to export this filtered list to pdf. For now i'm storing the results in session and accessing list from there in my pdf view, but ideally i would like to pass the filter parameters from the GET form directly to the export_to_pdf view.
Is that possible in django ? [ to have a given GET form send to two different urls with two submit buttons ? Would be great !
Thanks !
Here's my form
<form method="get">
<div class="well">
<h4 style="margin-top: 0">Filter Objects</h4>
<div class="row">
<div class="form-group col-sm-4 col-md-3">
{{ filter.form.risk__worktask.label_tag }}
{% render_field filter.form.risk__worktask class="form-control" %}
</div>
<div class="form-group col-sm-4 col-md-3">
{{ filter.form.craft.label_tag }}
{% render_field filter.form.craft class="form-control" %}
</div>
</div>
<button type="submit" class="btn btn-primary">
<span class="glyphicon glyphicon-search"></span> Search
</button>
</div>
<div class="well">
<h4 style="margin-top: 0">Filtered Ratings: {{ filter.qs.count }}</h4>
<a href="{% url 'myapp:export_ratings_to_pdf_by_worktask' %}">
<button type="button" class="btn btn-success">Export Filtered List ({{ filter.qs.count }} items)</button>
</a>
</div>
Why don't u use the formaction= tag attribute in your button to override the form action?
<form method="get" action="firstView">
<input ...
<input ...
<button ...>Submit to first view</button>
..
..
<button formaction="{% url 'myapp:secondView' %}" ...>Submit to second view</button>
</form>
It is a HTML5 attribute but it is supported by all the major browsers.
FormAction browser support
I have a blade view. When the user select an item a modal view appears in the same HTML.
My modal have 3 buttons. Each button have to redirect by post request to specific functions in my controller.
CarsController
class CarsControllerextends Controller
{
index(){
...
return view('cars')->with(['car'=>$response]);
}
// execute when the user click on save button
save(Request $request){
...
}
// execute when the user click on delete button
delete(Request $request){
...
}
// execute when the user click on remove button
remove(Request $request){
...
}
}
Modal
<form role="form" method="POST" action="{{ url('/guardarTurno') }}">
{{ csrf_field() }}
<!-- 3 hidden inputs to save the id of the item that the user selected ... is the best way?-->
<input type="hidden" id="cancha" name="cancha" value="" class="form-control">
<input type="hidden" id="fecha" name="fecha" value="{{$agenda['fechaElegida']}}" class="form-control">
<input type="hidden" id="hora" name="hora" value="" class="form-control">
<button type="submit" class="btn btn-labeled btn-success button-infousuario">
<span class="btn-label"><i class="fa fa-check fa-fw"></i></span>
Save
</button>
<button type="submit" class="btn btn-labeled btn-warning button-infousuario">
<span class="btn-label"><i class="fa fa-exclamation-triangle fa-fw"></i></span>
Delete
</button>
<button type="submit" class="btn btn-labeled btn-danger button-infousuario">
<span class="btn-label"><i class="fa fa-times fa-fw"></i></span>
Remove
</button>
</form>
What I want is:
Save button make a post request to save() method
Remove button make a post request to remove() method
Delete button make a post request to delete() method
Each of three button need the same ids
Thanks!
You will have to make 3 different forms to send to 3 different functions.
After your Save button, close the first </form>.
Then start a new form for each of the remaining buttons (Delete & Remove). Each form will have a different action
<form action="/remove" method="post">
{{ csrf_field() }}
<input type='hidden' name='id' value='1' />
<button type='submit'>Remove</button>
</form>
Then the same for Delete
Don't forget to define routes for each of the action=''
I have a div, which contains some text and two buttons. I have an onclick attribute on the div, because I want to be able to click anywhere inside of it to activate an event, except for the two buttons. I don't want the event to activate if I hit one of the buttons. I can't seem to figure out where to put the "onclick", though, because it either selects all or not enough. Is there a way to exclude these two buttons from the selection?
My HTML right now is:
<div id="event" class="span8" onclick="preview({{ name.event_id }})">
<strong>
{{ name.title|truncatechars:50 }}
</strong> <br>
Location: {{ name.location|truncatechars:50 }} <br>
Start Date: {{ name.start|truncatechars:50 }} <br>
End Date: {{ name.end|truncatechars:50 }}
<a class="page btn btn-primary btn-small" href="/event/{{ name.event_id }}">Event Page</a>
<button class ="page btn btn-danger btn-small" id="{{ name.event_id }}" href="#" onClick="removeEvent({{ name.event_id }}, {{ user.get_profile.id }})">
<i id="icon" class="icon-minus-sign icon-white"></i>
Remove
</button>
...
</div>
You can just add a call to stopPropagation in the button onClick attribute, like this:
<button class ="page btn btn-danger btn-small" id="{{ name.event_id }}" href="#" onClick="event.stopPropagation(); removeEvent({{ name.event_id }}, {{ user.get_profile.id }})">
Previously answered here: How to stop event propagation with inline onclick attribute?