Javascript - adding comma automatically to input field - javascript

I will post the part of a function that is adding numbers that are clicked into selected input field.
So, I need to separate it with a comma (,). I tried some of the examples but it seems not to be working on the function that I wrote.
var rowRange = 'abcdefghijklmnopqrstuvwxyz'.split('');
var $cart = $('#seats'),
$counter = $('#counter'),
sc = $('#seat-map').seatCharts({
map: [
'aaaaa__aaaaa',
'aaaaa__aaaaa'
],
naming : {
top : false,
getLabel : function (character, row, column) {
return rowRange[row - 1].toUpperCase() + column;
},
},
click: function () {
if (this.status() === 'available') {
$('#seats').split(",")
.attr('id', 'cart-item-'+this.settings.id)
.val(this.settings.label)
.appendTo($cart);
$counter.text(sc.find('selected').length+1);
return 'selected';
});
});
Seat is a input field where comma needs to be added after every click on any number.
.split(",")
when I remove this part the code works like it should, but without adding comma.

.split() doesn't work on jquery objects. Instead use it on the values in your select.
Here is an example on how it could work.
$selected = $('#selected');
$(".seat").on("click", function() {
const cur = $selected.val();
const valToInsert = $(this).text();
$selected.val(cur.length === 0 ? valToInsert : cur.split(',').concat(valToInsert).join(','));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="selected">
<button class="seat">a</button>

Related

Tail Select using Check box

I want to perform multiple tail select using checkbox than a dropdown , i checked a code ,but i was not able to convert it to checkbox , Can anyone help me .
var projects = tail.select("select.projects", {
deselect: true,
multiContainer: ".projects-selected",
multiple: true,
});
projects.config("multiple", false, true);
projects.on('change', changeFirst);
let tests = tail.select("select.tests", {
multiContainer: ".tests-selected",
disabled: true
});
function getData() {
var size = Math.floor(Math.random() * 6) + 5;
var randomEntry = function() {
var tmp = CryptoJS.MD5(Math.floor(Math.random() * 1000).toString()).toString();
console.log(tmp);
return {
id: 'ID_' + tmp,
name: tmp
};
};
return Array.from({
length: size
}, randomEntry);
}
function changeFirst(opt, event) {
if (event == 'select') {
let data = getData();
let items = {};
data.forEach(function(entry) {
items[entry.id] = entry.name
});
tests.config('items', items);
tests.config('disabled', false);
} else if (event == 'unselect') {
tests.config('disabled', true);
tests.config('items', {});
}
}
<div class="left">
<select class="projects">
<option>Project 1</option>
<option>Project 2</option>
</select>
</div>
<div class="right">
<span class="projects-selected"></span>
<span class="tests-selected"></span>
</div>
i tried editing this code , but am not getting what i wanted , so can anyone help me to sort it out .
Output should be something like this :
so when we click on the span generated it should unselect . , but whatever try to provide checkbox is not working
NOTE :
tail. select is a rewritten version of the jQuery tail. select plugin that can be used to beautify & enhance the default select box with no dependency
https://www.cssscript.com/single-multiple-select-tail/#:~:text=Description%3A,select%20box%20with%20no%20dependency.
I don't know whether this can be done using tail.select , If not possible , can anyone suggest any other way to do this .

How could i remove specific value from jquery array in jquery

I would like to remove specific value from an array , I have tried following script for delete value from an array but that not working.
HTML that contain values of an array
<input type="hidden" class="image_array" id="image_array" name="image_array[]" value="20200207050212.jpg,20200207050214.jpg">
So my array value is 20200207050212.jpg,20200207050214.jpg & I would like to remove 20200207050212.jpg from this array but not remove when i used following script.
1 Way
$(document).ready(function(){
$(document).on("click", '.profile_delete_image', function(){
var getImageName = $(this).attr('data-imagename');
console.log(getImageName)
var getImageArray =$('.image_array').val();
var checkValueExist = (getImageArray.indexOf(getImageName) > -1);
if(checkValueExist == true){
var itemtoRemove = getImageName;
getImageArray = $.grep(getImageArray, function(value) {
return value != itemtoRemove;
console.log(getImageArray)
});
}
});
})
2 Way
$(document).ready(function(){
$(document).on("click", '.profile_delete_image', function(){
var getImageName = $(this).attr('data-imagename');
console.log(getImageName)
var getImageArray =$('.image_array').val();
var checkValueExist = (getImageArray.indexOf(getImageName) > -1);
if(checkValueExist == true){
var itemtoRemove = getImageName;
getImageArray.splice(1,1);
}
});
})
NOte: when i do console.log it's return separated value like
2
0
2
0
0
2
0
7
0
5
0
2
1
2
j
p
g
So I don't want this i only want to remove given value from array and return an array with removed value.
Just use split() to make string as array.
var getImageName = '20200207050212.jpg' // Get your delete image name.
var getImageArray = [];
getImageArray = $('.image_array').val().split(',');
getImageArray = getImageArray.filter(e => e !== getImageName);
console.log(getImageArray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" class="image_array" id="image_array" name="image_array[]" value="20200207050212.jpg,20200207050214.jpg">
Take a look at the snippet,
This is a simple example, here we have an array of images, when the button is clicked, it will get the images to delete from image_array.
Checks for if images_array has value, and convert it to array using .split(). Then iterate through the array and delete if the value in images array matched.
var $ = jQuery;
var images = ['20200207050212.jpg', '20200207050214.jpg', 'abc.jpg', 'image_123123.jpg'];
$('#delete_image').on('click', function() {
console.log('before delete', images);
var image_arr = $('#image_array').val();
image_arr = image_arr ? image_arr.split(',') : image_arr;
if (image_arr.length) {
image_arr.forEach(function(img) {
if (images.indexOf(img) !== -1) images.splice(images.indexOf(img), 1)
})
console.log('after delete', images);
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<input type="hidden" class="image_array" id="image_array" name="image_array[]" value="20200207050212.jpg,20200207050214.jpg">
<button id="delete_image">Delete Image </button>

Filtering an exact of string in DataTable JQuery

How do I search for an exact match in the search bar of JQuery Datable I tried using fnFilter but it's still not returning an exact match.
$(document).ready(function() {
var oTable = $('#datacal_table').DataTable({"order": [[4, "asc"]]});
oTable.fnFilter("^"+$(this).val()+"$", 4, true);
});
For example I only watch to search 'active' but what happens is the 'inactive' words also returns in the result. What should I do I need to be able to search only the the exact string.
EDIT
I tried one of inuka's links How to search for an exact string in a jQuery DataTable?
and it seems like my text class is interfering with the search, how do I get around this? I want to keep using my class text so that it's colored.
<td id="status">
<span class = "label {{ getStatusColor($data->status) }}"
id = "status_{{ $data->id }}">
{{ getStatusText($data->status) }}
</span>
</td>
when I only retain {{getStatusText}} the search works but when I try to class it, it doesn't.
<script type="text/javascript">
$(document).ready(function() {
var table = $('#datacal_table').DataTable({
"order": [[4, "asc"]]
});
$('.dataTables_filter input', table.table().container())
.off('.DT')
.on('keyup.DT cut.DT paste.DT input.DT search.DT', function(e) {
var term = $.trim(this.value);
if (term !== ""){
var termRegExp = new RegExp('^' + $.fn.dataTable.util.escapeRegex(term) + '$', 'i');
$.fn.dataTable.ext.search.push(
function (settings, data, dataIndex){
var isFound = false;
$.each(data, function (index, value) {
if (termRegExp.test(value)){ isFound = true; }
return !isFound;
});
return isFound;
}
);
}
table.draw();
if (term !== "") {
$.fn.dataTable.ext.search.pop();
}
});
});
</script>
The following answer from this post will give you an answer for searching term inside your HTML table structure.
$('#datacal_table').DataTable({
"columnDefs": [{
"targets": [4],
"render": function ( data, type, full, meta ) {
if(type === 'filter'){
return $('#datacal_table').DataTable().cell(meta.row, meta.col).nodes().to$().find('span').text();
} else {
return data;
}
}
}]
});
According to Datatables documentation this columnDefs.targets will give you the option to match only specified column name values. "targets": [4] will only focus on values under your Status column.
try this code
var oTable = $('.datatable').DataTable();
$('.dataTables_filter input').keyup( function () {
oTable.fnFilter("^"+$(this).val(),0,true,false);
});
working link http://codepen.io/subbu1191/pen/GmrvNd
1.{string}: String to filter the table on
2.{int|null}: Column to limit filtering to
3.{bool} [default=false]: Treat as regular expression or not
4.{bool} [default=true]: Perform smart filtering or not
5.{bool} [default=true]: Show the input global filter in it's input box(es)
6.{bool} [default=true]: Do case-insensitive matching (true) or not (false)
you have to make the smart filtering false in order to get the regex working

How to replace text based on counter value?

Call to the count function made by two group of checkboxes. First group represents categories, when clicked subjects for that category will be listed out.
html: id: counter displays count value. id: select replaces text acordingly
<div class="small-8 text-left columns" style="left:-30px;">
<span id="counter"><span id="count">0</span></span>
<span id="select">Select Subjects</span>
</div>
script:(categories group) To pass value for the subjects to be fetched by ajax. updateCount();is the count function call.
$("input[type=checkbox][id^=level]").change(function() {
var selectedval = $(this).val();
if($(this).is(":checked")) {
var selectedtext = $(this).next().text();
sendtobox(selectedval, $("#slider1").val(),"regis");
} else {
$("th."+selectedval).remove();
updateCount();
}
});
(subjects group)
$(document).on('change', '[id^=sub][type=checkbox]', updateCount);
count function:
function updateCount () {
$('#count').text($('[id^=sub][type=checkbox]:checked').length);
}
script to replace text:
$(".close-reveal-modal").on("click",function()
{
document.getElementById("select").innerHTML = "Select subject";
var str = document.getElementById("select").innerHTML;
var res = str.replace("Select subject", "Selected Subject");
document.getElementById("select").innerHTML = res;
});
Now I can replace text and the count works just fine! My problem is it doesn't obey the English grammar!
If 0 item/subjects returned, the text should be 0 Selected Subjects and if more than 1 is checked, it should say the same. See the (s) must be added in 'subject' word.
My problem is , I couldn't identify number of counts to replace this text.
I want someting like this:
if ($("#count") >1 || ($("#count")==0))
{
var res = str.replace("Select subject", "**Selected Subjects"**);
document.getElementById("select").innerHTML = res;
}
else
{
var res = str.replace("Select subject", "**Selected Subject"**);
document.getElementById("select").innerHTML = res;
}
I tried to alert $('#count').length , it red like this each time the checkbox checked:
1 1 1 1
What I'm expecting is
1 -when clicked once
2 - when clicked twice
This way would be easier for me to replace text indeed!
it sounds like you want the TEXT of the span with id 'count' for that comparison:
if ($("#count").text() == "1") {
// singular
}
else {
// plural
}

In Jquery take a different values from single text box id

I am using Data Table in jquery. So i passed one input type text box and passed the single id. This data table will take a multiple text box. i will enter values manually and pass it into the controller. I want to take one or more text box values as an array..
The following image is the exact view of my data table.
I have marked red color in one place. the three text boxes are in same id but different values. how to bind that?
function UpdateAmount() {debugger;
var id = "";
var count = 0;
$("input:checkbox[name=che]:checked").each(function () {
if (count == 0) {
id = $(this).val();
var amount= $('#Amount').val();
}
else {
id += "," + $(this).val();
amount+="," + $(this).val(); // if i give this i am getting the first text box value only.
}
count = count + 1;
});
if (count == 0) {
alert("Please select atleast one record to update");
return false;
}
Really stuck to find out the solution... I want to get the all text box values ?
An Id can only be used once; use a class, then when you reference the class(es), you can loop through them.
<input class="getValues" />
<input class="getValues" />
<input class="getValues" />
Then, reference as ...
$(".getValues")
Loop through as ...
var allValues = [];
var obs = $(".getValues");
for (var i=0,len=obs.length; i<len; i++) {
allValues.push($(obs[i]).val());
}
... and you now have an array of the values.
You could also use the jQuery .each functionality.
var allValues = [];
var obs = $(".getValues");
obs.each(function(index, value) {
allValues.push(value);
}
So, the fundamental rule is that you must not have duplicate IDs. Hence, use classes. So, in your example, replace the IDs of those text boxes with classes, something like:
<input class="amount" type="text" />
Then, try the below code.
function UpdateAmount() {
debugger;
var amount = [];
$("input:checkbox[name=che]:checked").each(function () {
var $row = $(this).closest("tr");
var inputVal = $row.find(".amount").val();
amount.push(inputVal);
});
console.log (amount); // an array of values
console.log (amount.join(", ")); // a comma separated string of values
if (!amount.length) {
alert("Please select atleast one record to update");
return false;
}
}
See if that works and I will then add some details as to what the code does.
First if you have all the textbox in a div then you get all the textbox value using children function like this
function GetTextBoxValueOne() {
$("#divAllTextBox").children("input:text").each(function () {
alert($(this).val());
});
}
Now another way is you can give a class name to those textboxes which value you need and get that control with class name like this,
function GetTextBoxValueTwo() {
$(".text-box").each(function () {
alert($(this).val());
});
}

Categories

Resources