How to fetch the input elements value by class name in jquery - javascript

I want to fetch input elements value, they have class "features". I can access all of them
alert($('.features').length);
Correct me if I am wrong, $('.features') is an array of html input elements.But I tried
Array.isArray($('.features')) // returned false
I want to access the value of each element . How to achieve this
I tried to do one and below is the code snippet
function maintest() {
for(i = 0 ; i < 5 ; i ++ ) {
$("<input>").attr({"class":"features"}).appendTo("#mainDiv").val("input"+i);
$("<br/><br/>").appendTo("#mainDiv");
}
$("<button> Click me! </button>").click(function() {
let inputArray = [];
inputArray = $('.features');
alert(inputArray.length);
//alert( inputArray[0].val());
//what must be put here to see the data value
}).appendTo("#mainDiv");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<body onload="maintest()">
<div id="mainDiv"></div>
</body>

In javascript, setting a variable to a value overwrites the previous value. It doesn't enforce the type, so these lines:
let inputArray = [];
inputArray = $('.features');
is the same as
let inputArray = $('.features');
$() returns a jquery collection, not a javascript array; there are, of course, similarities, but it's not an "array".
To get the values out you can loop through the collection or you can use .map to extract values, eg:
var valuesArray = $('.features').map(function() {
return $(this).val();
}).toArray();
function maintest() {
for (i = 0; i < 5; i++) {
$("<input>").attr({ "class": "features" })
.appendTo("#mainDiv")
.val("input" + i);
$("<br/><br/>").appendTo("#mainDiv");
}
$("<button> Click me! </button>").click(function() {
let inputArray = $('.features');
var values = inputArray.map(function() {
return $(this).val();
}).toArray();
console.log(values);
}).appendTo("#mainDiv");
}
$(() => maintest());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="mainDiv"></div>

You could loop over the input array using jQuery $.each method.
Example:
function maintest() {
for (i = 0; i < 5; i++) {
$("<input>")
.attr({ class: "features" })
.appendTo("#mainDiv")
.val("input" + i);
$("<br/><br/>").appendTo("#mainDiv");
}
$("<button> Click me! </button>")
.click(function() {
let inputArray = [];
inputArray = $(".features");
$.each(inputArray, function(index, input) {
console.log(input.value);
});
})
.appendTo("#mainDiv");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body onload="maintest()">
<div id="mainDiv"></div>
</body>

Related

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>

How to get element by name with $key

PHP
//Here is my html for qty
<p>Qty : <input type="number" value="" name="qty<?php echo $key ?> onChange="findTotal()"/>
JS function
function findTotal() {
var arr = document.getElementsByName('qty');
...
document.getElementById('result').value = decimalPlaces(tot, 2);
}
My qty name needs key for post array. How do I get name inside js function to calculate quantities?
You can use
document.querySelector("input['name^='qty']").value
if you don't have jQuery.
This will select an input with name attribute starting with "qty". If you have multiple inputs which match the criteria you can select them all using
document.querySelectorAll("input[name^='qty']")
which will return a NodeList. You can read more about this here.
You can do something like this
var myVar = document.getElementsByTagName("somename");
//do something else
If you are using jquery
value = $( "input[name^='qtd']" ).val();
//it will pick the input wich name starts with 'qtd'
In pure DOM, you could use getElementsByTagName to grab all input elements, and loop through the resulting array. Elements with name starting with 'qty' get pushed to another array:
var eles = [];
var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].name.indexOf('qty') == 0) {
eles.push(inputs[i]);
}
}
Don't query the element by the name attribute's value. I'm not sure what's the purpose of the key and why you need it in the findTotal method, but here's an example:
<p>Qty : <input type="number" value="" name="qtyMyKey" onChange="findTotal(event)" /></p>
<script>
function findTotal(e) {
var inputEl = e.target,
inputName = inputEl.getAttribute('name'),
myKey;
if (typeof inputName === 'string') {
myKey = inputName.replace('qty', '');
}
console.log(myKey);
//var arr = document.getElementsByName('qty');
//document.getElementById('result').value = decimalPlaces(inputEl.value(), 2);
}
</script>
Here's the jsFiddle demo.

Couldn't append span element to array object in Angularjs/Jquery

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>

Javascript Arrays and variable click functions

So I have set up two javascript arrays to pull information from some php. One array gets the name of the category to be clicked on, while the other array stores the class and id tag for the category. The class and id tags are the same other than there css type, but the array needs to output them into document elements and then, when clicked, affect the relevant areas of the document. I also need to remove duplicates from the arrays, which doesn't seem to work under my current code:
<script type="text/javascript">
var BookSeries = [];
var BookClass = [];
var i=0;
</script>
then variables for the array are pulled from php and output this way:
<script type="text/javascript">
var uniqueSeries = BookSeries.filter(function(elem, pos) {
return BookSeries.indexOf(elem) == pos;
});
var uniqueClass = BookClass.filter(function(elem, pos) {
return BookClass.indexOf(elem) == pos;
});
while (uniqueSeries[i]) {
document.write( "<span id='"+uniqueClass[i]+"'>"+uniqueSeries[i]+"</span>" );
i++;
}
for(var i = 0; i < uniqueClass.length; i++) {
$np("#"+uniqueClass[i]).click(function(){
$np(".postitem").fadeOut(200);
$np("."+uniqueClass[i]).fadeIn(200);
});
}
</script>
You are using jquery so you can do the following for appending the elements to the DOM:
var htmlString = "";
for (var i = 0; i < uniqueSeries.length; i++) {
htmlString += "<span id='"+uniqueClass[i]+"'>"+uniqueSeries[i]+"</span>";
}
$("#myContainer").html(htmlString);
Not sure what is $np so I'll assume you meant jquery's $.
for(var i = 0; i < uniqueClass.length; i++) {
var uClass = uniqueClass[i];
$("#" + uClass).click(function(){
$(".postitem").fadeOut(200);
$("." + uClass).fadeIn(200);
});
}
Edit:
"#myContainer" refers to the id of the dom element you want to append the html to. if you just want to append it to document you can do:
$(document).appendTo(htmlString);
Also see I updated the code above to reflect your comments about the uniqueClass array.

Multiple checkbox can't access from JavaScript function

I have dynamic multiple check boxes which is used to restore multiple files. It works perfectly when I have more than 1 check boxes. Here is my php code for check boxes:
<form name="RestoreFile">
<input type="checkbox" title="'.$FldDoc['FldDocumentName'].'" name="restore_checkbox" value="'.$FldDoc['FldDocumentID'].'" id="restore_'.$NodeId.'_'.$FldDoc['FldDocumentID'].'"/>
<input type="button" value="Restore" onclick="RestoreDocFile(\''.$NodeId.'\',this.form.restore_checkbox);" />
</form>
And the definition of function RestoreDocFile() is given below:
function getSelected(opt)
{
var selected = new Array();
var index = 0;
for (var intLoop = 0; intLoop < opt.length; intLoop++) {
if (opt[intLoop].checked)
{
index = selected.length;
selected[index] = new Object;
selected[index].value = opt[intLoop].value;
selected[index].index = intLoop;
}
}
return selected;
}
function RestoreDocFile(nodeid, opt)
{
var getSelectDocIds = getSelected(opt);
//alert(nodeid+','+getSelectDocIds);
var strSelectedDocIds = "";
var i=0;
for (var item in getSelectDocIds)
{
if(i!=0)
{
strSelectedDocIds+=":";
}
strSelectedDocIds += getSelectDocIds[item].value ;
i++;
}
}
The problem is that if there has 1 checkbox at the time of form load it doesn't work properly.
Try replacing
onclick="RestoreDocFile(\''.$NodeId.'\',this.form.restore_checkbox);"
with
onclick="RestoreDocFile(\''.$NodeId.'\',this.form.getElementsByName(\'restore_checkbox\'));"
This will ensure you get a NodeList regardless of how many checkboxes there are.

Categories

Resources