Jquery a .Show() is not fully working - javascript

I have two functions. One that hides a Edit and Delete button, and shows a Save button, and another one that does the opposite (hides save, shows edit and delete).
Right now the first button works: Save appears and Edit/Delete disappear, but the second function does not work: It hides Save but only shows Delete...somehow Edit is not being shown.
button code within a <td>
<td class="col-lg-3 col-lg-offset-1">
<span style="visibility:hidden" class="ID">#Html.DisplayFor(modelItem => item.ID)</span>
<span class="item-edit-button">
<button type="button" onclick="someFunction(this)" class=" btn btn-warning col-lg-4"><span style="margin-right: 5px" class="glyphicon glyphicon-pencil"></span>Edit</button>
</span>
<span class="item-save-button">
<button type="button" onclick="saveFunction(this)" class="btn btn-success col-lg-4"><span style="margin-right: 5px" class="glyphicon glyphicon-trash"></span>Save</button>
</span>
<span class="item-delete-button"> // no use right now - ignore
<button type="button" onclick="deleteFunction(this)" class="btn btn-danger col-lg-4"><span style="margin-right: 5px" class="glyphicon glyphicon-trash"></span>Delete</button>
</span>
</td>
the JQuery
<script>
function someFunction(element)
{
$(element).hide();
$(element).closest("td").find("span.item-save-button").show();
$(element).closest("td").find("span.item-delete-button").hide();
}
function saveFunction(element)
{
$(element).hide();
$(element).closest("td").find("span.item-edit-button").show();
$(element).closest("td").find("span.item-delete-button").show();
}
</script>
http://jsfiddle.net/isherwood/BrP2a/
Hopefully I am just making some silly mistake.
ANSWER
I was accidentally hiding the button, not the span, thus when I tried to show my edit button's span it did not work as the button itself was hidden originally to fix this I had to use.
function someFunction(element) {
$(element).closest("span").hide();
$(element).closest("td").find("span.item-save-button").show();
$(element).closest("td").find("span.item-delete-button").hide();
}
function saveFunction(element) {
$(element).closest("span").hide();
$(element).closest("td").find("span.item-edit-button").show();
$(element).closest("td").find("span.item-delete-button").show();
}

You have hide the actual button by $(element).hide(); in someFunction and you are showing item-edit-button span so actual button is still hidden. Try this,
function saveFunction(element)
{
$(element).hide();
$(element).closest("td").find("span.item-edit-button button").show();
$(element).closest("td").find("span.item-delete-button").show();
}

You have to define the function before your HTML elements that mean if your elements are in body tag then you have to define the function in the head tag
then you can change the code little bit
function someFunction(element)
{
$(element).hide();
$(element).siblings("span.item-save-button").show();
$(element).siblings("span.item-delete-button").hide();
}
function saveFunction(element)
{
$(element).hide();
$(element).siblings("span.item-edit-button").show();
$(element).siblings("span.item-delete-button").show();
}
Here is the working fiddle for the code
http://jsfiddle.net/murli2308/YeZDe/

I think the problem is your use of the .closest() function, which finds the nearest parent of the given selector, starting with the selected element. See documentation for closest().
You probably are intending to use the .prev() and .next() functions.

You are hiding the Element (the button) but them Showing the TD. So the result is TD is visible but button itself is still hidden.
Here is the working code:
function someFunction(element)
{
$(element).closest("td").find("span.item-edit-button").hide();
$(element).closest("td").find("span.item-save-button").show();
$(element).closest("td").find("span.item-delete-button").hide();
}
function saveFunction(element)
{
$(element).closest("td").find("span.item-save-button").hide();
$(element).closest("td").find("span.item-edit-button").show();
$(element).closest("td").find("span.item-delete-button").show();
}

This doesn't answer your question directly, but I think it presents a simplification of your code that may help.
http://jsfiddle.net/isherwood/BrP2a/4/
<button id="item-edit" ...>...Edit</button>
...
$('#item-edit').click(function () {
$(this).hide();
$('#item-save').show();
$('#item-delete').hide();
});
$('#item-save').click(function () {
$(this).hide();
$('#item-edit, #item-delete').show();
});

Related

document.getElementById() not working as intended with multiple ids

I have an issue with document.getElementById(). Basically I have different forms each one with a different id and I'm using a bit of Javascript to replace some classes and add dinamically file name after upload.
That should be really easy, but I don't know why even if the ids are totally unique I get a weird behavior: whatever is the form in which I submit a file javascript will apply changes always on the first of them.
function spinnerLoad(){
document.getElementById('file-name[[${id}]]').textContent = this.files[0].name;
document.getElementById('spinner[[${id}]]').classList.replace('fas', 'spinner-border');
document.getElementById('spinner[[${id}]]').classList.replace('fa-file-upload', 'spinner-border-sm');
document.getElementById('uploadForm[[${id}]]').submit()
}
/*I'm using Bootstrap for my styling rules*/
/*${id} variable is server-side and it's there to make unique each form, I'm using Thymeleaf template engine*/
<form th:id="'uploadForm'+${id}" method="post" enctype="multipart/form-data" th:action="#{/upload/{id} (id=${id})}">
<label for="file-upload" class="btn btn-outline-success">
<span th:id="'spinner'+${id}" class="fas fa-file-upload"></span> <b>Upload file:</b> <i th:id="'file-name'+${id}">No file selected</i>
</label>
<input id="file-upload" type="file" name="multipartFile" accept="application/pdf" style="display: none" th:onchange="spinnerLoad()"/>
</form>
I googled the problem but I didn't manage to find a specific answer to my issue, so that's why I'm here bothering you.
I hope someone can help my figure this out, thank you.
You get a lot of repeating code and that can be hard to maintain. Here I placed the event listener on the the parent <div> to all the buttons. Then I need to test if is a button. And there is no need for an id for each button.
Actually, if you are just replacing a class name you don't even need to do the test (if()), because replace() will only do the replacement when the old value is present. This should be fine:
buttons.addEventListener('click', e => {
e.target.classList.replace('btn-success', 'btn-danger');
});
But here is the full example with the test:
var buttons = document.getElementById('buttons');
buttons.addEventListener('click', e => {
if (e.target.nodeName == 'BUTTON') {
e.target.classList.replace('btn-success', 'btn-danger');
}
});
.btn-success {
background-color: green;
}
.btn-danger {
background-color: red;
}
<div id="buttons">
<button class="btn-success">Button 1</button>
<button class="btn-success">Button 2</button>
<button class="btn-success">Button 3</button>
</div>
You're missing the css that would make this work, but otherwise your example is functional. However, it can be done more simply by working on the buttons as a class instead of individually.
var btns = document.getElementsByClassName("btn");
var addDanger = function(){
this.classList.replace('btn-success', 'btn-danger')
};
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener('click', addDanger, false);
};
.btn {height:20px; width: 50px;}
.btn-success {background-color:green}
.btn-danger {background-color:red}
<button id="btn1" class="btn btn-success"></button>
<button id="btn2" class="btn btn-success"></button>
<button id="btn3" class="btn btn-success"></button>

Clicking a button and detect its status in jquery

I am have a button like this:
<a class="btn btn-sm btn-danger employee" data-emp_id="23" href="javascript:void(0)" disabled>Resign</a>
If ajax response success it adds disabled to this button.
Here I need to this button has disabled on click event. If it has, need to alert different message, or if it hasn't I need to alert different message.
This is how I tried it.
$(document).on('click', 'a.employee', function(e){
var empID = $(this).data('emp_id');
if($(this).is(':disabled')) {
alert('message1');
} else {
alert('message2');
}
});
Also tried it something like this:
$(document).on('click', 'a.employee:not(:disabled)', function(e){
var empID = $(this).data('emp_id');
alert('here');
});
But, both are not working for me..
Hope somebody may help me out.
Thank you.
You cannot disable an anchor element, and adding a disabled attribute to it would mean that your HTML is invalid.
To solve this you could simply add a class to the element and key the click behaviour on that. Try this:
$(document).on('click', 'a.employee', function(e) {
e.preventDefault();
var empID = $(this).data('emp_id');
if ($(this).hasClass('disabled')) {
console.log('message1');
} else {
console.log('message2');
}
});
.disabled {
color: #CCC;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="btn btn-sm btn-danger employee disabled" data-emp_id="23" href="#">Disabled</a>
<a class="btn btn-sm btn-danger employee" data-emp_id="23" href="#">Not disabled</a>
Also note the use of preventDefault() instead of adding javascript: to the href attribute of the a element.
Disabled is not an attribute and hence not a property of anchor tag
try this way
$(document).on('click', 'a.employee[disabled])', function(e){
var empID = $(this).data('emp_id');
alert('here');
});

Identify the Click Event in bootstrap touch spin

I am little bit confusion to find the click event in the class using jquery.
my question is how to identify whether I click touchspin down or up
I am using bootstrap touch spin.
<button type="button" class="btn btn-default bootstrap-touchspin-down">-</button>
<input type="number" value="18" onchange="calculatetotal(3)" style="width: 100%; padding: 0px; display: block;" class="ex_limit form-control" readonly="" id="qty3">
<button type="button" class="btn btn-default bootstrap-touchspin-up">+</button>
I Want to calculate some process in when Up botton clicked and some process in down button click.
Here I try to Identify the button using class.
$('.btn, .btn-default, .bootstrap-touchspin-down').click(function(){
alert("down!");
});
Please help me to do this task.
$('[class*="bootstrap-touchspin-"]').click(function(event) {
var $this = $(this);
if ($this.hasClass('bootstrap-touchspin-down')) {
alert('down');
} else if ($this.hasClass('bootstrap-touchspin-up')) {
alert('up');
}
});
Alternatively:
$('.bootstrap-touchspin-down').click(function(event) {
alert('down');
});
$('.bootstrap-touchspin-up').click(function(event) {
alert('up');
});
better and easy way is to handle change event like given below
$('input[name=\'cart-quantity\']').on("change",function(event){
alert("hi")
})

Adding "Clear Field" buttons to Bootstrap 3 inputs using jQuery + CSS class

How can I add a "Clear field" button to multiple Bootstrap 3 input fields just using jQuery and a CSS class?
I've found solutions that can add a 'clear field' button to a field with a particular ID, but nothing so far that can do it by class. I've got a form with a lot of fields and I'd rather not have to repeat my code over again for each field.
I've tried this so far (Bootply), but I can't figure out how to get jQuery to clear just the one field and toggle the one icon, not all of them.
//JS
$(document).ready(function(){
$(".searchinput").keyup(function(){
$(".searchclear").toggle(Boolean($(this).val()));
});
$(".searchclear").toggle(Boolean($(".searchinput").val()));
$(".searchclear").click(function(){
$(".searchinput").val('').focus();
$(this).hide();
});
});
//HTML
<div class="btn-group">
<input id="searchinput" type="search" class="form-control searchinput" placeholder="type something..." value="">
<span id="searchclear" class="searchclear glyphicon glyphicon-remove-circle"> </span>
</div>
<div class="btn-group">
<input id="searchinput" type="search" class="form-control searchinput" placeholder="type something..." value="">
<span id="searchclear" class="searchclear glyphicon glyphicon-remove-circle"></span>
</div>
//CSS
.searchinput {
width: 200px;
}
.searchclear {
position:absolute;
right:5px;
top:0;
bottom:0;
height:14px;
margin:auto;
font-size:14px;
cursor:pointer;
color:#ccc;
}
1) You can use $(this) to get a reference to the current targeted element
2) Use .next() to toggle the visibility for only the icon which is the next immediate sibling of input that you're currenlty key in
3) Use .prev() to clear only the input which is the immediate previous sibling of clear icon that is clicked:
Final code should look like:
$(document).ready(function () {
$(".searchinput").keyup(function () {
$(this).next().toggle(Boolean($(this).val()));
});
$(".searchclear").toggle(Boolean($(".searchinput").val()));
$(".searchclear").click(function () {
$(this).prev().val('').focus();
$(this).hide();
});
});
Bootply Demo
Try changing your javascript code to this:
$(document).ready(function(){
$(".searchinput").keyup(function(){
$(this).parent().find('.searchclear').toggle(Boolean($(this).val()));
});
$(".searchclear").toggle(Boolean($(".searchinput").val()));
$(".searchclear").click(function(){
$(this).parent().find('.searchinput').val('').focus();
$(this).hide();
});
});
Essentially what it does is add scope to the clear buttons so that it is limited to the sibling. There are other jQuery functions that might be more specific, but this should work.
http://www.bootply.com/130368
Another option would be to use .siblings() to make sure you are targeting just the siblings with the searchclear class.
$(document).ready(function(){
$(".searchinput").keyup(function(){
$(this).siblings(".searchclear").toggle(Boolean($(this).val()));
});
$(".searchclear").toggle(Boolean($(".searchinput").val()));
$(".searchclear").click(function(){
$(".searchinput").val('').focus();
$(this).hide();
});
});
http://www.bootply.com/130369

How to add/append and toggle items to the div on every click of an link in jquery?

I am having the div like below..
<div id="div1">Edit your content
<a id="link1" href="#">click to Edit</a>
<textarea id="text1" cols="3"/>
<input type="button" id="button1" value="Save" />
</div>
What i want is..
I want to show and hide the textarea and save button every time the link is clicked.
And when an save button clicked the textarea content has to be added before the textarea as listitem, every time the save button clicked the edited text has been updated into that list.
Please anyone guide me to do this..
The simples approach would be if the Edit your content part could be wrapped in a container of its own, so that the content of that container could be replaced entirely upon save:
<div id="div1">
<span class="content">Edit your content</span>
<a id="link1" href="#">click to Edit</a>
<textarea id="text1" cols="3"></textarea>
<input type="button" id="button1" value="Save" />
</div>
$('#div1 > a').click(function() {
var parent = $(this).closest('div');
parent.find('textarea').val(parent.find('.content').html());
parent.find(':input, .content, a').toggle();
});
$('#div1 > input[type=button]').click(function() {
var parent = $(this).closest('div');
parent.find('.content').html(parent.find('textarea').val());
parent.find(':input, .content, a').toggle();
});
Demo
You'll note that the declaration of parent could easily be replaced with #div1 in this particular example, but with this code, you could easily change the #div1 > a selector to one that matches several elements (i.e. .editable > a; demo)
Edit
It appears I misread your question the first time around, but the changes aren't all that big.
Rather than setting the textbox to the value of your .content, you would clear it each time you're showing it. Also, you might not want to hide the .content each time the edit link is clicked. At the click of the save button, you create a new element, and append that after the last .content, rather than updating the existing one.
$('#div1 > a').click(function() {
var parent = $(this).closest('div');
parent.find('textarea').val('');
parent.find(':input, a').toggle();
});
$('#div1 > input[type=button]').click(function() {
var parent = $(this).closest('div');
$('<div/>', { 'class': 'content' })
.html(parent.find('textarea').val())
.insertAfter(parent.find('.content:last'));
parent.find(':input, a').toggle();
});​
Note that I've changed .content to a div, because of its block-level behavior. This should of course be reflected in the initial markup as well.
Demo
Edit (2)
To account for your question in comments, about adding the textarea and save button upon link click, you'd have to make a few changes. First of all, the link click listener would have to be updated with code to add the elements, and presumably with a first check to see whether or not they exist already (i.e. second click of link button):
$('#div1 > a').click(function() {
var parent = $(this).closest('div');
var txt = parent.find('textarea');
if(txt.length == 0) {
txt = $('<textarea/>', { id: 'text1', cols: 3 });
txt.appendTo('#div1');
$('<input />', { type: 'button', id: 'button1' }).val('Save').appendTo('#div1');
}
txt.val('');
parent.find(':input, a').toggle();
});
Second, your listener $('#div1 > input[type=button]') will no longer work exactly as written, because there is no such button in the document at the time when the selector is evaluated. To fix this, you could either use a live delegate, such as:
$('#div1').on('click', 'input[type=button]', function() { ... });
Demo. (for earlier jQuery versions, use .delegate(selector, event, handler) rather than .on(event, selector, handler).)
... Or, you could add the listener immediately to the button as you're creating it:
$('<input />', { type: 'button', id: 'button1' })
.val('Save')
.appendTo('#div1')
.click(saveEdit);
Demo
As a bonus, I'm adding focus to the textbox after showing it in these demos. You may want that as well.
you can do it like this
HTML
<div id="div1">Edit your content
<a id="link1" href="#">click to Edit</a>
<ul id="NewElement"></ul>
<textarea id="text1" cols="3" style="display:none;"></textarea>
<input type="button" id="button1" value="Save" />
</div>​
Jscript
$('#link1')​.click(function(){
$('#text1').toggle();
});
$('#button1').click(function(){
$('#NewElement').append('<li>' + $('#text1').val() +'</li>');
});
Live Demo
​
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#link1').click(function(){
$('#some').toggle();
});
$('#button1').click(function(){
$('ul').append('<li>'+$('#text1').val()+'</li>');
})
})
</script>
</head>
<div id="div1">Edit your content
<a id="link1" href="#">click to Edit</a>
<ul></ul>
<div id="some">
<textarea id="text1" cols="3"/></textarea>
<input type="button" id="button1" value="Save" />
</div>
</div>

Categories