I want to loop an array and show the result using sweet alert, I am new in this so I try the code below, but show me some like [object],[object]
swal({
content:{
element: "ul",
attributes: {
innerHTML:$.each(json.DATA.ARYPUB, function (key, img) {
"<li><img src='"+img.PATH+"'></li>"
})
}
}
})
Can someone help me, please
One approach could be generating the complete HTML outside the constructor of the alert and then set that html string to the related property. Example:
var html = "";
$.each(json.DATA.ARYPUB, function(key, img)
{
html += "<li><img src='" + img.PATH + "'></li>"
});
swal({
content:{
element: "ul",
attributes: {
innerHTML: html
}
}
});
I faced the same issue so, I did this
const addOption = (arr) => {
let optionItems;
arr.forEach(item =>{
optionItems += `<option value="${item}">${item}</option>`
})
return optionItems
}
//in swal
Swal.fire({
html:addOption(Yourarray)
})
Related
Hi guys i have written some javascript code to display some values depend on another dropdown. So now i would like to display those selected values in my edit page..
Here is my code:
function getSubjectsTopics(subject_id)
{
if(subject_id) {
loading_show();
axios.get("/master/topic/get-topic-by-subject-id/" + subject_id)
.then(function(response) {
var optionHtml = '<option value="0">Parent</option>';
if(response.data.status) {
$.each(response.data.subject_topics, function(i,v) {
optionHtml += `<option value="${v.id}" >${v.name}</option>`;
}
$("#ddl_topic_type").html(optionHtml).attr('disabled', false).select2();
loading_hide();
})
.catch(function(error) {
loading_hide();
console.log(error);
Swal.fire({
type: 'error',
title: 'Oops...',
text: 'Something went wrong!'
})
})
} else {
$("#ddl_topic_type").attr('disabled', true);
}
}
Can some one help me how can i add my selected code in optionhtml variable.TIA
In the $.each block, you can use a ternary operator and add the "selected" keyword based on the selection criteria.
First assign a boolean to isSelected variable after checking whether it should be selected or not. Then add the selected keyword into the template literals using a ternary operator
optionHtml += `<option value="${v.id}" ${isSelected ? 'selected' : ''} >${v.name}</option>`;
The variable htmlStr may contain different spellings of id:
var htmlStr = "<div id="demo_div"></div>";
var htmlStr = "<div id='demo_div'></div>";
var htmlStr = "<div id=demo_div class="demo"></div>";
var htmlStr = "<div id=demo_div></div>";
How can I write this differently without many try-catch functions? Can I combine the patterns? It works - but does not look pretty.
var idname;
try {
idname = /(id="(.*?)(\"))/g.exec(htmlStr)[2]
} catch (e) {
try {
idname = /(id='(.*?)(\'))/g.exec(htmlStr)[2]
} catch (e) {
try {
idname = /(id=(.*?)(\ ))/g.exec(htmlStr)[2]
} catch (e) {
try {
idname = /(id=(.*?)(\>))/g.exec(htmlStr)[2]
} catch (e) {
console.log(e);
}
}
}
}
console.log(idname);
You can do this without using regex by simply parsing the HTML.
const htmlStrings = [
'<div id="demo_div"></div>',
"<div id='demo_div'></div>",
"<div id=demo_div class='demo'></div>",
'<div data-id="not_a_real_id"></div>', //note: doesn't have an ID
"<div data-id=not_an_id ID= demo_div></div>",
"<div id= demo_div><span id=inner_id></span></div>"
];
function getId(html) {
const parser = document.createElement('div');
parser.innerHTML = html;
return parser.firstChild.id;
}
htmlStrings.forEach(x => console.log(getId(x)));
As you can see, you can create an element, put the HTML in it, then grab the first child and check it's ID. It works even if you have another type of attribute like a custom attribute called data-id or if the ID has any kind of capitalisation or even if that div has inner elements or anything else.
This technique won't work with invalid HTML or if you have multiple elements you want the ID of but this is simply to demonstrate it. Once it's parsed into a proper element, you can traverse its hierarchy as you see fit and perform any sort of extraction you need.
/id=["']?([^\s"'>]+)/g
This will match all four examples.
I have a website with a list of json objects arranged something like this:
[
{
"a": true or false,
"b": "information",
"c": "information",
"d": "information",
"e": "information"
},
...
]
The idea of this code is to print out all the objects on a table and have a checkbox which filters out the false objects out when needed. The site is supposed to just have the the table with unfiltered object on there, but after I added the checkbox event listener the full table list disappeared. When I check the checkbox I get the filtered objects and it keeps adding more and more of the same filtered content on the bottom of the table if I keep re-clicking it.
What am I doing wrong here? Here is the code I have:
var stuff = document.getElementById("stuff-info");
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'url');
ourRequest.onload = function() {
var ourData = JSON.parse(ourRequest.responseText);
renderHTML(ourData);
};
ourRequest.send();
function renderHTML(data) {
var htmlString = "";
var filteredData = data.filter(function(element) {
return element.a
});
var checkbox = document.querySelector("input[name=hide]");
checkbox.addEventListener('change', function() {
if (this.checked) {
for (i = 0; i < filteredData.length; i++) {
htmlString += "<table><tr><td>" + filteredData[i].b + "</td><td>" + filteredData[i].c + "</td><td>" + filteredData[i].d + "</td><td>" + filteredData[i].e + "</td></tr>"
}
} else {
for (i = 0; i < data.length; i++) {
htmlString += "<table><tr><td>" + data[i].b + "</td><td>" + data[i].c + "</td><td>" + data[i].d + "</td><td>" + data[i].e + "</td></tr>"
}
}
stuff.insertAdjacentHTML('beforeend', htmlString);
});
}
Might be easier to filter with CSS selector:
#filter:checked ~ table .filter { display: none }
<input type=checkbox id=filter> Filter
<table border=1>
<tr class=filter><td>1</td><td>a</td></tr>
<tr><td>2</td><td>b</td></tr>
<tr class=filter><td>3</td><td>c</td></tr>
<tr><td>4</td><td>d</td></tr>
</table>
after I added the checkbox event listener the full table list disappeared.
All of your logic for deciding what to render is trapped inside your onchange event, so nothing will be drawn until a checkbox is changed.
When I check the checkbox I get the filtered objects and it keeps adding more and more of the same filtered.
All of your html strings are generated with += against the original htmlString variable trapped in the closure. So yeah, it will just keep adding more and more rows. You are also inserting the udated strings into the dom without removing the old table(s), so this will be exponential growth.
I think there is a great case here for higher order functions instead of for loops, you can use the map array method to transform each item in the array into a string, instead of manually iterating. This is cleaner and more maintainable.
Notice that now that the rendering logic is not mixed together with the event logic, it would be much easier to reuse the render function with some different data or different events. It's also somewhat trivial to add more transformations or filters.
const ourRequest = new XMLHttpRequest();
ourRequest.onload = function() {
const ourData = JSON.parse(ourRequest.responseText);
initialRender(ourData);
};
ourRequest.open('GET', 'url');
ourRequest.send();
function filterAll() { return true; }
function filterA() { return element.a; }
function toRowString(item) {
return `
<tr>
<td>${item.a}</td>
<td>${item.b}</td>
<td>${item.c}</td>
<td>${item.d}</td>
<td>${item.e}</td>
</tr>`;
}
function renderTable(predicate, parentElement, data){
const rows = data
.filter(predicate)
.map(toRowString);
parentElement.innerHTML = `<table>${rows}</table>`;
}
function initialRender(data) {
const stuff = document.getElementById("stuff-info");
const checkbox = document.querySelector("input[name=hide]");
renderTable(filterAll, stuff, data);
checkbox.addEventListener('change', function(event) {
renderTable(
event.target.checked ? filterA : filterAll,
stuff,
data
);
}
}
I am trying to solve a problem in javascript and I want to do it in javascript not in jQuery.
I create objects in javascript, display them as elements and I bind an eventListener. For simplicity I create objects with a name, description and a price. What I basically want to do is when people click the name the corresponding price is alerted. Is there any way to do this with javascript? In my actual project I want a hover event so that people get a tooltip-like description of the product, but the idea is the same.
Thanks in advance.
Here a fiddle:
fiddle
And some code:
function makeProduct (name, description, price) {
this.name = "<p class='name'>" + name + "</p>";
this.description = "<p class='description'>" + description + "<p>";
this.price = "<p class='price'>" + price + "</p>";
document.getElementById('productlist').innerHTML+=this.name;
document.getElementById('productlist').innerHTML+=this.description;
document.getElementById('productlist').innerHTML+=this.price;
}
var product1=new makeProduct("Pizza", "very Tasty", 5.00);
var product2=new makeProduct("Choclate milk", "warm for the cold winter", 3.00);
var productnames = document.getElementsByClassName('name');
for (i=0; i<productnames.length; i++){
(function(){
productnames[i].addEventListener('click', showPrice, false);
})();
}
function showPrice () {
alert("product price");
}
The quick fix is to write a function that returns the next matching p elem:
function getNextElement(elem, className) {
var next = elem.nextElementSibling; // set next element to "nextElementSibling" relative to passed element.
while (next && !next.classList.contains(className)) { // check for existence and class
next = next.nextElementSibling; // if it exists, but the class does not, move to the next element and repeat.
}
return next; // return whatever was found, or null
}
function showPrice () {
var elem = getNextElement(this, 'price'),
price = elem ? elem.innerHTML : 'Price not found.';
alert(price);
}
See updated fiddle: http://jsfiddle.net/zkbdy0rt/5/
A better way to do this would be to change how you are building your product list. For instance, I would put each product in a containing div (with class="product") for easier styling or finding.
In JavaScript, you can also add arbitrary properties to DOM elements which can be useful. For instance, you could store the price on the DOM element and then retrieve it in your click event handler.
div.price = product.price;
and then later...
showPrice = function (e) {
var price = this.parentElement.price;
alert(price.toFixed(2));
}
See this fiddle for a working example: http://jsfiddle.net/zkbdy0rt/6/
First I fix your current code:
function makeProduct (name, description, price) {
this.name = "<p class='name'>" + name + "</p>";
this.description = "<p class='description'>" + description + "<p>"; //this line
...
}
//this line shoud be:
this.description = "<p class='description'>" + description + "</p>"; //</p> should be closing tag
Secondly:
function makeProduct (name, description, price) {
//...
document.getElementById('productlist').innerHTML+=this.price;
}
as makeProduct(..) returns nothing, there shoulding be assigment to new object to product1
var product1=new makeProduct("Pizza", "very Tasty", 5.00);
Finally your function that returs relevant price should look line:
function showPrice(evt)
{
var p1 = evt.target.nextSibling.nextSibling;
alert(p1.innerHTML);
}
DEMO
I am using MVC3 on my project.
I have a view with a bunch of DDL's, Search Button and a Table.
User can choose values and then hit the search button and the table will show all data that got hit.
This is my jquery code for the search button click:
$(function () {
$('#submitfloat').click(function () {
var SubjectTypes = $('#SubjectTypes').val();
var Teams = $('#Teams').val();
var Companies = $('#Companies').val();
var Consultants = $('#Consultants').val();
var PlannedDates = $('#PlannedDates').val();
var CompletedDates = $('#CompletedDates').val();
var DateTypes = $('#DateTypes').val();
var data = {
Subjectypes: SubjectTypes,
Companies: Companies,
Teams: Teams,
Consultants: Consultants,
PlannedDates: PlannedDates,
CompletedDates: CompletedDates,
DateTypes: DateTypes
};
$.post('#Url.Action("Search", "SearchNKI")', data, function (result) {
$("#GoalcardSearchResult tbody").html('');
result.forEach(function (goalcard) {
$("#GoalcardSearchResult tbody").append(
$('<tr/>', {
click: function () {
// todo: redirect
alert(goalcard.Id);
},
html: "<td>" + goalcard.Name + "</td><td>" + goalcard.Customer + "</td><td>" + goalcard.PlannedDate + "</td><td>" + goalcard.CompletedDate + "</td>"
}));
});
});
return false;
});
});
This is my Controller:
[HttpPost]
public JsonResult Search(SearchQueryViewModel model)
{
var goalcard = SearchRep.FindGoalCard(model); // My LINQ
return Json(goalcard.Select(x => new GoalCardViewModel(x)));
}
Everything works fine but when I add my Jquery Table Sorter:
<script type="text/javascript">
$(document).ready(function () {
$("#GoalcardSearchResult").tablesorter();
});
</script>
I get this wall of Json text when I click on the Search button:
![][1]
[1]:
I have no idea why this happens, when I debug my search button click jquery code its not even getting executed when I add the Table Sorter jquery code. Anyone have any idea what the cause is?
All I know is that when I add the Table Sorter, it blocks my button click jquery code from running and jumps directly to the server-side and returns json.
Thanks in advance!
It was a modified Table Sorter code, with some minor changes I got it running