jQuery: Button add and remove closest - javascript

I have a HTML as follows:
<div class="parent-wrapper">
<div class="test-guided-search-row">
<select class="form-control test-guided-search-row-select-bool-query">
<option>AND</option>
</select>
<select class="form-control test-guided-search-row-select-query-path">
<option>ALL</option>
</select>
<select class="form-control test-guided-search-row-query-type">
<option>abcd</option>
<option>efg</option>
</select>
<input class="form-control" type="text">
<button class="btn btn-primary btn-sm" type="button" data-button-action="addRow">+</button>
<button class="btn btn-primary btn-sm" type="button" data-button-action="deleteRow">-</button>
</div>
</div>
How can I make it so that the button + will add the entire row div next to the div in which the button that was clicked? I am having trouble with this because there are multiple of these row divs and I want to be able to add row next to this div row and remove only that row.

To achieve this you need to use delegated event handlers as the button elements will be dynamically appended to the DOM. From there you can use closest() to find the row, along with clone() and append() or remove() respectively.
Firstly, add classes to the buttons to make identifying them easier:
<button class="btn btn-primary btn-sm btn-add" type="button" data-button-action="addRow">+</button>
<button class="btn btn-primary btn-sm btn-delete" type="button" data-button-action="deleteRow">-</button>
Then you can attach events to them:
$('.parent-wrapper').on('click', '.btn-add', function() {
$(this).closest('.test-guided-search-row').clone().appendTo('.parent-wrapper');
}).on('click', '.btn-delete', function() {
$(this).closest('.test-guided-search-row').remove();
});
Example fiddle

find your row, clone it, append it.
$('.button').on('click', function() {
var row = $(this).closest('.test-guided-search-row').clone();
$('.parent-wrapper').append(row);
})
find your row, delete it.
delete
$('.button').on('click', function() {
var row = $(this).closest('.test-guided-search-row').remove();
})
// you need to define what button is + what button is - with a class name

$('.parent-wrapper').on('click', '.btn-add', function() {
var row = $(this).closest('.test-guided-search-row').clone();
$(this).closest('.test-guided-search-row').after(row);
}).on('click', '.btn-delete', function() {
$(this).closest('.test-guided-search-row').remove();
});
This is what exactly solved my issue. I wanted to append to the closest button click row.

If you want to be able to add row next to a particular div row and remove only that row, you need to add a number as the id to each
This might help:
Pass
$(this).closest('.new-wrapper')[0].id
to addRow(rowId) when clicking on the + button.
function addRow(rowId){
var next = rowId+1;
$(".parent-wrapper #rowId").after('<div id="'+next+'" class = "new-wrapper"> $(".test-guided-search-row").html() </div>);
}

Related

remove readonly from input

I have a pice of code that copy 2 3 divs and the div contains a readonly property.
After that I have a button that says to edit when I click on that button this should remove the readonly and the input field is available to edit.
My code that doesn't work!
my javascript code:
I have tried removeAttr, prop('readonly', false), attr('readonly', false)
$("body").on("click", ".btn",function(){
if($(this).is("#edit")){
$(this).parents(".control-group").removeAttr('readonly');
}else if($(this).is("#save")){
}else if($(this).is("#remove")){
$(this).parents(".control-group").remove();
}
});
The div that I copy:
<div class="control-group input-group" style="margin-top:10px">
<input id="rule" type="text" class="form-control" readonly>
<div class="input-group-btn">
<button id="edit" class="btn btn-danger remove" type="button"><i class="glyphicon glyphicon-remove"></i> Edit</button><button id="remove" class="btn btn-danger remove" type="button"><i class="glyphicon glyphicon-remove"></i> Remove</button>
</div>
</div>
I hope that when i click on edit the readonly disappear and after a click on save and the readonly back again.
Thanks for the help
PS: the remove button works!
You may have better luck with .attr as readonly is an attribute and not a property. See this (Specifically, attributes vs properties)
One issue I see with your code is this line here:
$(this).parents(".control-group").removeAttr('readonly');
You are trying to remove the readonly attribute from a div. I think you mean to remove it from your .form-control which is an input
Maybe try $(this).parents(".control-group").find('input.form-control').removeAttr('readonly'); (i'd do some null checks here. Plenty can go wrong if the selector fails)
Here's a basic example of how to toggle the readonly attribute using jQuery
var readonly = true;
$('button').on('click', (e) => {
readonly = !readonly
$('input').attr('readonly', readonly);
// Extra
if (readonly) {
$('input').attr('placeholder', "I'm readonly");
} else {
$('input').attr('placeholder', "I'm not readonly");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input readonly placeholder="I'm readonly" />
<button>Toggle Readonly</button>
You're applying remove to the wrong element.
Try this:
$("body").on("click", ".btn",function(){
if($(this).is("#edit")){
$(this).parents(".control-group").find('input').removeAttr('readonly');
}
...
}
});
Using the find jQuery function, you can call every input element inside the .control-group element. To further expand the functionality, say, to include select elements or other buttons (with a unlock-readonly class, for instance), you can try:
$(this).parents(".control-group").find('input, select, .unlock-readonly').removeAttr('readonly');

Is there a way to send button id onClick to a bootstrap modal?

Using laravel, I have a list of user details obtained from the database with edit and remove button at the end of each record. When i click the remove button, the particular record gets removed, but when I added a modal such that when the delete button is clicked, a model appears, but adding the functionality to the confirmation "Yes" button of the modal got tricky, as it deleted the first record no matter which user i need to delete. How do i get the clicked user to be deleted when the modal button is clicked?
I have tried to assign each button the id of the current row.
#foreach($admins as $admin)
<tr>
<td>{{$admin['id']}}</td>
<td>{{$admin['name']}}</td>
<td>{{$admin['email']}}</td>
<td>
<button type="button" class="btn btn-block btn-danger" data- toggle="modal" data-target="#modal-danger" id="{{$admin['id']}}">Remove</button>
</td>
</tr>
#endforeach
<!-- The Button From Modal -->
<button type="button" class="btn btn-outline">Remove</button>
I did it with JS. You can show your modal with $('#modal-danger').modal('show')
So you can add a onClick event to your button that fill a hidden input.
Your button that make the modal appear:
<button type="button" class="btn btn-block btn-danger" onClick="showModal({{$admin['id']}})">Remove</button>
Your hidden input (somewhere in your page):
<input type="hidden" id="id-to-remove" />
Your button from modal:
<button type="button" class="btn btn-outline" onclick="realRemove()">Remove</button>
Your JS:
function showModal(id) {
$('#id-to-remove').val(id);
$('#modal-danger').modal('show');
}
function realRemove() {
$('#modal-danger').modal('hide');
var id = $('#id-to-remove').val();
alert('You can now remove ID ' + id + ' from your database!');
}
This should work
Since you are using jQuery you can use attribute method to get the current clicked user id and pass to the URL:
Your HTML button class
$(".my-btn").click(function(){
var userID = $(this).attr("data-user");
if (typeof userID !== typeof undefined && userID !== false) {
if(userID.length > 0) {
// There you go the user id of the clicked user
console.log(userID);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="my-btn" data-user="user_id_123">Remove</button>
I suggest you to refer the following URL for your further questions regarding attr method https://www.w3schools.com/jquery/html_attr.asp
make a global variable to store the target id and assingn the id to it when clicking the button on the target row
<button type="button" class="btn btn-block btn-danger" data- toggle="modal" data-target="#modal-danger" id="{{$admin['id']}}" onClick=someFunction({{$admin['id']}})>Remove</button>
target_id=0
function someFunction(id) {
target_id=id
}
and then make another function to trigger when clicking on the remove button in the model and from that access the global variable for the target id
that's the optimal way to do it as I can think cheers.

Button click does't alert div contents

I have three dynamically generated div. Each contains different data and buttons.On each button click I want to alert the data.
I have this. but it only shows the first div data for each button click.
form. this form generate dynamically
<input type="hidden" name="price" id="price" class="price" value="
{{$data->price}}"/>
<input type="submit" name="submit" id="button1" class="btn btn-danger
btn-lg raised button1"/>
<div>
<script>
$('.button1').on('click', function(){
var id = $('.price').val();
alert(id);
});
</script>
Try below code:
$('button').on('click', function(){
var id = $(this)[0].id;
alert(id);
});
Since you told that your divs are dynamic generated, you've to bind your click event through to another static element or document.
This should help
$(document).on('click', '.button1' function(){
var id = $('.id').val();
alert(id);
});

How to get data from attributes then disable buttons accordingly

I have run a bit of problem with our user interface, here's my code:
I have a button here inside a
<button class="btn btn-info" type="button" id="btnSubmit" data-btn="{{ row[1] }}" data-id="{{ row[2] }}" data-toggle="modal" data-target="#myModal" contenteditable="false" disabled='disabled'> Pay</button>
I have been using row[2] from another function and it worked, so this time i used row[1] to evaluate data. The condition is that
when the row[1] of that row is empty the button would be disabled and would be colored to btn btn-danger and the text would be
made to "Paid" however thorugh my attempts I only made everything disabled or perhaps the last entry only as disabled. Here's my latest attempt:
<script type="text/javascript">
$(document).ready(function() {
var button = document.getElementById('btnSubmit');
var id = button.dataset.id;
$('#btnSubmit').attr('data-btn').onkeyup(function() {
if($(this).val() != '') {
$('#btnSubmit').prop('disabled', true);
}
else{
$('#btnSubmit').prop('disabled', false);
}
});
});
</script>
And its disabling all buttons. I just want the bytton to be enabled when its empty and disabled if its empty, and again as Ive said would be colored to btn btn-danger and the text would be made to "Paid" how do I do this in this case?
I've read the documentations and everything but it didn't work for some reasons. I also tried having an invisible input and getting its id but no luck. Please help
Okay... Assuming that data-bnt is the target element to check on keyup.
(I don't know what data-id is for...)
And that the target must not be empty to enable the submit button.
Then try this:
$(document).ready(function() {
var button = $('#btnSubmit');
var target = $('#'+button.data('btn'));
target.on("keyup",function(){
button.prop('disabled', ($(this).val() == '') ? true : false );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="targetID">
<button
class="btn btn-info"
type="button"
id="btnSubmit"
data-btn="targetID"
data-toggle="modal"
data-target="#myModal"
contenteditable="false"
disabled='disabled'> Pay</button>

HTML Selectable table with edit/delete/view options

I have table, where you can select table rows, and it passes the information to modal window. But there is problem, I want the popup window to show error if there is no row selected
Button to edit row
<a class="icon icon-pencil js-popup js-tooltip" href="#edit" title="Edit selected row"></a>
JavaScript Code
$(document).on('click', '#table_contactgroups tbody tr', function(e) {
$(this).addClass('selected').siblings().removeClass('selected');
var name = $(this).find('td:first').html();
var id = $(this).attr('id');
$('#edit input[name="name"]').val(name)
$('#edit input[name="id"]').val(id)
$("#name").text(name);
$('#delete input[name="id"]').val(id)
});
Modal
<div id="edit">
<h2 class="text-center ls-large">Edit contact group</h2>
<form class="js-ajax-form" data-ajax-form="edit=a.logged-in;editFrom=
<?php echo URL_BASE; ?>template/header.php"
name="contacts-form" method="post"
action="<?php echo URL_BASE; ?>contactgroups/contactgroup_manager.php?a=edit">
<fieldset>
<!-- <input type="text" name="name" placeholder="Name">-->
<div class="input-wrap">
<input type="text" name="name" maxlength="45" value="" placeholder="Name">
</div>
<input type="hidden" name="id" value="">
</fieldset>
<div class="controls multiple">
<button class="btn btn-default btn-small" type="submit" name="Edit" value="Edit">Submit</button>
<a class="btn btn-unimportant btn-small js-popup-close" href="#">Cancel</a>
</div>
</form>
</div>
There are two ways you could go with this.
Disable the edit button when no rows are selected.
Display an error when the edit button is pressed with no rows selected.
Arguably the first one is more user-friendly since it stops them making an unnecessary click.
In either case, you need to ensure a row is selected. So if you disable your edit button at page load like this using the disabled attribute:
<button type="button" id="EditButton" disabled>Edit</button>
Then in your existing function which runs when the user clicks on a row, you can enable it, since you now have a selected row:
$(document).on('click', '#table_contactgroups tbody tr', function(e) {
//...
$("#EditButton").prop('disabled', false);
});
That way, if there are no rows, the button never gets enabled.
N.B. I notice your Edit "button" is actually a hyperlink. If you want to continue using that, this answer may be helpful in determining how to enable/disable it : Disable link using css. Otherwise you might be better to replace it with a button, or hide it instead. It's more difficult to make hyperlinks unclickable.
If you want to go down route 2, and display an error message when no row is selected, you'll have to handle the click event of the hyperlink. First, give it an id.
<a id="EditLink" class="icon icon-pencil js-popup js-tooltip" href="#edit" title="Edit selected row"></a>
Then handle the click, and check for selected rows. Since you're using the ".selected" class to denote a selected row, this is fairly easy to test for.
$("#EditLink").click(function(event) {
if ($(".selected").length == 0)
{
event.preventDefault(); //stops the normal click behaviour from occurring
alert("Please select a row to edit");
}
});

Categories

Resources