get all selected checkbox value and display them
wanted to separate each element in the array into new line
$('#generate').on('click', function() {
var array = [];
$("input:checked").each(function() {
array.push($(this).val());
});
$("#selectedSubject").text(array+'<br>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
ok so i fixed it myself
on last line i kept using .text instead of .html thats what made me failed oof
$('#generate').on('click', function() {
var array = [];
$("input:checked").each(function() {
array.push($(this).val());
});
let text = "";
for (let i = 0; i < array.length; i++) {
text += array[i] + "<br>";
}
$("#selectedSubject").html(text);
use each agian to iterate over the new array
ie:
$.each(array, function( index, value ) {
$("#selectedSubject").append( value );
});
Related
I have an issue with split() function, I have input in which I push ids that I'm getting through mapping objects.
My HTML:
<input class="custom-img-id" name="custom-img-id" type="hidden" value="" />
My JS:
frame.on( 'select', function() {
var imgIdInput = $( '.custom-img-id' );
var attachments = frame.state().get('selection').map(function( a ) {
a.toJSON();
return a;
}),
thesamepicture = false,
i;
for (i = 0; i < attachments.length; ++i) {
imgContainer.append('<img src="' + attachments[i].attributes.url + '"/>');
imgIdInput.val().split(",").push( attachments[i].id );
}
imgIdInput.val( imgIdInput.val().split(",").join() );
});
If for example I have two object with ids 100 and 101, I will get inside input value this:
value=",100,101"
How to remove first comma? I think I'm doing something wrong.
The issue is probably that "".split(",") gives you [""], not an empty array.
I'd suggest splitting the string once prior to the loop (handling the issue with ""), adding to the resulting array, and then converting it back to a string once at the end, see *** comments:
frame.on( 'select', function() {
var imgIdInput = $( '.custom-img-id' );
var attachments = frame.state().get('selection').map(function( a ) {
a.toJSON();
return a;
}),
thesamepicture = false,
i;
// *** Get the current IDs as an array
var val = imgIdInput.val().trim();
var ids = val ? imgIdInput.val().split(",") : [];
for (i = 0; i < attachments.length; ++i) {
imgContainer.append('<img src="' + attachments[i].attributes.url + '"/>');
// *** Add to the array
ids.push(attachments[i].id);
}
// *** Save the IDs in the hidden input
imgIdInput.val(ids.join());
});
you can use replace
imgIdInput.val( imgIdInput.val().split(",").join().replace(",","") );
console.log(",100,101".replace(",","")) // "100,101"
You need to use split, filter and join function of the array & String to get the expected output.
var value=",100,101"
value = value.split(",")
const finalValue = value.filter(tmp =>{
return tmp !== ''
})
console.log(finalValue.join(","));
I'm trying to find a specific row in a column of an HTML table and replace an occurrence of a specific string with a given value.
I tried to use JQuery's .html but it just replaces everything in the row with the given value. A .text().replace() returned me false.
Here's my code:
function ReplaceCellContent(find, replace)
{
//$(".export tr td:nth-child(4):contains('" + find + "')").html(function (index, oldHtml) {
// return oldHtml.replace(find, replace);
//});
$(".export tr td:nth-child(4):contains('" + find + "')").text($(this).text().replace(find, replace));
//$(".export tr td:nth-child(4):contains('" + find + "')").html(replace);
}
$('.export tr td:nth-child(4)').each(function () {
var field = $(this).text();
var splitter = field.split(':');
if (splitter[2] === undefined) {
return true;
} else {
var splitter2 = splitter[2].split(',');
}
if (splitter2[0] === undefined) {
return true;
} else {
$.post(appPath + 'api/list/', {action: 'getPW', pw: splitter2[0]})
.done(function (result) {
ReplaceCellContent(splitter2[0], result);
});
}
});
I'm iterating through every row of the column 4 and extracting the right string. This is going through an AJAX post call to my function which returns the new string which I want to replace it with.
splitter2[0] // old value
result // new value
I hope someone could help me. I'm not that deep into JS/JQuery.
findSmith findJill findJohn
var classes = document.getElementsByClassName("classes");
var replaceCellContent = (find, replace) => {
for (var i = 0; i < classes.length; i++) {
if (classes[i].innerText.includes(find)) {
classes[i].innerText = classes[i].innerText.replace(find, replace);
}
}
}
this replaces all "fill" occurrences to "look".
I love to use vanilla JS, I'm not really a fan of JQuery but this surely should work on your code.
Do like this :
var tds = $("td");
for( var i = 0; i < tds.length ; i++){
if ( $(tds[i]).text().includes("abc") ){
var replacetext = $(tds[i]).text().replace("abc", "test");
$(tds[i]).text(replacetext);
}
}
Say give all your table rows a class name of "trClasses"
var rows = document.getElementsByClassName("trClasses");
for (var I = 0; I < rows.length; I++) {
rows.innerText.replace("yourText");
}
The innerText property would return the text in your HTML tag.
I'm a newbie too, but this should work. Happy Coding!
I'm looping over an Ajax result and populating the JSON in a select box, but not every JSON result is unique, some contain the same value.
I would like to check if there is already a value contained within the select box as the loop iterates, and if a value is the same, not to print it again, but for some reason my if check isn't working?
for (var i = 0; i < result.length; i++) {
var JsonResults = result[i];
var sourcename = JsonResults.Source.DataSourceName;
if ($('.SelectBox').find('option').text != sourcename) {
$('.SelectBox').append('<option>' + sourcename + '</option>');
}
}
The text() is a method, so it needs parentheses, and it returns text of all <option> concatenated. There are better ways to do this, but an approach similar to yours can be by using a variable to save all the added text, so we can check this variable instead of having to check in the <option> elements:
var result = ["first", "second", "first", "third", "second"];
var options = {};
for (var i = 0; i < result.length; i++) {
var JsonResults = result[i];
var sourcename = JsonResults; //JsonResults.Source.DataSourceName;
if (!options[sourcename]) {
$('.SelectBox').append('<option>' + sourcename + '</option>');
options[sourcename] = true;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="SelectBox"></select>
Note: I only used var sourcename = JsonResults; for the demo. Use your original line instead.
.text is a function, so you have to call it to get back the text in the option
for (var i = 0; i < result.length; i++) {
var JsonResults = result[i];
var sourcename = JsonResults.Source.DataSourceName;
if ($('.SelectBox').find('option').text() != sourcename) {
$('.SelectBox').append('<option>' + sourcename + '</option>');
}
}
For one thing, the jQuery method is .text() - it's not a static property. For another, your .find will give you the combined text of every <option>, which isn't what you want.
Try deduping the object before populating the HTML:
const sourceNames = results.map(result => result.Source.DataSourceName);
const dedupedSourceNames = sourceNames.map((sourceName, i) => sourceNames.lastIndexOf(sourceName) === i);
dedupedSourceNames.forEach(sourceName => {
$('.SelectBox').append('<option>' + sourceName + '</option>');
});
I have a ToDo list, using localStorage... I need to be able to remove the item from the ToDo list... I try to use "dataArray.splice();" But the problem is I don't know how i can remove the object when the position is unknown...
function getTodoItems() {
for (var i = 0; i < dataArray.length; i++) {
if (!dataArray[i].listItem.length) return;
var itemList = document.getElementById("my-todo-list");
var list = document.createElement("li");
itemList.appendChild(list);
list.innerHTML = dataArray[i].listItem;
var spanItem = document.createElement('span');
spanItem.style.float = 'right';
var myCloseSymbol = document.createTextNode('\u00D7');
spanItem.classList.add("closeBtn");
spanItem.appendChild(myCloseSymbol);
listItems[i].appendChild(spanItem);
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
console.log(dataArray);
}
var list = document.getElementsByTagName('li');
list[i].onclick = function() {
this.classList.toggle("checked");
}
}
}
Then probably get its position:
const position = dataArray.indexOf(/*whatever*/);
dataArray.splice(position, 1);
You can get the position of the element using 'indexOf'
let pos = dataArray.indexOf(element);
dataArray.splice(pos,1)
IndexOf() wont work if you are trying to find the index of an entire object or array inside the array.
If you need to find the index of an entire object inside your array, you test each one's value to find out if it is the correct one. I would use findIndex();
Try this in your console:
var array = [];
for (var i = 0; i < 10; i++ ){ array.push({item: i}) }
console.log('Current Array: ', array);
var indexOfResult = array.indexOf({item: 3});
console.log('indexOf result: ',indexOfResult);
var findIndexResult = array.findIndex(object => object.item === 3);
console.log('findIndex result: ',findIndexResult)
I create a form with matrix like this:
for(var i = 0; i < rows; i++)
{
for(var j = 0; j < columns; j++)
{
var input = $('<input>')
.attr({
class: 'matrix_cell',
value: 0});
form.appendChild(input[0]);
}
var br = $('<br>')[0];
form.appendChild(br);
}
And I want to read a matrix that user inputted to two-dimensional array and then pass it to php file in ajax query.
I tried this way:
function getMatrix(){
var matrix_row = []
$("#matrix_form").find("input").each(function(i){
var value = $(this).val();
if (!isNaN(value)){
matrix_row[i] = value;
}
});
return matrix_row;
}
But it reads matrix to onedimensional array.
See http://jsfiddle.net/hcbLozd7/
function getMatrix(){
var matrix_row = [];
var ind = 0;
$("#frm").contents().each(function(i,e){ //for all contents in div
if (this.nodeName == "INPUT") //if it's input
{
if (!matrix_row[ind]){ //it matrix doesn't have a new array, push a new array
matrix_row.push([]);
}
matrix_row[ind].push($(this).val()); //add input value to array inside array
}
else{ //when element is br
ind++; //increment counter
}
});
return matrix_row;
}