I have code like :
<div id="content">
<div id="widget1"></div>
<div id="widget89"></div>
<div id="widget78"></div>
..............
<div id="widget(anyIndex)"></div>
</div>
By adding content into widget (HTML/JS widget) I have :
<div id="content"
<div id="widget1">
<script type='text/javascript'>
jQuery("#widget1").selectme({
Numpost:4,
Stylepost:"papa",
});
</script>
</div>
<div id="widget89">
<script type='text/javascript'>
jQuery("#widget89").selectme({
Numpost:7,
Stylepost:"popo",
});
</script>
</div>
..............
<div id="widget(anyIndex)">.....</div>
</div>
It is so manual and time-consuming.
Now, I want use short code instead of repeating too much Javascript in each div like :
<div id="content"
<div id="widget1">[4][papa]</div>
<div id="widget89">[7][popo]</div>
..............
<div id="widget(anyIndex)">...</div>
</div>
JS :
<script>
(function (a) {
a.selectme = function (c, b) {
var d = this;
d.init = function () {
d.options = a.extend({}, a.selectme.defaultOptions, b);
...................something
};
d.init()
};
a.selectme.defaultOptions = {
Numpost:4,
Stylepost:"Enter your style",
};
a.fn.selectme = function (b) {
return this.each(function () {
(new a.selectme(this, b))
})
}
})(jQuery);
</script>
Notice :Widget(anyindex) is catch automatically. For example: widget89 is set current but I don't know the index of that widget (index = 89), just sure that I am inputting Javascript/Jquery code into it. When I add new widget I will have new index, for example : widget105 or also widget200 (anyindex)
How can I do that. Thanks for your help.
Here's a way using data attributes in markup and a simple each loop to initialize. Add data- attributes for the variables you need to specify in plugin.
<div id="widget89" data-numpost="7" data-style="popo">
alert( $('#widget89').data('numpost') );
To get index of widgets create a collection of them first to use to index against:
Using $.each to intialize the whole collection will give you the index of widget in collection ( I'm not clear what you need it for):
$('[id^=widget]').each(function(idx){
var $this=$(this), data=$this.data, INDEX=idx;
$this.selectme({
Numpost:data.numpost,
Stylepost:data.style
})
})
you can use a function
function setwidget(id,post,style)
{
jQuery("#"+id).selectme({
Numpost:post,
Stylepost:style
});
}
now call like
setwidget("widget1",4,"papa");
setwidget("widget89",7,"popo");
Related
JS noob here.
I'm not sure if this if I'm doing this correctly but I'm trying to run a script "within" another script.
<script type="text/discourse-plugin" version="0.8">
api.decorateWidget('post:after', helper => {
let post = helper.getModel();
if (post.get('post_number') % 3 === 0) { // after every 3 posts
return helper.rawHtml(`
<div class="lead_static_wrapper"><p>Label</p>
<div class="proper-ad-unit">
<div id="pr-ad-nr_main_1">
propertag.cmd.push(function() { proper_display('nr_main_1'); });
</div>
</div>
</div>
`);
}
});
</script>
I need this part to run but it just shows as text when live, and doesn't seem to be running.
propertag.cmd.push(function() { proper_display('nr_main_1'); });
This doesn't seem to be the working:
<script type="text/discourse-plugin" version="0.8">
api.decorateWidget('post:after', helper => {
let post = helper.getModel();
if (post.get('post_number') % 3 === 0) { // after every 3 posts
return helper.rawHtml(`
<div class="lead_static_wrapper"><p>Label</p>
<div class="proper-ad-unit">
<div id="pr-ad-nr_main_1">
<script>propertag.cmd.push(function() { proper_display('nr_main_1'); });</script>
</div>
</div>
</div>
`);
}
});
</script>
Is there a way to edit the JS structure so this works?
I'm trying to make this work for Discourse forums. Any help is appreciated! Thanks!
Use a backslash to escape the closing slash.
<script>propertag.cmd.push(function() { proper_display('nr_main_1'); });<\/script>
Consider the following snippet as an example:
<div class="bar foo">
</div>
<div class="bar">
<div class="foo"></div>
</div>
Given var $set=$('.bar'); I need to select both nodes with foo class. What is the proper way to achieve this. Considering addBack() requires a selector and here we need to use the $set jQuery object and $set.find('.foo') does not select the first node.
use this :
var $set = $(".bar").filters(function () {
var $this = $(this);
if($this.is(".foo") || $this.find(" > .foo").length !== 0){
return true;
} else{
return false;
}
});
Here's one way of going about it:
var set = $('.bar');
var foos = [];
for (var i = 0; i < set.length; i++) {
if ($(set[i]).hasClass('foo')) {
foos.push(set[i]);
}
}
if (set.find('.foo').length !== 0) {
foos.push(set.find('.foo')[0]);
}
console.log(foos);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bar foo"></div>
<div class="bar">
<div class="foo"></div>
</div>
The for loop checks all elements picked up with jQuery's $('.bar'), and checks if they also have the foo class. If so, it appends them to the array. The if checks if any of the elements picked up in set have any children that have the foo class, and also adds them.
This creates an array that contains both of the DIVs with the foo class, while excluding the one with just bar.
Hope this helps :)
test this :
var $newSet = $set.filter(".foo").add($set.has(".foo"));
You could use the addBack() function
var $set=$('.bar');
console.log($set.find(".foo").addBack(".foo"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bar foo">
</div>
<div class="bar">
<div class="foo"></div>
</div>
what I'm trying to do is iterate over a collection of div, contained in a parent container. My structure is the following:
<div id='main'>
<div data-id='2'>
</div>
<div data-id='3'>
</div>
</div>
My goal is take the field data-id of each div and create an array collection. Previously I used the select where do I get each value of available option, like this:
var available_services = $('#selected-service').find('option', this).map(function ()
{
return this.value;
}).get();
But now I'm using a div collection instead of the select. How I can iterate through all available div?
This should return all data-id values in a list:
var available_services = $('#main').find('div').map(function (item)
{
return item.attr('data-id');
});
I didn't test this, but I think should do the job. (maybe you need to tweak a little bit)
I believe this will do it:
var available_services = [];
$('#main div').each(function(){
available_services.push($(this).data( "id" ));
})
This is the easy way to go:
$(document).ready(function() {
var myCollection = [];
$('#main div').each(function(){
var dataDiv = $(this).attr('data-id');
myCollection.push(dataDiv)
})
});
Try this:
(function(){
var main = $("#main");
var divs = $(main).find("div");
var arrId = divs.map(function(index, div){
return $(div).attr("data-id");
});
console.log(arrId);
})()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='main'>
<div data-id='2'>
</div>
<div data-id='3'>
</div>
</div>
I have a for each loop in my razor view (MVC4)
#foreach (var fe in ViewBag.FeatureProducts)
{
<div class="product-details" style="display:none;">#Html.Raw(fe.Details)</div>
<div class="product-qty-dt"> </div>
}
in the each loop i have to extract the #html row content and display in to the div 'product-qty-dt'.
For that I write the following jquery,
$(document).ready(function () {
var data = $('.product-details p').map(function () {
return $(this).text();
}).get();
//product availability
var availability = data[2].split(",");
$.each(availability, function (i) {
$('.product-qty-dt').append( availability[i])
});
});
But this was only consider the last foreach raw. how can i call this jquery in each loop call.
For example, In first loop,
<div class="product-details" style="display:none;"><p>Lorem, Ispum</p><p>doler emit,fghjh</p><p>9gm</p></div>
<div class="product-qty-dt"> 9gm </div>
second loop
<div class="product-details" style="display:none;"><p>Lorem, Ispum</p><p>doler emit,fghjh</p><p>5gm</p></div>
<div class="product-qty-dt"> 5gm </div>
Thirdloop
<div class="product-details" style="display:none;"><p>Lorem, Ispum</p><p>doler emit,fghjh</p><p>3gm</p></div>
<div class="product-qty-dt"> 3gm </div>
The following will add the text of the last <p> in a <div class="product-details"> element into the corresponding <div class="product-qty-dt"> element
$('.product-details').each(function () {
var t = $(this).children('p').last().text();
$(this).next('.product-qty-dt').text(t);
})
This should do the trick. Also the data array is still used just incase you would like to access other data portions stored in product-details.
$(".product-details").each(function()
{
var data = $(this).find('p').map(function () { return $(this).text() }).get();
$(this).next('.product-qty-dt').text(data[2]);
})
I am trying to make a page where the user selects an item in a drop-down list, which then will create a duplicate drop-down list. The last drop-down list always needs to create a new one once an item is selected.
Using the following javascript code
<script type="text/javascript">
$(document).ready(function () {
$(function listselect() {
if (x == null) {
var x = 1;
}
//need to increment x after the completion of the following funciton so the function will trigger on different drop-down lists
$('#FooId' + x).change(function q() {
$('#FooId' + x).clone().attr('id', 'FooId' + (++x)).attr('name', 'Selected').insertAfter('#FooId' + (x - 1))
//return x;
});
//return x;
});
});
</script>
and the razor html
<div class ="container">
<div class="label">
#Html.LabelFor(Function(model) model.Foo, "Foo")
</div>
<div class="foo" id="foo">
#Html.DropDownList("FooId", Nothing, "--Select--", New With {.Name = "Selected", .Id = "FooId" & "1"})
//#*#Html.ValidationMessageFor(Function(model) model.Foo)*#
</div>
</div>
I am able to make the first list clone itself, but how do you return x from function q so that it can be used by its own function (Function q needs to trigger when an item is selected in Foo1, then Foo2, etc.).
(Sorry if this doesn't make sense, I am not sure how to word it. I am very new to coding). Thanks.
If I got you right, you don't need most of your code. And it's easier to use classes here. Just do it like this:
$(document).ready(function () {
$('.foo').on('change', function(e) {
var newFoo = $(e.target).clone();
$(e.target).after(newFoo);
});
});
And your markup part should be like this:
<div class ="container">
<div class="label">
#Html.LabelFor(Function(model) model.Foo, "Foo")
</div>
<div class="foo" id="foo">
#Html.DropDownList("FooId", Nothing, "--Select--", new {name = "Selected", #class = "foo" })
</div>
</div>
I don't remember Html.DropDownList signature so I created simple jsfiddle without it. I hope this is what you needed.
UPDATE:
I've corrected my fiddle as follows:
$(document).on('change', '.foo:last', function(e) {
var newFoo = $(e.target).clone();
$(e.target).after(newFoo);
});
Now it doesn't add extra selects if it's not the last select that was changed.