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.
Related
I have a problem changing items after searching.
I looked at similar threads but found no solution there :(
It looks like the first time the page loads well - the first time the entire Index.cshtml page is loaded which contains a collection of books in the selected category.
There is a search engine on the page - after searching for "manual" - ajax correctly replaces elements with those containing "manual" in the name.
Then when I enter something into the search engine a second time (for example "exercises") - the content of the page does not change any more.
I tried to debug and I see that new items are correctly downloaded from the database - the condition "if (Request.IsAjaxRequest ())" is true and the items are passed to partial view - there the "foreach" loop goes through them. Unfortunately, after _Partial, nothing happens.
I can't find a mistake - the strangest thing is that the first ajax call works fine - only the second (and subsequent) bad.
CatalogController.cs
public ActionResult Index(string categoryName = null, string searchQuery = null)
{
if (categoryName == null)
categoryName = (db.Categories.Find(1)).Name;
var category = db.Categories.Include("Books").Where(x => x.Name.ToLower() == categoryName).Single();
var books = category.Books.Where(x => (searchQuery == null || x.Title.ToLower().Contains(searchQuery.ToLower()) || x.SubTitle.ToLower().Contains(searchQuery.ToLower()) || x.Level.ToLower().Contains(searchQuery.ToLower())) && !x.Inaccessible);
if (Request.IsAjaxRequest())
return PartialView("_PartialBooksList", books);
else
return View(books);
}
Index.cshtml
<form class="o-search-form" id="search-form" method="get" data-ajax="true" data-ajax-target="#booksList">
<input class="o-search-input" id="search-filter" type="search" name="searchQuery" data-autocomplete-source="#Url.Action("SearchTips")" placeholder="Search" />
<input class="o-search-submit" type="submit" value="" />
</form>
<div class="row" id="booksList">
#Html.Partial("_PartialBooksList")
</div>
#section Scripts
{
<script src="~/Scripts/jquery-3.5.0.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.js"></script>
<script>
$(function () {
var setupAutoComplete = function () {
var $input = $(this);
var options =
{
source: $input.attr("data-autocomplete-source"),
select: function (event, ui) {
$input = $(this);
$input.val(ui.item.label);
var $form = $input.parents("form:first");
$form.submit();
}
};
$input.autocomplete(options);
};
var ajaxSubmit = function () {
var $form = $(this);
var settings = {
data: $(this).serialize(),
url: $(this).attr("action"),
type: $(this).attr("method")
};
$.ajax(settings).done(function (result) {
var $targetElement = $($form.data("ajax-target"));
var $newContent = $(result);
$($targetElement).replaceWith($newContent);
$newContent.effect("slide");
});
return false;
};
$("#search-filter").each(setupAutoComplete);
$("#search-form").submit(ajaxSubmit);
});
</script>
}
_PartialBooksList
#model IEnumerable<ImpressDev.Models.Book>
#using ImpressDev.Infrastructure
<div class="row">
#foreach (var book in Model)
{
<div class="col-12 col-xl-4">
<a class="o-shop-link" href="#Url.Action("Details", "Catalog", new { bookId = book.BookId })">
<div class="o-shop-item">
<img class="o-shop-img" src="#Url.BookPhotoSourcePath(book.PhotoSource)" />
<div class="o-shop-text">
<h2>#book.Title</h2>
<h6>#book.SubTitle - #book.Level - <b>#book.Price zł.</b></h6>
+ Add to cart
</div>
</div>
</a>
</div>
}
</div>
Please help
I am not sure if this is the case, but try to change this code:
$($targetElement).replaceWith($newContent);
To this:
$($targetElement).html($newContent);
I think the problem is the div element with id="booksList" is replaced after first search. So you don't have this element in the second search.
I looked through the code step by step and found a solution to my problem.
In the first search, replace id="booksList"
<div class="row" id="booksList">
#Html.Partial("_PartialBooksList")
</div>
partial view in which there was only without id = booksLists.
In the next search there was no ID in this place and there was nothing to replace.
I am being able to provide option's in the menu bar but when I click on any of the option it's working absolutely fine,but if I tried to select twice it is changing at all places.
For Ex.
I want to make a ordered list such as:
1.Some Text here
a.option 1 b.option 2
c.option 3 d.option 4.
When I am trying to select some text its also converting 1 to A.
Please help.Thanks in advance
document.execCommand('insertUnorderedList',true,null);
let selectedStyle = event.target.parentNode.classList.value;
$('li').attr('id', function(i) {
return 'unorder'+(counter+1);
});
$('ol > li').css({'list-style-type':selectedStyle});
You can ignore the counter part its not required.I was trying to put id at every element and use jquery to update only that part.
let counter = 0;
document.querySelectorAll (".unorder-list-select .unorder-list-main .unorder-container ul").forEach((elem)=>{
elem.addEventListener("click",(event)=>{
counter++;
$('li').attr('id', function(i) {
return 'unorder'+(counter+1);
});
$('ul > li').css({'list-style-type':selectedStyle});
}
HTML
<div class="order-list-select" id="orderList" draggable="true">
<div>
<span class="jodit_popup_triangle"></span>
<div class="math-toolbar-top" id="orderlistHeader"></div>
<div class="order-list-main">
<div class="order-list-container"></div>
<div class="order-container">
<ol class="upper-roman">
<li><hr></li>
</ol>
<ol class="decimal">
<li><hr></li>
</ol>
</div>
</div>
</div>
</div>
Actual
1.text
2.text
Some text here
1.Txt
2.Txt
Expected
1.text
2.text
Some text here
a.Txt
b.Txt
I did it by Jquery don't know if its right approach but it has made me achieve my task.
Below is the code for my this.
document.querySelectorAll(".unorder-list-select .unorder-list-main .unorder-container ul").forEach((elem)=>{
elem.addEventListener("click",(event)=>{
counter++;
document.execCommand('insertUnorderedList',true,null);
let selectedStyle = event.target.parentNode.classList.value;
let select = window.getSelection().focusNode.parentElement.parentElement;
let ul_id = ""
$(select).attr('id', function(i) {
ul_id = "unorder"+(counter);
return ul_id;
});
if(selectedStyle == "right-arrow"){
$('#'+ul_id).css({'list-style-image':`url('icons/list-right-editor.svg')`});
}else if(selectedStyle == "open-square"){
$('#'+ul_id).css({'list-style-image':`url('icons/square-open-editor.svg')`});
}else{
$('ul').attr('type',function(){
return selectedStyle;
})
$('#'+ul_id).css({'list-style-type':selectedStyle});
}
document.querySelector(".unorder-list-select").remove();
})
});
Please change the classess accordingly to get the tag and click.
I have little problem with my code. I push the value of an input in an empty array, and i display the value in a html list with a remove button.
But when i remove the value in html, the array still holds the value. I used arr.splice(0, 1) but it doesn't remove the specific value. Example:
My html list looks like:
v1
v2
v3
My array after the list is filled:
array = [v1, v2, v3]
When i remove v2 in html my array doesn't changes. I'm new to JavaScript.
My code in JSBin or JSFiddle.
im sorry my english is not very nice
https://jsfiddle.net/15mdjdpa/
var taches = [];
var saisie;
var ecran;
var liste;
var organiz;
var j= 0;
function run(){
saisie= document.getElementById('champ').value;
taches.push(saisie);
ecran = document.getElementById('afficheur');
var liste = document.getElementById('listes');
console.log("taches :", taches);
var li = document.createElement('li');
li.setAttribute("id", "lisupr");
var btn = document.createElement('Button');
btn.textContent="X";
btn.addEventListener("click",function supr (){
liste.removeChild(li);
taches.splice(0,1);
console.log("tableau taches: "+ taches);
} );
li.innerText= saisie + " "+" ";
console.log("saisie "+saisie);
li.appendChild(btn);
liste.appendChild(li);
}
<input type ="text" id="champ" onfocus="javascript:this.value=''" class="form-control ">
<button type="button" onclick ="run()" class="btn btn-primary" >send</button>
<div id="afficheur"><h4> list : </h4>
<ul id="listes"> </ul>
</div>
If you want to remove v2 from array, do like this.
var index = array.indexOf(v2);
if(index != -1) array.splice(index,1);
I'd rewrite this code using jQuery. I'd remove all the ids - you can make the edits relative to the button being clicked. Which would let you have more than one of these on a page, among other things.
HTML:
<div class="module">
<input class="item" />
<button type="button" class="btn btn-primary js-add">add</button>
<ul class="list"></ul>
</div>
Here's the script:
var list = [],
addToList = function(target,item){
list.push(item);
target
.append(
$('<li>')
.html(item)
.append(
$('<button>')
.addClass('js-delete m-l')
.html('X')
)
)
}
$('.js-add').click( function(){
var parent = $(this).parent(),
item = parent.find('input.item');
addToList(parent.find('ul.list'),item.val());
item.val('');
})
$('.module').on( 'click', '.js-delete', function(){
var parent = $(this).parent(),
index = $('li').index( parent );
list.splice(index,1);
parent.remove();
console.log(list);
})
Actually, if you want to make it so you can add multiple lists, you actually need to nest the 'list' array in an object or array, and have something reference it, probably inside the module div.
Your issue is what Angular does automatically - without all the management. It binds the html content to the json array so all you need to do is change the array value, or delete it. The HTML would immediately reflect the change.
Here's a jsfiddle:
https://jsfiddle.net/mckinleymedia/yducyt83/
So, I have been bashing my head against the desk for a day now. I know this may be a simple question, but the answer is eluding me. Help?
I have a DropDownList on a modal that is built from a partial view. I need to handle the .Change() on the DropDownList, pass the selected text from the DropDownList to a method in the controller that will then give me data to use in a ListBox. Below are the code snippets that my research led me to.
all other controls on the modal function perfectly.
Can anyone see where I am going wrong or maybe point me in the right direction?
ProcessController
// I have tried with [HttpGet], [HttpPost], and no attribute
public ActionResult RegionFilter(string regionName)
{
// Breakpoint here is never hit
var data = new List<object>();
var result = new JsonResult();
var vm = new PropertyModel();
vm.getProperties();
var propFilter = (from p in vm.Properties
where p.Region == regionName && p.Class == "Comparable"
select p).ToList();
var listItems = propFilter.ToDictionary(prop => prop.Id, prop => prop.Name);
data.Add(listItems);
result.Data = data;
return result;
}
Razor View
#section scripts{
#Scripts.Render("~/Scripts/ui_PropertyList.js")
}
...
<div id="wrapper1">
#using (Html.BeginForm())
{
...
<div id="fancyboxproperties" class="content">
#Html.Partial("PropertyList", Model)
</div>
...
<input type="submit" name="bt_Submit" value="#ViewBag.Title" class="button" />
}
</div>
Razor (Partial View "PropertyList.cshtml")
...
#{ var regions = (from r in Model.Properties
select r.Region).Distinct(); }
<div>
<label>Region Filter: </label>
<select id="ddl_Region" name="ddl_Region">
#foreach (var region in regions)
{
<option value=#region>#region</option>
}
</select>
</div>
// ListBox that needs to update after region is selected
<div>
#Html.ListBoxFor(x => x.Properties, Model.Properties.Where(p => p.Class == "Comparable")
.Select(p => new SelectListItem { Text = p.Name, Value = p.Id }),
new { Multiple = "multiple", Id = "lb_C" })
</div>
...
JavaScript (ui_PropertyList.js)
$(function () {
// other events that work perfectly
...
$("#ddl_Region").change(function () {
$.getJSON("/Process/RegionFilter/" + $("#ddl_Region > option:selected").attr("text"), updateProperties(data));
});
});
function updateProperties(data, status) {
$("#lb_C").html("");
for (var d in data) {
var addOption = new Option(data[d].Value, data[d].Name);
addOption.appendTo("#lb_C");
}
}
The callback function passed to your $.getJSON method is wrong. You need to pass a reference to the function, not to invoke it.
Try this:
$.getJSON("/Process/RegionFilter/" + $("#ddl_Region > option:selected").text(), updateProperties);
Also, in order to get the text of the selected drop-down option, you need to use the text() function:
$("#ddl_Region > option:selected").text()
See Documentation
I want to display a property name based on user input and display this inside of SyntaxHighlighter. Another post says this is supposed to be easy.
JS
$('#inputText').keyup(function () {
var outputValue = $('#codeTemplate').html();//Take the output of codeTemplate
$('#codeContent').html(outputValue);//Stick the contents of code template into codeContent
var finalOutputValue = $('#codeContent').html();//Take the content of codeContent and insert it into the sample label
$('.popover #sample').html(finalOutputValue);
SyntaxHighlighter.highlight();
});
SyntaxHighlighter.all();
Markup
<div style="display: none;">
<label class="propertyName"></label>
<label id="codeTemplate">
<label class="propertyName"></label>
//Not using Dynamic object and default Section (appSettings):
var actual = new Configuration().Get("Chained.Property.key");
//more code
</label>
<pre id="codeContent" class="brush: csharp;">
</pre>
</div>
<div id="popover-content" style="display: none">
<label id="sample">
</label>
</div>
This outputs plain text. As if SyntaxHighlighter never ran. I suspect that the issue has to do with the fact that <pre> doesn't exist after the page is rendered. However, updating
SyntaxHighlighter.config.tagName = "label";
along with pre to label did not work either.
There were many problems that had to be overcome to get this to function. I feel this is best explained with code:
JS
<script>
$(function () {
$('#Key').popover({
html: true,
trigger: 'focus',
position: 'top',
content: function () {
loadCodeData(true);
console.log('content updated');
var popover = $('#popover-content');
return popover.html();//inserts the data into .popover-content (a new div with matching class name for the id)
}
});
$('#Key').keyup(function () {
loadCodeData();
});
function loadCodeData(loadOriginal) {
var userData = $('#Key').val();
var codeTemplate = $('#codeTemplate').html();
var tokenizedValue = codeTemplate.toString().replace('$$propertyNameToken', userData);
$('#codeContent').html(tokenizedValue);
$('#codeContent').attr('class', 'brush: csharp');//!IMPORTANT: re-append the class so SyntaxHighlighter will process the div again
SyntaxHighlighter.highlight();
var syntaxHighlightedResult = $('#codeContent').html();//Take the content of codeContent and insert it into the div
var popover;
if(loadOriginal)
popover = $('#popover-content');//popover.content performs the update of the generated class for us so well we need to do is update the popover itself
else {
popover = $('.popover-content');//otherwise we have to update the dynamically generated popup ourselves.
}
popover.html(syntaxHighlightedResult);
}
SyntaxHighlighter.config.tagName = 'div';//override the default pre because pre gets converted to another tag on the client.
SyntaxHighlighter.all();
});
</script>
Markup
<div style="display: none;">
<label id="codeTemplate">
//Not using Dynamic object and default Section (appSettings):
var actual = new Configuration().Get("$$propertyNameToken");
//Using a type argument:
int actual = new Configuration().Get<int>("asdf");
//And then specifying a Section:
var actual = new Configuration("SectionName").Get("test");
//Using the Dynamic Object and default Section:
var actual = new Configuration().NumberOfRetries();
//Using a type argument:
int actual = new Configuration().NumberOfRetries<int>();
//And then specifying a Section:
var actual = new Configuration("SectionName").NumberOfRetries();
</label>
<div id="codeContent" class="brush: csharp;">
</div>
</div>
<div id="popover-content" style="display: none">
</div>