Dropdown menu not being displayed on first click after being created dynamically - javascript

I have created a dropdown menu which is being populated dynamically when the button is pressed however the content is not being displayed until the button is clicked several times, once it has been displayed it works ok.
The HTML is:
$('#btnGroupDrop1').on( 'click', $('#availableVans'), function() {
getAvailableVans();
});
function getAvailableVans() {
$.ajax({
url: "${ctx}/str/getDeliveryVans.jx?${_csrf.parameterName}=${_csrf.token}",
type: 'POST',
contentType: 'application/json',
success: function(data) {
var buttonHtml = '<button id="buttonGroupDrop1" type="button" class="btn btn-secondary dropdown-toggle" data-toggle="dropdown" aria-expanded="false"> Add new list for:</button>\n';
var divHeader = '<div id="availableVans" class="dropdown-menu" aria-labelledby="buttonGroupDrop1">\n';
var vanList = "";
$.each( data.vans ,function( idx, van ){
var userVan = '<a class="dropdown-item newListBtn" data-id="' + van.id + '" data-color="' + van.strelColor + '" data-user="' + van.username + '">' + van.username + '</a>';
vanList = vanList + userVan + "\n";
});
var allVans = '<a class="dropdown-item newListBtn" data-id="0" data-color="" data-user="ALL VANS">ALL VANS</a>\n';
var divFooter = '</div>';
$('#buttonGroup').html( buttonHtml + divHeader + vanList + allVans + divFooter);
},
error: function(data,status,er) {
alert("Failure to retrieve list of vans");
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="buttonGroup" class="btn-group" role="group">
<button id="btnGroupDrop1" type="button" class="btn btn-secondary dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
Add new list for:
</button>
<div id="availableVans" class="dropdown-menu" aria-labelledby="btnGroupDrop1">
<c:forEach var="van" items="${map.vans}" varStatus="status">
<a class="dropdown-item newListBtn" data-id="${van.id}" data-color="${van.strelColor}" data-user="${van.username}">${van.username}</a>
</c:forEach>
<a class="dropdown-item newListBtn" data-id="0" data-color="" data-user="">ALL VANS</a>
</div>
</div>

after the click should be a selector and you wrote an element
change this code
$('#btnGroupDrop1').on( 'click', $('#availableVans'), function() {
getAvailableVans();
});
to
$(document).on( 'click', '#btnGroupDrop1', function() {
getAvailableVans();
});

Related

How to dynamically add form elements in jquery?

I'm trying to created a dynamic form in rails with a little bit of javascript I have a problem I only get one row in the output when using pry apparently it's because I have the same params for every field input since I use jQuery .clone, maybe someone has struggled with something similar can share some knowledge, how to dynamically add index to params in this form with javascript ?
#extends('Admin.master')
#section('content')
<div class="p-5">
<h3><i class="fas fa-cog ml-2"></i>Setting</h3><hr>
<form action="{{ route('settings.update', $setting->id) }}" method="POST" >
#csrf
#method('PUT')
<div id="showDynamic">
</div>
</form>
</div>
#endsection
#section('script')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
let count = 1;
$('.add').click(function(){
count++;
dynamic(count);
});
dynamic(count);
function dynamic(number) {
var html = '' +
'<div class="row">\n' +
'<div class="col-md-4">\n' +
'<input class="form-control" placeholder="Name">\n' +
'</div>\n' +
'<div class="col-md-4">\n' +
'<input class="form-control" placeholder="Link">\n' +
'</div>\n' +
'<div class="col-md-2">\n' +
'<a class="btn btn-primary" id="add">Add</a>\n' +
'<a class="btn btn-danger" id="delete">Delete</a>\n' +
'</div>\n' +
'</div>';
$('#showDynamic').append(html);
}
});
</script>
#endsection
1st id must be unique .. So change id="add" and id="delete" to classes class="btn btn-primary add"
2nd event-binding-on-dynamically-created-elements After changing the id to class use $(document).on('click' , '.add' , function(){ //code here })
Your code should be
<script>
$(document).ready(function(){
let count = 1;
$(document).on('click' , '.add' , function(){
count++;
dynamic(count);
});
dynamic(count);
function dynamic(number) {
var html = '' +
'<div class="row">\n' +
'<div class="col-md-4">\n' +
'<input class="form-control" placeholder="Name">\n' +
'</div>\n' +
'<div class="col-md-4">\n' +
'<input class="form-control" placeholder="Link">\n' +
'</div>\n' +
'<div class="col-md-2">\n' +
'<a class="btn btn-primary add">Add</a>\n' +
'<a class="btn btn-danger delete">Delete</a>\n' +
'</div>\n' +
'</div>';
$('#showDynamic').append(html);
}
});
</script>
$(document).ready(function(){
let count = 1;
$(document).on('click' , '.add' , function(){
count++;
dynamic(count);
});
dynamic(count);
function dynamic(number) {
var html = '' +
'<div class="row">\n' +
'<div class="col-md-4">\n' +
'<input class="form-control" placeholder="Name">\n' +
'</div>\n' +
'<div class="col-md-4">\n' +
'<input class="form-control" placeholder="Link">\n' +
'</div>\n' +
'<div class="col-md-2">\n' +
'<a class="btn btn-primary add">Add</a>\n' +
'<a class="btn btn-danger delete">Delete</a>\n' +
'</div>\n' +
'</div>';
$('#showDynamic').append(html);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="showDynamic"></div>

putting conditional user access on ajax

So, I have an ajax script and there's a user that can see the table yet it can't update nor delete the data on the table. here's the script
function tampil_data_asum(){
$.ajax({
type : 'ajax',
url : 'json_asum',
async : false,
dataType : 'json',
success : function(data){
var html = '';
var i;
for(i=0; i<data.length; i++){
html += '<tr>'+
'<td>'+(i+1)+'</td>'+
'<td>'+data[i].tertanggung+'</td>'+
'<td>'+data[i].no_polis+'</td>'+
'<td>'+data[i].tgl_polis+'</td>'+
'<td>Rp.'+number_format(data[i].premi)+'</td>'+
'<td>Rp.'+number_format(data[i].komisi)+'</td>'+
'<td>'+data[i].keterangan+'</td>'+
'<td class="text-center">'+
'<button class="btn btn-success btn-xs asum_detail" data="'+data[i].id_asum+'"><i class="fa fa-info-circle"></i></button>'+' '+
'<button class="btn btn-info btn-xs asum_edit" data="'+data[i].id_asum+'"><i class="fa fa-edit"></i></button>'+' '+
'<button " class="btn btn-danger btn-xs asum_hapus" data="'+data[i].id_asum+'"><i class="fa fa-trash"></i></button>'+
'</td>'+
'</tr>';
}
$('#show_data_asum').html(html);
}
});
}
I want to put conditional on the button so when the user logs in, he can't access these buttons
Since your condition based on user's levels, I would suggest this css method. Just check the user level in if condition
var html = '';
var i;
if(user_level >= 5) {
//add one css class which will make the button non-clickable
for(i=0; i<data.length; i++){
html += '<tr>'+
//your other tds
//added the no-click class to the buttons
'<td class="text-center">'+
'<button class="no-click btn btn-success btn-xs asum_detail" data="'+data[i].id_asum+'"><i class="fa fa-info-circle"></i></button>'+' '+
'<button class="no-click btn btn-info btn-xs asum_edit" data="'+data[i].id_asum+'"><i class="fa fa-edit"></i></button>'+' '+
'<button " class="no-click btn btn-danger btn-xs asum_hapus" data="'+data[i].id_asum+'"><i class="fa fa-trash"></i></button>'+
'</td>'+
'</tr>';
}
} else {
//no need add the class to the buttons. just paste your existing code
}
$('#show_data_asum').html(html);
css:
.no-click {
pointer-events: none;
}

how to disable link after clicking once with jquery

How can i disable a link after clicking on it once with jquery . on clicking the link its adding an input field inside a div with unique id. I am getting the values in a dropdown from a variable.
$(document).ready(function() {
var count = 1;
$(".block").on('click', function(){
$("#textInput").append(
'<div class="cgparent" id="input'+count+'">' +
'<div class="col-md-8">' +
'<input class="form-control" type="text">' +
'</div>' +
'<div class="col-md-4">' +
'<button style="margin-right: 5px" class="btn btn-info" id="edittext"><i class="fa fa-pencil" aria-hidden="true"></i></button>' +
'<button class="btn btn-danger" type="button" id="removebtn"><i class="fa fa-trash-o" aria-hidden="true"></i></button>' +
'</div>' + '<br><br>' +
'</div>'
).show();
count++;
});
});
<?php if ($table_name == "questions") {?>
<div class="dropdown" >
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Add Block
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<?php
$question_fields = $this->db->list_fields('questions');
for ($i=0; $i<count($question_fields); $i++){?>
<li><a class="block" ><?php echo $question_fields[$i]?></li>
<?php } ?>
</ul>
</div>
<?php } ?>
If adding some CSS is ok for you this is the simplest I had found:
Javascript:
$(document).on('click', '#buttonSelector', function () {
$(this).addClass('disabled');
});
CSS:
.disabled {
/* if you also want it to fade a bit:
opacity: 0.5
*/
pointer-events: none;
cursor: default;
}
Using the following code will set a variable true once the link is clicked. After the link is clicked again it will ignore the click.
$(document).ready(function() {
var count = 1;
var clicked = false;
$(".block").on('click', function(e){
if(clicked) {
e.preventDefault();
}
clicked = true;
$("#textInput").append(
'<div class="cgparent" id="input'+count+'">' +
'<div class="col-md-8">' +
'<input class="form-control" type="text">' +
'</div>' +
'<div class="col-md-4">' +
'<button style="margin-right: 5px" class="btn btn-info" id="edittext"><i class="fa fa-pencil" aria-hidden="true"></i></button>' +
'<button class="btn btn-danger" type="button" id="removebtn"><i class="fa fa-trash-o" aria-hidden="true"></i></button>' +
'</div>' + '<br><br>' +
'</div>'
).show();
count++;
});
});
I would do it by setting a counter. If the counter is higher than zero, that means the link has been clicked.
<a class="once-only" href="/do-stuff">Click me</a>
<script type="text/javascript">
$(document).ready(function ($) {
var clicked = 0;
$(document).on('click', '.once-only', function () {
if (clicked != 0) {
return false;
}
var clicked = clicked + 1;
});
});
</script>
Update
The comments brought this solution:
<script type="text/javascript">
$(document).ready(function ($) {
$(document).on('click', '.once-only', function () {
​$(this).contents().unwrap();​​
});
});
</script>
The above will simply remove the anchor.

Identifying which button is clicked inside a table

so I have a DataTable and inside each row I put three buttons:
{
"render": function(data, type, row, meta) {
str = '<button id="edit" style="margin-right: 5px;margin-left:10px;" title="Edit" class="btn btn-info action" data-value="' + row.spot_report_id + '"><i class="fa fa-edit"></i></button>' +
'<button id="view" style="margin-right: 5px;" title="View" class="btn btn-info action" data-value="' + row.spot_report_id + '"><i class="fa fa-eye"></i></button>' +
'<button title="Delete" class="btn btn-info deleteButton" data-value="' + row.spot_report_id + '"><i class="fa fa-trash"></i></button>';
return str;
}
}
I handle each click event like this:
$('#spot_reports_tbl').off('click').on('click', '.action', function(e) {
var id = $(this).attr('data-value');
console.log('Target: ' + e.target.id);
switch (e.target.id) {
case 'view':
//view_spotreport(id);
break;
case 'edit':
//edit_spot_report(id);
break;
default:
alert('Cannot handle event. Contact IT Admini');
}
});
The problem is, sometimes it gets the ID sucessfully and sometimes it did not get it. Why is that so?
Thanks!
Use data-* attribute instead of id.
{
"render": function(data, type, row, meta) {
str = '<button data-action="edit" style="margin-right: 5px;margin-left:10px;" title="Edit" class="btn btn-info action" data-value="' + row.spot_report_id + '"><i class="fa fa-edit"></i></button>' +
'<button data-action="view" style="margin-right: 5px;" title="View" class="btn btn-info action" data-value="' + row.spot_report_id + '"><i class="fa fa-eye"></i></button>' +
'<button title="Delete" class="btn btn-info deleteButton" data-value="' + row.spot_report_id + '"><i class="fa fa-trash"></i></button>';
return str;
}
}
Event handling:
$(document).on('click', '.action', function(e) {
var action = $(this).data('action'); // Get action data attribute value
switch (action) {
case 'view':
//view_spotreport(id);
break;
case 'edit':
//edit_spot_report(id);
break;
default:
alert('Cannot handle event. Contact IT Admini');
}
});

russian letters inside javascript script transform into diamonds

I create items on the page like this
var list_item = "";
if (eventstatus == 'CANCELED') {
list_item = '<li class="media list-group-item list-group-item-info" id="tooltip" data-toggle="tooltip" data-placement="right" title="Event canceled! Impossible to enroll!">';
tooltipflag = true;
}
else list_item = '<li class="media list-group-item list-group-item-info">';
list_item += '<a class="pull-left" href="#">';
list_item += '<img class="media-object img-thumbnail" src="holder.js/200x120" alt="NO IMAGE">';
list_item += "</a>";
list_item += '<div class="media-body">';
list_item += '<h4 class="media-heading">';
if (eventstatus == 'CANCELED') list_item += name + ' <span class="label label-danger">' + eventstatus + ' <span class="glyphicon glyphicon-warning-sign"></span></span>';
else if (eventstatus == 'DRAFT') list_item += name + ' <span class="label label-warning">' + 'SOON' + ' <span class="glyphicon glyphicon-pencil"></span></span>';
else list_item += name + ' <span class="label label-primary">' + 'NEW' + ' <span class="glyphicon glyphicon-flag"></span></span>';
list_item += '</h4>';
list_item += '<p>' + description + '</p>';
list_item += '<br>';
list_item += '<div class="form-group pull-right">';
list_item += '<button type="submit" class="btn btn-info btn-sm" data-toggle="modal" id="info_button' + i + '" data-target="#info' + i + '" >';
list_item += '<span class="glyphicon glyphicon-info-sign"></span> Просмотреть информацию';
list_item += '</button>';
if (eventstatus == 'CANCELED') list_item += '<button type="submit" class="btn btn-success btn-sm disabled" data-toggle="modal" id="enroll" data-target="#enroll">';
else list_item += '<button type="submit" class="btn btn-success btn-sm" data-toggle="modal" data-target="#enroll">';
list_item += '<span class="glyphicon glyphicon-plus"></span> Записаться';
list_item += '</button>';
list_item += '</div></div></li>';
return list_item;
But words Просмотреть информацию & Записаться look like
But if I write it in html code - not in javascript function - it looks properly.
What is wrong?
Assuming your file is properly encoded in UTF-8 and served as UTF-8 (check the settings of your http server if necessary), you can declare the script in UTF-8 in the import like this :
<script charset="UTF-8" src="yourFile.js"></script>

Categories