create reset value button on select2 - javascript

im using select2 and try to create a reset button for each select. i have 6 select.
my script is like this
$('.deggre').on('change', function() {
var deggre = $( this ).val();
var span = $("#dropdownMenu1").find('span').clone(); // Copy 'X' span.
$("#dropdownMenu1").text(deggre); // Insert text first.
$("#dropdownMenu1").append(span); // Then, append the 'X' span.
if($(this).val() == "")
$('#dropdownMenu1').css({"display": "none"});//value is none then hide
else
$('#dropdownMenu1').css({"display": "inline-block"});//have value then show
});
$("#dropdownMenu1").click(function(){
$(".deggre").val("");
});
my script didnt work for this case. how to solve this problem?
i need to show the button when we choose option on select2, and give innerHtml to the button. and then when the button click, its will reset his own select then the button is gone cause it didnt get the value.
heres my jsfiddle
https://jsfiddle.net/acvxeq8x/2/

You need to trigger the change
$("#dropdownMenu2").click(function(){
$(".position").val("").trigger('change');
});
I have updated your fiddle: https://jsfiddle.net/acvxeq8x/3/

Here is the simplified and minimal version of your code which is pretty straight forward. The code below seems long because of comments added within for explanation. Hope you will ignore them once you understand.
HTML Changes
<div class="wrap">
<!--Remove everything within wrap div and keep one copy of button in js to dynamically
construct the button tag-->
</div>
New CSS added
button.btnspl{
margin:10px;
/*Bit styling for dynamically created buttons*/
}
JS Changes
//Bind single change event to all your select element
$('.deggre,.position,.year').on('change', function() {
var ctrl=$(this); //reference for current element
var ctrlClass=ctrl[0].classList[0]; //get the first class which will be the class given
//to your original select element like deggre, position, year etc.,
$('button.btnspl[data-control="'+ctrlClass+'"]').remove();
//Since your select element is single select type, I hope you want to keep only one tag
//for each select. So, you remove other tags with above line
if(ctrl.val() == "")return; //return if value is empty, you aren't creating anything
var btn=$('<button class="btn btn-grey btnspl" type="button"><span class="glyphicon glyphicon-remove"></span></button>');
//Button copy from your wrap div
var option = $('<span>'+ctrl.val()+'</span>');
//get the selected option and place it in span
var span = $(deggre).insertBefore(btn.find('span'));
//insert the above created span before the glyphicon-remove in button
btn.attr('data-control',ctrlClass);
//the created button should have information about the control which created it
//so wrapping the ctrlClass [deggre, year, position] into data-* attribute of created button
//this will be used to remove particular button and clear its respective select,
//on different scenarios
$('.wrap').append(btn);
//append the button to .wrap div
});
//attaching close click event to glyphicon-remove.
//Read about event-delegation for dynamically created elements
//button is dynamically created here
$('.wrap').on('click','.glyphicon-remove',function(){
var ctrl=$(this).closest('.btn');
//get the parent of the clicked remove icon using closest
var ctrlClass=ctrl.attr('data-control');
//get its data-control attribute added during creation
$('.'+ctrlClass).val("").trigger('change');
//empty its value and trigger change
ctrl.remove();
//remove the control
})
JSFiddle DEMO

Related

How can I modify a list item after I created it with jQuery?

This is my todo list what I made.
(To make my code more readable I tried to comment. I hope it worked.)
If you try my demo, you can add li items with the "add" button. And the li items has 2 more buttons.
I want to create a modify button to users with can modifying their list items. I have no idea what I can to do for this with jQuery.
Second problem is that list buttons don't work perfectly well. Because if I use once a delete button it change the done button to delete an item. But if I dont use the delete button, the done button is working well.
I dont know why, maybe the same class name is the problem?
Here is my demo in JS Bin:https://jsbin.com/natiziqawa/edit?html,js,output
$(document).ready(function(){
$("#add").click(function(){
// Created list elements and their's buttons
var list_item =document.createElement("li");
var remove_button=document.createElement("button");
var done_button=document.createElement("button");
// append the buttons some string to caption buttons
$(remove_button).append("Delete");
$(done_button).append("Done");
// added class name the items to to distinguish them
$(list_item).addClass("item")
$(remove_button).addClass("delete");
$(done_button).addClass("done");
// filled the created items with the input values
var list_text =$("#input").val();
var time=$("#time").val();
// filled the list item with their's buttons and class names and input values
$(list_item).append(time," : ",list_text,done_button,remove_button);
// finally fill the ul with list items but first check out what is written in the input
if(input.value==""){
alert("Please enter an activity")
}
// If the input has some value can go
else{
$("ul").append(list_item);
// after clicked, clear the input field
$("#input").val("");
// list item's buttons
$(".done").click(function(){
$(list_item).click(function(){
$(this).css("color","white")
$(this).css("text-decoration","line-through")
});
});
$(".delete").click(function(){
$(list_item).click(function(){
$(this).remove()
});
});
}
});// main function close
}); // document ready close
The idea behind my solution is to use the contenteditable attribute for the added fields. To do this, you need to dynamically wrap the first two fields in an additional div, as shown here:
$(list_item).append('<div class="edit_item" contenteditable="true">'+time+'</div>'," : ",'<div class="edit_item" contenteditable="true">'+list_text+'</div>',done_button,remove_button);
You will need to replace this code with your existing one. For a better understanding, this code is located in the comment: "// filled the list item with their's buttons and class names and input values"
Also, you need to add this rule to the css to align the fields:
.edit_item {
display: inline-block;
}
And regarding the second question:
You had a targeting problem. You must refer to the current list_item using the closest() method.
For mark:
$(".done").click(function(){
$(this).closest(list_item).css("color","white")
$(this).closest(list_item).css("text-decoration","line-through");
});
For removing:
$(".delete").click(function(){
$(this).closest(list_item).remove();
});

Hide input after append(after)

I am trying to create input fields with button. But what I want is, when input field is created, I want hide created input field with the same button. I tried slideToggle function, but that didn't worked very well.
<button type="button" id="addEmail" "class1"></button>
$('#addEmail').one('click', function () {
var dummy = '<input type="text">';
$('.email').after(dummy); //creating input after class 'email'
$(this).addClass('less-inputs'); //Changing buttons css
});
The most concise way would be to create a jQuery context to represent your dummy element instead of a mere HTML string.
Something like:
var $dummy = $('<input type="text">');
$('.email').after($dummy);
$dummy.addClass('less-inputs');
Or even shorter:
$('<input type="text">')
.addClass('less-inputs')
.insertAfter($('.email'));
You can add the input within the HTML and simply show/hide it on button click.
If you want to create it dynamically you can add an ID to the input to check its existence. If the input exists you remove it, otherwise you add it.

Change tabindex dynamically in jquery

Imagine this simple layout ( http://jsfiddle.net/4F9cL/ ).
We have a table, for each row i have a label a textbox and a checkbox.
The first textbox has tabindex = 1 , the first checkbox has tabindex = 2, the next textbox on the second row has tabindex = 3 and so on.
What i would like to do is change the tabindex on the checkbox on the same row for the textbox that im in if the content of the textbox has changed.
For example at the moment im checking the checkbox on the row that the thebox content has been changed, i do that with the following code:
$("input:text").change(function () {
$(this).parents('tr:first').find('input:checkbox').prop('checked', 'checked');
So the scenario is the following: If the content of the textbox hasnt changed, when i tab i want the focus to change to the checkbox on the same row. If the content of the textbox HAS changed, i would like the focus to be on the next textbox on the row below INSTEAD of the checkbox on the same row.
I hope i explained it good enough for you to understand what im trying to do.
I've tried using .removeprop() and .removeattr() but that doesnt work and when next tab hits it just goes to the bottom of the page.
$("input:text").change(...);
The change event of a textbox will only be executed once the textbox loses focus. This means that when you press Tab, that function has not yet run, and you'll end up with your old tabindex target.
$("input:text").keyup(...);
$("input:text").keydown(...);
These events will fire when you either press down on (keydown), or release (keyup) a button while the textbox is focused.
Something like this should do the trick:
$("input:text").keyup(function() {
var textBox = $(this);
var textBoxIsEmpty = textBox.val().length == 0; //I assume you use this to determine which element should be the next to get focused when pressing tab.
var currentTabIndex = parseInt( textBox.attr("tabindex") );
var nextTarget = GetNextTarget(textBoxIsEmpty); //not sure how you define this. This is the item you want to be your next target when you press tab.
var nextTabIndex = currentTabIndex + 1;
nextTarget.attr("tabindex", nextTabIndex);
});
Although I am not 100% sure if changing the tabindex dynamically works in every browser.
I have tried like that and it's working fine for me.
before applying this you should clear on this you have declare you tabindex in the input properly.
jQuery("input:text").keyup(function() {
currentTabIndex = parseInt(jQuery(this).attr("tabindex") );
nextTabIndex = currentTabIndex + 1;
jQuery('input[tabindex='+nextTabIndex+']').select();
});

Action on clicking out of a form, inside a table

To start here is the fiddle with all the relevant code: http://jsfiddle.net/baruck/43787/
I'm building a webapp that at some point the user needs to register a number of items.
It is a big form, and this section of the form is inside a table.
Each input tag is inside a td followed by a span. When the user clicks to edit a certain row a script hides the span (that holds the value of the input) and shows up the input. When the user click on another row (or creates a new one) the script picks the value of the input add it/change the span text and hides the input and shows up the span.
When user clicks on some row, it first selects the row adding the 'editing' class to it, and the second click put the focus on the input.
While I'm clicking inside the table all goes well; the problem is when I click outside of the table that contains the inputs or hit tab after the last input on the active row. The focus go somewhere else...
When one of those two action happens I want to 'deactivate the row', meaning pick up the values from the inputs on that row, add/change them in the span, hide the input and show the span.
Summary: need to fire this function when clicking outside of the table with a class of 'editable' or when 'tab away' on the last input of row...
function deactivateRows() {
//Deactivate editing on the rows
$('table.editable tr.editing').removeClass('editing');
$('table.editable').find('td').not('.delete').each(function () {
$(this).find('input').each(function () {
var inputContent = $(this).val();
$(this).prop('disabled', true).addClass('hide').attr('value', inputContent);
$(this).parent().find('span').html(inputContent).removeClass('hide');
});
});
}
I think the trick will be to traverse up the DOM from a clicked element, or the related element of a blur event, and see if you hit table.editable. Something like this:
var isInsideEditable = function (el) {
return !!el && $(el).closest('table.editable').length > 0;
};
$('select, input, textarea', '.editable').on('blur', function (e) {
if (!isInsideEditable(e.relatedTarget))
deactivateRows();
});
$(window).on('click', function (e) {
if (!isInsideEditable(e.target))
deactivateRows();
return false;
});

HTML: Get value from input with no ID

Been looking around and I cant seem to find an answer to this so maybe im wording it wrong but here it goes.
So I have a table displaying data from a database. In jQuery I have made it so a row can be added with empty inputs and then submitted to the database, this works fine.
I am now attempting to be able to edit it. So each row will have a button to edit that row, the button will put the row values into inputs so you can change the value and update the database. How can I do this? I was looking into using this here but Im not sure how I can get the value of the input boxes without them having some sort of ID.
jQuery I was trying to use:
$('#tbl').on('click','.xx',function() {
$(this).siblings().each(
function(){
if ($(this).find('input').length){
$(this).text($(this).find('input').val());
}
else {
var t = $(this).text();
$(this).text('').append($('<input />',{'value' : t}).val(t));
}
});
});
Am I over thinking this? Should I just be grabbing the values and then putting them in pre-made input boxes?
Update:
HTML:
sb.AppendLine("<table style='width: 80%;'>")
sb.AppendLine("<tr class='inputRowbelow'>")
sb.AppendLine("<td style='width: 20%;' class='ui-widget-header ui-corner-all'>Area</td>")
sb.AppendLine("<td class='ui-widget-header ui-corner-all'>Details</td>")
sb.AppendLine("<td class='ui-widget-header ui-corner-all'>Options</td>")
sb.AppendLine("</tr>")
For Each w In workItems
sb.AppendLine("<tr>")
sb.AppendLine("<td>" & w.area & "</td>")
sb.AppendLine("<td>" & w.details & "</td>")
sb.AppendLine("<td><a href='#' class='fg-button ui-state-default ui-corner-all edit'><img src='/images/spacer.gif' class='ui-icon ui-icon-pencil' /></a></td>")
sb.AppendLine("</tr>")
Next
sb.AppendLine("</table>")
There are a couple of ways to do this, including changing your VB code to add extra data to the html, but I will answer this from a pure javascript/JQuery solution.
First of all you need to handle the click event for each edit button, after that you find the matching row, and then you can get the first to td elements of that row...
$(".edit").click(function(e){
e.preventDefault();//prevent the link from navigating the page
var button = $(this);//get the button element
var row = button.closest("tr");//get the row that the button belongs to
var cellArea = row.find("td:eq(0)");//get the first cell (area)
var cellDetails = row.find("td:eq(1)");//get the second cell (details)
//now you can change these to your inputs and process who you want
//something like this...
ConvertToInput(cellArea, "area");
ConvertToInput(cellDetails, "details");
});
function ConvertToInput(element, newId){
var input = $("<input/>");//create a new input element
input.attr("id", newId);//set an id so we can find it
var val = element.html();//get the current value of the cell
input.val(val);//set the input value to match the existing cell
element.html(input);//change the cell content to the new input element
}
Here is a working example
From that you can then do the saving that you say you have already implemented, using the ID values of each field to get the values to save.
Instead of using a For Each ... in ... Next loop, use a a For loop with a counter. give each button and each row an ID with the current counter value at the end. You can then use Jquery to make each row editable separately, because each row has a row number now.

Categories