pass color from view to jquery - javascript

Hi guys i have a view where i have some tags and that tags has a color, i cant change that color via css directly cause its a pseudo element .tag::after what i need is pass that value#tag.color` to the script but i have no idea how to do it i know that when i already did it i can change it easy with the hover and the css change via jquery but how can i pass the value?
#foreach (var tags in i.Tags)
{
<div class="col-md-2">
<ul class="tagMargin">
<li>#tags.NomeTag</li>
</ul>
</div>
}

You can use JQuery .data() and store arbitrary data associated with the matched elements
Having recreated a simple controller
public ActionResult Index()
{
var sampleList = new List<SampleModel>();
sampleList.Add(new SampleModel
{
Color = "#2ecc71",
Name = "Emerald"
});
sampleList.Add(new SampleModel
{
Color = "#2980b9",
Name = "Belize Hole"
});
sampleList.Add(new SampleModel
{
Color = "#c0392b",
Name = "Pomegranate"
});
return View(sampleList.ToList());
}
And the view with my data attribute
#foreach(var tags in Model)
{
<div>
<ul>
<li>#tags.Name</li>
</ul>
</div>
}
Simply retrieve the values of the attribute using JQuery by looping through the list items with the class .tag
var array = [];
$('.tag').each(function () {
array.push($(this).data('color'));
})
console.log(array);
Results:
["#2ecc71", "#2980b9", "#c0392b"]

Related

Get `li` elements and push it into object

I have a simple question!
I have this html and js:
<ul>
<li id="x">foo</li>
<li id="y">bar</li>
</ul>
var data = {
'language': 'fa',
'phrases': {},
};
I want to append all li in the phrases of data for have this output:
{"language":"fa","phrases":{"x":"foo","y":"bar"}}
I try this:
data.phrases.$(this).attr('id') = $(this).html();
And try push this:
data.phrases.push( {$(this).attr('id') : $(this).html()} );
And try extend this:
data.phrases.extend( {$(this).attr('id') : $(this).html()} );
But does not work!
Completed code:
<ul>
<li id="x">foo</li>
<li id="y">bar</li>
</ul>
<div id="result"></div>
var data = {
'language': 'fa',
'phrases': {},
};
//I want to append all `li` in the `phrases` of `data` for have this output:
//{"language":"fa","phrases":{"x":"foo","y":"bar"}}
$("li").each(function() {
//data.phrases.$(this).attr('id') = $(this).html();
//data.phrases.push( {$(this).attr('id') : $(this).html()} );
//data.phrases.extend( {$(this).attr('id') : $(this).html()} );
});
$("#result").html(JSON.stringify( data ));
See here online code: https://jsfiddle.net/NabiKAZ/fw63jd5k/
You cannot .push() into Object.
Use assignment to properties instead:
var data = {
'language': 'fa',
'phrases': {},
};
$("li").text(function(i, txt) {
data.phrases[this.id] = txt;
});
$("#result").html(JSON.stringify( data ));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li id="x">foo</li>
<li id="y">bar</li>
</ul>
<div id="result"></div>
data.phrases is your object literal
[this.id] is your new object property, where this.id is the current li's ID
= txt; is where you assign to that property the value of the current li text
As you can figure out from above, if you need the entire HTML use .html() instead like:
$("li").html(function(i, html) {
data.phrases[this.id] = html;
});
You're quite close! The issue is that the dot operator in JavaScript cannot be used to evaluate a key then access it. You're looking for the [ ] operator, which can be used to evaluate whatever is in the brackets, then use the value as the key. So try this:
data.phrases[$(this).attr('id')] = $(this).html();
you have the right idea, but you aren't quite using your functions correctly. push is an array method, and extend just isn't a native method. so what we want to do is set the id to the key, and the value to the html
https://jsfiddle.net/fw63jd5k/2/
$("li").each(function(i, el) {
data.phrases[el.id] = $(el).html()
}

Save new ul list order after button click using Jquery ui

I have a ul with several dynamically loaded list items (given by the controller to the view). I'm able to move the list items with the JQuery UI and Ruxable Sortable libraries.
Now I need to save the new list order. I've seen lots of examples with PHP and classic asp.net but I have no experience in them and I really want to focus on razor and C# here. My database is MySQL.
When the user clicks on the submit button all the controller needs to retrieve is the same list but with altered orderpositions. How can I achieve this?
View
<ul class="list-group sortable" id="forumlist">
#{
for (int i = 0; i < Model.Count(); i++)
{
<li id="li"#Model[i].id class="list-group-item">#Model[i].name</li>
}
}
</ul>
<button type="button" class="btn btn-info">Opslaan</button>
So; Is there a way to send the collection of items back to the controller (via HttpPost) with altered index? The Model[i] contains a "orderposition" property which indicates were the item needs to be shown in the list. This is also the property that needs to be adapted.
I fixed it!
So just to clarify the process:
There is a list of items
They are displayed in a OL as li
With the JQuery UI sortable methods the list items are draggable
The user drags the list items
The user saves the new order of the list items
So what I did was this:
I just load the items into the view.cshtml:
Controller:
public ActionResult Items()
{
List<item> items= [METHOD that returns the items]();
return View(items);
}
View
#model List<Models.Items>
#using (Html.BeginForm("UpdateItems", "ItemController", FormMethod.Post, new { id = "updateitemform" }))
{
<ol class="list-group sortable" id="itemlist">
#{
for (int i = 0; i < Model.Count(); i++)
{
<li data-order="#Model[i].position" id="#Model[i].Forum_id" class="list-group-item">item
</li>
#Html.HiddenFor(model => Model[i].Item_id)
#Html.HiddenFor(model => Model[i].position,new { #id = "item"+#Model[i].Item_id })
}
}
</ol>
<button type="button" id="saveneworderbutton" class="btn btn-info">Save this shit!</button>
}
And now the magic: Javascript/jquery!
$(document).on("click", "#saveneworderbutton", function () {
$(".list-group-item").each(function (index) {
var id = $(this).attr("id");
$("#" + "item" + id).val(index);
});
$("#updateitemform").submit();
});
I hope this helps people!
Can you send both information? I mean, you can send two lists, one should be the indexes altered, a list like this:
{2, 5, 3, 8, 1}
Your controller can expect this: (... , int[] alteredList)
Well, a better approach can be create a View Model with a property:
public int[] alteredList { get; set; }
then, you can populate that property in the View, and your controller will be expecting the new Model (that new model is the View Model that you create for this operation)
your controller's action method look like this:
public ActionResult [ListActionMethod](NewViewModel listview)
and your view should change the line:
#model ...NewViewModel
Add an attribute to each li element for example data=<%=i %>
and then access these attribute using $('Your selecter').attr("data")
and check whether it is odd or even

Add new values to attribute of the same object

I have a button that needs to add some values to an object attribute. The problem I have found is that I'm creating new objects on every click.
And what I need is to add new values to a specific attribute of a specific object.
I'm getting this
Object { id=0, title="Rolling Stones", sessionsBegin="1443564000000"}
Object { id=0, title="Rolling Stones", sessionsBegin="1443564000001"}
Object { id=0, title="Rolling Stones", sessionsBegin="1443564000002"}
What I need to generate is this
Object { id=0, title="Rolling Stones",sessionsBegin="1443564000000, 1443564000001,1443564000002"}
This on the controller part:
$scope.addItem = function(indexItem, title) {
$scope.cart = {
"id" : indexItem,
"title" : title
}
if ($scope.cart.id==indexItem){
$scope.cart.sessionsBegin=$scope.sessions[indexItem].date;
console.log($scope.cart);
}
}
This on the partial view side:
<div class="row" >
<div class="large-6 columns" >
<div class="panel">
<div ng-repeat="session in sessions">
{{event.id}} Date: {{session.date }} &nbsp
Availability: {{session.availability}} &nbsp
<a ng-click="addItem($index, session.title);" ng-show="addMore">ADD </a>
</div>
</div>
</div>
</div>
You need to concat a string to your current value, like that:
// Add a comma if needed:
$scope.cart.sessionsBegin += ($scope.cart.sessionsBegin) ? ', ' : '';
// and then add the value itself:
$scope.cart.sessionsBegin += $scope.sessions[indexItem].date;
Btw. usually you'd want a list of those sessionsBegin values to be an array - it will be much easier to work with. In that case I'd suggest:
if (!$scope.cart.sessionsBegin) {
$scope.cart.sessionsBegin = [];
}
$scope.cart.sessionsBegin.push($scope.sessions[indexItem].date);
Wouldn't changing $scope.cart.sessionsBegin=$scope.sessions[indexItem].date; to $scope.cart.sessionsBegin+=$scope.sessions[indexItem].date; do the trick?
In your code you redefine the cart object every time you press 'add' though. Hence why your console.log shows new objects every time.
$scope.cart = { ... } // this bit of code means you delete the 'old' $scope.cart and redefine it with new values
Does this work for you?
$scope.addItem = function(indexItem, title) {
$scope.cart = $scope.cart || {
"id" : indexItem,
"title" : title
}
if ($scope.cart.id==indexItem){
var sessionAsArray = $scope.cart.sessionsBegin.split(',');
sessionAsArray.push($scope.sessions[indexItem].date);
$scope.cart.sessionsBegin=sessionAsArray.join(',');
console.log($scope.cart);
}
}

Change label display name labels, based on the values from db, on dropdown change

Problem Statement: I want to change the display name of labels(#Html.LabelFor) in Razor view of MVC based on the display names which i get from db.
I have added the dropdown list of languages in the _Layout.cshtml
<li>#Html.Action("Index", "LanguageDropdown", new { languageid = Request["languageId"] })</li>
I have created one partial view for drop down:
#model ALCMS.Web.Models.Master_or_Configuration.LanguageDropdownModel
<script type="text/javascript">
function GetLanguage() {
var languageId = $('#LanguageId').val();
var Url = "#Url.Content("~/MasterConfigGeneral/GetLanguage")";
$.ajax({
url: Url,
dataType: 'json',
data: { LanguageId: languageId },
success: function (data) {
}
});
}
</script>
<div style="display:inline-block">
#Html.DropDownListFor(l => l.LanguageID, new SelectList(Model.Languages, "Value", "Text"), "Select Language", new { id = "LanguageId" ,onchange="GetLanguage()" })
</div>
Partial View Controller:
public ActionResult Index(string languageId)
{
//return View();
var languages = dbEntity.LookupLanguages;
var model = new LanguageDropdownModel
{
LanguageID = languageId,
Languages = languages.ToList().Select(l => new SelectListItem
{
Value = Convert.ToString(l.LanguageID),
Text = l.Name
})
};
return PartialView(model);
}
In Controller Json Result method:
public JsonResult GetLanguage(int languageID)
{
JsonResult jsResult = new JsonResult();
objdbGlobalTenant.ddlLanguage = (from lsr in dbEntity.LocaleStringResources
where lsr.LanguageID == languageID
select new SelectListItem()
{
Text = lsr.ResourceValue,
Value = lsr.ResourceName
}).Distinct().ToList<SelectListItem>();
//ViewBag.Language = objdbGlobalTenant.ddlLanguage;
jsResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return jsResult;
}
Now everything is working fine.I'm able to get the selected langaugeID in Json Result method in Controller based on the change event of Language dropdown. Based on this Language ID i'm getting display names(ResourceValue) which i need to apply for the particular view.
Problems:
1>After getting the display names from db how to change display names
of particular view when language change event triggers.?? For
ex:Currently i'm seeing the Create.CSHTML. Now if i change the
language dropdown it should trigger Json Event in controller and
after getting values it should apply the values on the view which it
got from db.
Note: Dropdown is in Layout.cshtml(like master in .aspx)
2>Drop-down which i placed in Layout.cshtml is getting refreshed
every time new view is loaded which inherits(layout.cshtml).How to
make the controller to retain it's state during postback??
3>How to get the selected drop-down item from the layout in multiple
Controllers,to change the display name in each view based on the langaugeid
of dropdown in layout
How to do this??If i'm doing wrong suggest me some other ways...
Below are the suggestions :
Issue 1 :
You may keep one attribute in each label which identifies them uniquely.
Your HTML should render like following
<!-- For English -->
<label label-unique-name="Name">Name</label>
<label label-unique-name="Surname">Surname</label>
<!-- For French -->
<label label-unique-name="Name">nom</label>
<label label-unique-name="Surname">nom de famille</label>
<!-- For Spanish -->
<label label-unique-name="Name">nombre</label>
<label label-unique-name="Surname">apellido</label>
Here label-unique-name is your attribute, which will remain fixed for each language. Now when you change the language from dropdown you will bring the values like below.
<!-- For English -->
<label-unique-name:"Name",label-value:"Name">;<label-unique-name:"Surname",label-value:"Surname">
<!-- For French -->
<label-unique-name:"Name",label-value:"nom">;<label-unique-name:"Surname",label-value:"nom de famille">
<!-- For English -->
<label-unique-name:"Name",label-value:"nombre">;<label-unique-name:"Surname",label-value:"apellido">
Please note : this is for understanding only, it's not a JSON.
Now using jQuery go through each label and replace the label's value. Hope it'll help you.
Issue 2 :
You can save the selected language's value in session, and generate your dropdown accordingly.
#Html.DropDownListFor(l => l.LanguageID, new SelectList(Model.Languages, "Value", "Text"), !string.isNullorEmpty(HttpContext.Current.Sessions["Language"]) ? HttpContext.Current.Sessions["Language"] : "Select Language", new { id = "LanguageId" ,onchange="GetLanguage()" })

multidimensional object building in javascript using loops

So i have a html layout in which there are blocks (there are no fix number of them, because they can be created dynamically).
In these blocks there are boxes (again, they can be created dynamically)
The boxes contain *html element*s and also have different data attributes
So i need to create an object which looks like this
block1 = {
box1 : {
id : box1.data('id'),
content : box1.html()
},
box2 : {
id : box2.data('id'),
content : box2.html()
}
},
block2 = {
box3 : {
id : box3.data('id'),
content : box3.html()
}
}
Please don't write that the syntax is not correct, i know. I just tried to somehow illustrate what i want.
So my question is how do i do this with the help of jQuery?
Thank you in advanced
You can select all blocks and boxes and iterate over each of them using .each [docs]:
var blocks = {};
$('.block').each(function(index) {
var boxes = {};
$(this).find('.box').each(function(index) {
boxes['box' + index] = {
id: $(this).data('id');
content: $(this).html();
};
});
blocks['block' + index] = boxes;
});
You might not need an object of objects though, maybe an array of array suffices or would be even better, depending on what you intend to do with the data.
To learn more about how objects work, have a look at MDN - Working with Object.
Here is an idea:
1- Iterate over all of the blocks using some CSS selector.
2- Create a generic JS object and set a collection attribute called "boxes" to be an array
3- For each one, iterate over all the boxes inside it, again, using some CSS selector.
4- Create a generic JS object for each box and set the attributes as needed.
Code version
I think something like this would work (not tested):
var blocks = new Array();
$(".blocks").each(function(b) {
var my_block = {boxes: new Array()};
var $block = $(b);
$(".box", $block).each(function(box) {
var $box = $(box);
my_block.boxes.push({id: $box.attr("id"), content: $box.html()});
});
blocks.push(my_block);
});
You should take a look at Knockout.js, it's very comfortable to build an application like yours.
In detail: use Objects. Build an array for yourself, containing Objects with e.g. Block Name and all Child nodes.
<div id="lanesContainer" data-bind="foreach: blocks">
<div id="" class="dropLane laneDefault ui-widget-header ui-dialog ui-widget ui-corner-all ui-front ui-resizable">
<div class="ui-dialog-titlebar ui-helper-clearfix" data-bind="drop: {value: $data.dropTask}">
<p class="laneheader" data-bind="text: $data.title">Lane</p>
</div>
<ul data-bind="foreach: box">
<li class="ui-dialog-content laneItem" data-bind="drag: {value: $data}">
<div class="ui-widget-header laneItemHeader" data-bind="text: $data.Title"></div>
<div class="ui-widget-content laneItemBody" data-bind="text: $data.Description"></div>
<div class="ui-widget-content laneItemFooter">
<div class="ui-corner-all ui-state-default notification-important">
<span class="ui-icon ui-icon-notice" title="sometitle" data-bind="css: {'notification-important-hide': !$root.isElementImportant($data) }"></span>
</div>
</div>
</li>
</ul>
</div>
</div>
Is this useful?
Here is how to get an Object with nested Array of Childs:
function laneObject(title) {
var obj = new Object();
obj.title = title; //Identifier for Lane
obj.childs = []; //Elements of Lane to display
return obj;
}
I am not entirely sure of what your question is, but if you want to create blocks and boxes dynamically, I suggest you first of all use Arrays.
//All dynamically created blocks
blocks = [];
//Create blocks
for(var i = 1; i < 3; i++) {
var block = {
//All dynamically generated bloxes
boxes = [];
};
//Create boxes
for(var j = 1; j < 4; j++) {
block.box[j] = {
id : j,
content : '<span>html for box' + j + '</span>'
}
}
blocks[i] = block;
}

Categories

Resources