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>
Related
I can't copy value from textarea in the first click.
im working with Popup Box.
i think the problem is im hidding the .footer-result-box for textarea.
im using code like this :
HTML :
<div id="popup-box">
<div class="footer-result-box" style="height:0px">
<textarea id="final-interest"></textarea> //textarea
</div>
<button class="btn-copy-all"> COPY </button> //copy button
</div>
jQuery :
$(".btn-copy-all").click(function() {
//im use this code for get value from table when row selected.
if (states.activeScreen == "interest") {
var datas = new_tabel_interest.rows(".selected").data();
}
if (states.activeScreen == "related") {
var datas = new_tabel_page_interest.rows(".selected").data();
}
res = "";
for (i = 0; i < datas.length; i++) {
if (res != "") res += ",";
res += datas[i][2];
}
//EXECUTE
$("#final-interest").val(res); //texarea get value from selected row
$(".footer-result-box").animate({
height: "205px"
}); //display box
$("#final-interest").select(); //select textarea value
document.execCommand('copy'); //copy the result
$("#popup-box").css({
display: "none"
}); //close popup-box
alert("Copied!");
});
The code running well, but the result not copied.
My Goal :
Success copy textarea value then close the #popup-box.
Textarea Value will get DATA from Table when im select the row table.
I have a simple form: https://jsfiddle.net/skootsa/8j0ycvsp/6/
<div class='field'>
<input placeholder='Nickname' type='text'>
</div>
<div class='field'>
<input placeholder='Age' type='text'>
</div>
How would I get a button that copied the contents of each input box + the "placeholder" attribute (or class name)? So that the clipboard results looked like this:
Nickname: Johnnyboy
Age: 22
You need to:
create an invisible element to copy the data
get the data from your form and set it to the previous element
select it
call document.execCommand('copy') to copy the selected text to the
clipboard
I have updated your fiddle, check it out https://jsfiddle.net/8j0ycvsp/9/
In case you want the code
function copyToClipboard() {
/*get inputs from form */
var inputs = document.querySelectorAll("#the-form input[type=text]");
/*do a copy of placeholder and contents*/
var clipboardText = ''
for (var i = 0, input; input = inputs[i++];) {
clipboardText += input.placeholder+': '+(input.value ? input.value : '' )+'\n';
}
/*create hidden textarea with the content and select it*/
var clipboard = document.createElement("textarea");
clipboard.style.height = 0;
clipboard.style.width = 0;
clipboard.value = clipboardText;
document.body.appendChild(clipboard);
clipboard.select();
console.log(clipboard.value);
/*do a copy fren*/
try {
if(document.execCommand('copy'))
console.log('Much succes, wow!');
else
console.log('Very fail, wow!');
} catch (err) {
console.log('Heckin concern, unable to copy');
}
}
So give it a try
var input = document.querySelectorAll('.field input');
document.getElementById('submit').addEventListener('click', function () {
var innerHTMLText = "";
for (var i = 0; i < input.length; i++) {
innerHTMLText += input[i].placeholder + ':' + input[i].value + ' ';
}
console.log(innerHTMLText);
document.getElementsByClassName('bix')[0].innerHTML = innerHTMLText;
});
I am trying to take a user input value that is entered through an html input box, and have it as a value within my function (the negKeyword function in my code to be more specific). The problem that I think is happening is this input value is stored as a variable, so when the code is first stored in memory it is stored as "", since the user has not inputed anything yet. How do I get it so when the user inputs something it replaces blank or "" with what ever the user inputs?
What I basically want to happen next is the user will click a button, it will then compare what the user inputs to what the "negKeyword" function outputs and give a result on whether they match or not (this action is demonstrated in my booleanKeyword function in my code).
Here is my code.
var input = document.getElementById("input").value;
var arr = ['no', 'not', 'checked'];
var text = ''; //JS output variable.
var keyword = 'leak'; //Individual keyword.
function negKeyword() {
for (i = 0; i < arr.length; i++) {
if (text == input) { break; }
text = arr[i] + ' ' + keyword;
}
return text;
}
function booleanKeyword() {
if (input == negKeyword()) {
document.getElementById("result").style.color="green";
document.getElementById("result").innerHTML="Match";
} else {
document.getElementById("result").style.color="red";
document.getElementById("result").innerHTML="No Match";
}
}
document.getElementById("result2").innerHTML=keyword;
<label for="Full Negative Keyword">Negative Keyword</label> <input id="input" type="text" />
<div id="message">Result: <span id="result"></span></div>
<div id="message">Keyword: <span id="result2"></span></div>
<button id="test" onclick="booleanKeyword()">Click to Test</button>
You can retrieve the input's value again, by getting it and assigning to the same variable (but inside the function that is called after the button click).
var input = document.getElementById("input").value;
var arr = ['no', 'not', 'checked'];
var text = ''; //JS output variable.
var keyword = 'leak'; //Individual keyword.
function negKeyword() {
input = document.getElementById("input").value;
for (i = 0; i < arr.length; i++) {
if (text == input) { break; }
text = arr[i] + ' ' + keyword;
}
return text;
}
function booleanKeyword() {
input = document.getElementById("input").value;//The variable is reassigned, only after the click
if (input == negKeyword()) {
document.getElementById("result").style.color="green";
document.getElementById("result").innerHTML="Match";
} else {
document.getElementById("result").style.color="red";
document.getElementById("result").innerHTML="No Match";
}
}
document.getElementById("result2").innerHTML=keyword;
Edit: added the same code to negKeyword() function as it requires the input too.
It is not working because your variable input is always "". You have to assign new value to it each time the button is clicked. I just moved your code for input in BooleanKeyword() function. Now everything is working fine.
Everytime when something like this is not working, just try to log/alert values.
For example you could just alert(input + ' ' + negKeyword()); on top of booleanKeyword() function and you would see problem by yourself.
var input;
var arr = ['no', 'not', 'checked'];
var text = ''; //JS output variable.
var keyword = 'leak'; //Individual keyword.
function negKeyword() {
for (i = 0; i < arr.length; i++) {
if (text == input) { break; }
text = arr[i] + ' ' + keyword;
}
return text;
}
function booleanKeyword() {
input = document.getElementById("input").value;
if (input == negKeyword()) {
document.getElementById("result").style.color="green";
document.getElementById("result").innerHTML="Match";
} else {
document.getElementById("result").style.color="red";
document.getElementById("result").innerHTML="No Match";
}
}
document.getElementById("result2").innerHTML=keyword;
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<label for="Full Negative Keyword">Negative Keyword</label> <input id="input" type="text" />
<div id="message">Result: <span id="result"></span></div>
<div id="message">Keyword: <span id="result2"></span></div>
<button id="test" onclick="booleanKeyword()">Click to Test</button>
</html>
Am struggling hard to bind an array object with list of span values using watcher in Angularjs.
It is partially working, when i input span elements, an array automatically gets created for each span and when I remove any span element -> respective row from the existing array gets deleted and all the other rows gets realigned correctly(without disturbing the value and name).
The problem is when I remove a span element and reenter it using my input text, it is not getting added to my array. So, after removing one span element, and enter any new element - these new values are not getting appended to my array.
DemoCode fiddle link
What am I missing in my code?
How can I get reinserted spans to be appended to the existing array object without disturbing the values of leftover rows (name and values of array)?
Please note that values will get changed any time as per a chart.
This is the code am using:
<script>
function rdCtrl($scope) {
$scope.dataset_v1 = {};
$scope.dataset_wc = {};
$scope.$watch('dataset_wc', function (newVal) {
//alert('columns changed :: ' + JSON.stringify($scope.dataset_wc, null, 2));
$('#status').html(JSON.stringify($scope.dataset_wc));
}, true);
$(function () {
$('#tags input').on('focusout', function () {
var txt = this.value.replace(/[^a-zA-Z0-9\+\-\.\#]/g, ''); // allowed characters
if (txt) {
//alert(txt);
$(this).before('<span class="tag">' + txt.toLowerCase() + '</span>');
var div = $("#tags");
var spans = div.find("span");
spans.each(function (i, elem) { // loop over each spans
$scope.dataset_v1["d" + i] = { // add the key for each object results in "d0, d1..n"
id: i, // gives the id as "0,1,2.....n"
name: $(elem).text(), // push the text of the span in the loop
value: 3
}
});
$("#assign").click();
}
this.value = "";
}).on('keyup', function (e) {
// if: comma,enter (delimit more keyCodes with | pipe)
if (/(188|13)/.test(e.which)) $(this).focusout();
if ($('#tags span').length == 7) {
document.getElementById('inptags').style.display = 'none';
}
});
$('#tags').on('click', '.tag', function () {
var tagrm = this.innerHTML;
sk1 = $scope.dataset_wc;
removeparent(sk1);
filter($scope.dataset_v1, tagrm, 0);
$(this).remove();
document.getElementById('inptags').style.display = 'block';
$("#assign").click();
});
});
$scope.assign = function () {
$scope.dataset_wc = $scope.dataset_v1;
};
function filter(arr, m, i) {
if (i < arr.length) {
if (arr[i].name === m) {
arr.splice(i, 1);
arr.forEach(function (val, index) {
val.id = index
});
return arr
} else {
return filter(arr, m, i + 1)
}
} else {
return m + " not found in array"
}
}
function removeparent(d1)
{
dataset = d1;
d_sk = [];
Object.keys(dataset).forEach(function (key) {
// Get the value from the object
var value = dataset[key].value;
d_sk.push(dataset[key]);
});
$scope.dataset_v1 = d_sk;
}
}
</script>
Am giving another try, checking my luck on SO... I tried using another object to track the data while appending, but found difficult.
You should be using the scope as a way to bridge the full array and the tags. use ng-repeat to show the tags, and use the input model to push it into the main array that's showing the tags. I got it started for you here: http://jsfiddle.net/d5ah88mh/9/
function rdCtrl($scope){
$scope.dataset = [];
$scope.inputVal = "";
$scope.removeData = function(index){
$scope.dataset.splice(index, 1);
redoIndexes($scope.dataset);
}
$scope.addToData = function(){
$scope.dataset.push(
{"id": $scope.dataset.length+1,
"name": $scope.inputVal,
"value": 3}
);
$scope.inputVal = "";
redoIndexes($scope.dataset);
}
function redoIndexes(dataset){
for(i=0; i<dataset.length; i++){
$scope.dataset[i].id = i;
}
}
}
<div ng-app>
<div ng-controller="rdCtrl">
<div id="tags" style="border:none;width:370px;margin-left:300px;">
<span class="tag" style="padding:10px;background-color:#808080;margin-left:10px;margin-right:10px;" ng-repeat="data in dataset" id="4" ng-click="removeData($index)">{{data.name}}</span>
<div>
<input type="text" style="margin-left:-5px;" id="inptags" value="" placeholder="Add ur 5 main categories (enter ,)" ng-model="inputVal" />
<button type="submit" ng-click="addToData()">Submit</button>
<img src="../../../static/app/img/accept.png" ng-click="assign()" id="assign" style="cursor:pointer;display:none" />
</div>
</div>
<div id="status" style="margin-top:100px;"></div>
</div>
</div>
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());
});
}