How to replace text based on counter value? - javascript

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
}

Related

How to auto generate number in an input field?

I am creating a table with an auto numbering ID column. I want to be able to have my input text field to auto-generate an ID number(when the user starts typing into the name input field).
How do I auto-generate a number into an input field?
You could use the code below. What it does is every time you click the insert button, it adds a number to the id of the item (the number next to the text field).
This code uses document.getElementById() to modify all of the elements, and uses a variable num to incremement the id value. The part where it adds the item to the list is optional - I just added it to make it look more realistic.
var num = 1;
var input = document.getElementById('item');
var p = document.getElementById('number');
var list = document.getElementById('list');
var button = document.getElementById('insert');
button.addEventListener('click', function() {
num++;
p.innerHTML = num;
list.innerHTML += "<li>" + input.value + "</li>";
});
#item {
display: inline;
}
#number {
display: inline;
margin-right: 10px;
}
<p id='number'>1</p>
<input type='text' id='item' />
<button id='insert'>Insert</button>
<ul id='list'>
</ul>
If you have an HTML table, then you could respond to all edits, listening to the input event, and decide whether to fill a unique number (or wipe it out).
Here is a generic function you could call which takes as argument the table element that should have this feature, and the number of the column that should get these ID values.
Example:
function autoId(table, colNo) {
table.addEventListener("input", function(e) {
const tr = e.target.closest("tr");
const idInput = tr.cells[colNo].querySelector("input");
for (const input of tr.querySelectorAll("input")) {
hasData = input.value.trim() !== "" && input !== idInput;
if (hasData) break;
}
if (hasData && idInput.value.trim() === "") {
idInput.value = (Math.max(...Array.from(
table.querySelectorAll("td:nth-child(" + (colNo+1) + ") input"),
input => +input.value
).filter(v => !isNaN(v))) || 0) + 1;
} else if (!hasData && idInput.value.trim() !== "") {
idInput.value = "";
}
});
}
const table = document.querySelector("table");
// Call the function passing it the table and the column that has the ID -- that's all
autoId(table, 0);
// Let's give user the possibility to add rows, using the first data row as template
document.querySelector("#btnAddRow").addEventListener("click", () => {
table.insertAdjacentHTML("beforeend", table.rows[1].innerHTML);
});
<table>
<tr><th>ID</th><th>Name</th></tr>
<tr><td><input size="2"></td><td><input></td></tr>
</table>
<button id="btnAddRow">Add row</button>

Removing a particular element from an array causing an issue

I have an array where if i delete a specific element it will remove it but later if i again remove another element the newly selected element will be deleted but previously deleted element will be present as shown in fig.
refer above picture at first i removed phone from a array and next i removed Account Disabled but in the second table the previously deleted element phone is still present
var selectedOpts = $('#lstBox1 option:selected');
var text = selectedOpts.val();
var colData = [];
this.firmData.forEach(function (dta) {
colData.push(dta.DisplayName);
})
const removeItem = value => colData.filter(item => item !== value)
console.table(removeItem(text))
console.log(text);
UPDATE
actual requirement
my requirement is i need to move data viceversa while moving i also want to remove it from array for now i can only append those values but i am not able to remove it from an array
1st column html
<div class="menu">
<select multiple="multiple" id='lstBox1' >
</select>
</div>
1st column JS code
self.firmData.forEach(function (data) {
$("#lstBox1").append($('<option class="items">').text(data.DisplayName).attr('value', data.DisplayName));
});
2nd column HTMl
<div class="menu">
<select multiple="multiple" id='lstBox2' >
</select>
</div>
2nd column JS code
self.data.forEach(function (data) {
$("#lstBox2").append($('<option class="items">').text(data.columnsexpo).attr('value', data.columnsexpo));
});
Button functions
"click #btnRight": function(e){
var selectedOpts = $('#lstBox1 option:selected');
var text = selectedOpts.val();
$('#lstBox2').append($(selectedOpts).clone())
this.data.push(columnsexpo: text);
}
"click #btnLeft": function(e){
var selectedOpts = $('#lstBox2 option:selected');
var text = selectedOpts.val();
$('#lstBox1').append($(selectedOpts).clone())
this.data.push(columnsexpo: text);
}
Not sure from the question what you're trying to do, but this should remove the item you want from the original array. Warning - may contain bugs / errors, however Array.prototype.splice removes items from an array.
var selectedOpts = $('#lstBox1 option:selected');
var text = selectedOpts.val();
var colData = [];
this.firmData.forEach(function (dta) {
colData.push(dta.DisplayName);
})
function findItem(item) {
return item == text;
}
colData.splice(colData.findIndex(findItem), 1);
console.table(colData)
console.log(text);
.filter don't remove item from array
To remove item in your array you can do
colData.splice(colData.indexOf(text), 1)
Live demo
var colData = ['a', 'b', 'c', 'd'];
const removeItem = value => {
let arr = colData.splice(colData.indexOf(value), 1);
return arr;
}
removeItem('a');
removeItem('d');
console.log(colData);

Javascript - adding comma automatically to input field

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>

Filter/Search List box of Array Collection based on the user input text entered in the text area in Flex

I have a MXList Box having arrayCollection and I have another textarea box.
My requirement is: When users enter the desired text in the text area, I need to fetch and show the matching records from the List like:
___________
|____Ka___| Text area
__________
|Kanrna |List Box : ArrayCollection
|Kam |
|Kao |
|kaddsd |So it looks something like this
|_________|
I have tried with various approaches:
<mx:List id="availableProfileList"
dataProvider="{campaignProxy.campaignWizardVo.currentProfiles}""/>
<mx:TextArea id="textSearch" textInput="applyFilter()"/>
protected function applyFilter():void{
campaignProxy.campaignWizardVo.currentProfiles.filterFunction = matchingFunction(campaignProxy.campaignWizardVo.currentProfiles, textSearch.text);
//Alert.show(textSearch.text)
//availableProfileList.findString(textSearch.text);
//availableProfileList.setFocus();
}
public function matchingFunction(availableProfileList:List, text:String):Vector.<int> {
var results:Vector.<int> = new Vector.<int>;
var item:String;
var entered:String = text.toLowerCase();
var itemIdx:int;
Alert.show("before for");
for(var idx:int = 0; idx < availableProfileList.dataProvider.length; idx++) {
item = availableProfileList.dataProvider.getItemAt(idx) as String;
item = item.toLowerCase();
itemIdx = item.indexOf(entered);
if(item.indexOf(entered) > -1) {
results.push(idx);
}
}
return results;
}
After checking these questions:
combobox which filters dataprovider based on user input
and:
Flex - Search/Filter DataGrid by Text Input
I still don't understand how to make it work.
<mx:TextInput id="textSearch" maxChars="30" width="230" height="20.004135" change="applyFilter()" enabled = "true"
/>
protected function applyFilter():void{
(availableProfileList.dataProvider as ArrayCollection).filterFunction = filterFunc;
(availableProfileList.dataProvider as ArrayCollection).refresh();
}
public function filterFunc(item:Object):Boolean{
var searchedStr:String = textSearch.text;
var profile:ProfileVO = item as ProfileVO;
if (searchedStr == null) {
return (availableProfileList.dataProvider as ArrayCollection).refresh();
}
else {
return profile.profileName.toLowerCase().indexOf(searchedStr.toLowerCase()) == 0;
}
}
The filterFunction is a property of your ArrayCollection which should be set only once. Then.
<mx:List id="availableProfileList"
dataProvider="{campaignProxy.campaignWizardVo.currentProfiles}""/>
<mx:TextArea id="textSearch" textInput="{campaignProxy.campaignWizardVo.currentProfiles.refresh();}"/>
The filterFunction must accept one argument that is supposed to be a collection item and return true if the item should be visible and false otherwise. The refresh method on data provider forces the filtering to happen.
function filterList(item:Object):Boolean
{
// Returns true if item label (or title, or name, I don't remember)
// starts with the text in the input area, case insensitive.
return item.label.toLowerCase.indexOf(textSearch.text.toLowerCase()) == 0;
}
DISCLAMER: This all above is a guideline, not a complete solution, please figure details on your own.

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