daulat daulat - 17 days ago 5
CSS Question

How to delete any date separated by comma in input fields

I want to delete Any date from dates string separated by comma in input field.

I'm able to delete last date but what if i want to delete any date form middle position

For example

Delete last date from input field it's working fine.

Now Try to delete first,second,third date it's from input field it's not working.enter image description here

External link to jQuery ui css file

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">


Input field

<input type="text" style="width:100%" id="dates" value="2016-11-16,2016-11-17,2016-11-18,2016-11-19,2016-11-26
">


External link to js files

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>


Working js code

<script>
jQuery(document).ready(function($) {
// Input field selector on key up event
$('#dates').keyup(function(e) {
if(e.keyCode == 8 || e.keyCode == 46) {
// Split string into array
var datesString=$(this).val().split(",");
// Create Empty Array
dates=[];
// Remove last element from array
for(var i=0 ; i<datesString.length-1;i++){
dates.push(datesString[i]);
}
// Set dates In input field
$(this).val(dates);
// after adding dates in input field add focus
$(this).focus();

}
});
});
</script>


Working example in

jsfiddle

jsfiddle full working functionality

Answer

If I understand correctly you want to delete from input dates in the middle depends of cursor position ?

In that case plain input it's bad choice. People won't know whether to click backspace before or after comma inside input.

In this case plugins like Tag-it will work the best.

@Edit ---

I don't know why I did it for you, but here you have my reproduce. https://jsfiddle.net/fd1034rn/5/

I need just few lines of code.

$(document).ready(function() {
        $("#myTags").tagit({
            fieldName: "date",
            singleField: true
        });

        $('#myTags input:eq(0)').datetimepicker();

        //tests
        setInterval(function(){
            $("#val").text($('#myTags').tagit('assignedTags'));
        },200);
 });

It's almost finished, you will have to refine this a bit.

Comments