I have a question about to creating dynamic jquery slideToggle function. I have html template as below:
<h4 id="client" class="section-title">
<div class="sect-icon"></div>
<span>Client Info</span> </h4>
<div class="form-row" id="client_data">
<div class="form-group col-md-4">
<label for="id_client_name">Name</label>
<input class="form-control" disabled value="{{client.client_name}}">
</div>
</div>
And jQuery function as :
$(document).ready(function () {
$("#client").click(function () {
if ($('#client_data').is(':visible')) {
$("#client").removeClass("section-title");
$("#client").addClass("section-title closed");
} else {
$("#client").removeClass("section-title closed");
$("#client").addClass("section-title");
}
$("#client_data").slideToggle("fast");
});
It is work . But this jQuery function is only for concreate html class. If i append another class to html ,then i should be copy this jQuery and past and edit id part. But i want to write one jQuery function for dynamic html id.
I mean how i can use above jQuery function for below html without creating new jQuery
<h4 id="equip" class="section-title">
<div class="sect-icon"></div> <span>Calibrated Equipment</span></h4>
<div class="form-row" id="equip_data">
<div class="form-group col-md-4">
<label for="id_brand_name">Brand</label>
<input class="form-control" disabled value="{{equip.brand_name}}">
</div>
</div>
When I was a university student, a teacher told us that repeated code is called "function":
function myStuff(idText) {
$("#" + idText).click(function () {
if ($('#' + idText + "_data").is(':visible')) {
$("#" + idText).removeClass("section-title").addClass("section-title closed");
} else {
$("#" + idText).removeClass("section-title closed").addClass("section-title");
}
$("#" + idText).slideToggle("fast");
}
And you pass the id to myStuff whenever you want, like:
$(document).ready(function () {
myStuff("client");
});
Related
I have a list with categories and questions (which can both be added dynamically), at the moment I am able to sort the categories using jQuery sortable, but not the questions underneath the categories.
I've tried just adding another .sortable function on the question wrap element but it is not responding at all.
My code at the moment:
// HTML template for new fields
const template = `
<div class="row sortwrap">
<div class="col-md-8">
<input type="text" name="category[]" placeholder="" class="form-control name_list catinput" />
<i class="mdi mdi-sort dragndrop"></i>
<div class="questionlist questionwrap">
<div class="row">
<div class="col-md-8">
<button class="btn btn-success questionbutton">Extra vraag</button>
<input type="text" name="question[]" placeholder="1. Voeg een vraag toe" class="form-control name_list questioninput" />
</div>
<div class="col-md-4">
</div>
</div>
</div>
</div>
<div class="col-md-4">
<button id="addcategory" class="btn btn-danger btn_remove removebutton">X</button>
</div>
</div>`;
const vraagTemplate = `
<div class="row" id="question">
<div class="col-md-8">
<input type="text" name="question[]" class="form-control name_list questioninput" />
</div>
<div class="col-md-4">
<button class="btn btn-danger btn_remove">X</button>
</div>
</div>`;
// Count numbers and change accordingly when field is deleted
function updatePlaceholders() {
// Sortable code
// $('#dynamic_field').sortable( "refresh" );
let df = $('#dynamic_field');
df.find('input[name^=cat]').each(function(i) {
$(this).attr("placeholder", i + 1 + ". Voeg een categorie toe");
});
df.find('.sortwrap').each(function(i) {
$(this).attr("id", i + 1);
});
df.find('.questionlist').each(function() {
$(this).find('input[name^=qu]').each(function(i) {
$(this).attr("placeholder", i + 1 + ". Voeg een vraag toe");
});
});
}
// Append question template
$('#dynamic_field').on('click', '.questionbutton', function() {
let $ql = $(this).closest('.questionlist');
$ql.append($(vraagTemplate));
updatePlaceholders();
});
// Delete
$('#dynamic_field').on('click', '.btn_remove', function() {
$(this).closest('.row').remove();
updatePlaceholders();
});
$('#addcategory').on('click', function() {
let t = $(template)
$('#dynamic_field').append(t);
updatePlaceholders();
});
$(function() {
$('#addcategory').trigger('click');
$('#question').sortable();
$('#dynamic_field').sortable({
cancel: '.questionwrap',
placeholder: "ui-state-highlight"
});
});
This is my sortable code:
$(function() {
$('#addcategory').trigger('click');
$('#question').sortable();
$('#dynamic_field').sortable({
cancel: '.questionwrap',
placeholder: "ui-state-highlight"
});
#question is the wrap of my question list and #dynamic_field is the wrap of my category element (the questions are also inside this element).
How can I make my questions also sortable? And also only make then sortable inside their parent div (so I can't drag a question from one category to the other but only within its own category).
One of the first thing I have noticed about your code is that the ID is repeated for each creation of a dynamic element. This will cause a lot of issues when you have 6 #question elements. This can be addressed by adding the ID to the element when it's created and creating a unique ID. For example, if there are 0 #questions then you can count that and add 1.
<div id="question-1"></div>
<script>
var id = $("[id|='question']").length + 1;
</script>
In this, id would be 2. there is one element that contains "question" and the |= selector will look for that before the - in a ID name. Can also use ^= selector.
Making use of handle will help a lot too. This will help allow proper sorting of nested items versus their parents. Also containment is helpful here too unless you want to move them between lists.
Consider the following code. It's a little clunky and I hope you can see what I am referring to.
$(function() {
function makeSortable(obj, options) {
console.log("Make Sortable", obj);
obj.sortable(options);
obj.disableSelection();
}
function updateSort(obj) {
console.log("Update Sortable", obj);
obj.sortable("refresh");
}
function addQuestion(q, c) {
console.log("Add Question", q, c);
var makeSort = $("[id|='question']", c).length === 0;
var question = $("<div>", {
class: "question",
id: "question-" + ($("div[id|='question']", c).length + 1)
});
question.append($("<div>", {
class: "col-md-8"
}).html(q));
question.append($("<div>", {
class: "col-md-4"
}).html("<button class='btn btn-danger btn-remove'>X</button>"));
question.appendTo($(".catcontent", c));
console.log(makeSort, question, c);
if (makeSort) {
makeSortable($(".catcontent", c), {
containment: "parent",
items: "> div.question"
});
} else {
updateSort($("[id|='question']", c).eq(0).parent());
}
}
function makeCategory(name) {
console.log("Make Category", name);
var makeSort = $("[id|='category']").length === 0;
var cat = $("<div>", {
class: "category ui-widget",
id: "category-" + ($("[id|='category']").length + 1)
});
cat.append($("<div>", {
class: "cathead ui-widget-header"
}).html(name + "<i class='btn btn-add-question'>+</i>"));
cat.append($("<div>", {
class: "catcontent ui-widget-content col-md-8"
}));
cat.appendTo($("#cat-wrapper"));
if (makeSort) {
makeSortable($("#cat-wrapper"), {
handle: ".cathead",
items: "> div.category"
});
} else {
updateSort($("#cat-wrapper"));
}
}
$('#addcategory').on('click', function() {
let t = $(template);
$('#dynamic_field').append(t);
updatePlaceholders();
});
$(".categorybutton").click(function(e) {
e.preventDefault();
makeCategory($(".catinput").val());
$(".catinput").val("");
});
$(".catwrap").on("click", ".btn-add-question", function(e) {
e.preventDefault();
var resp = prompt("Question to Add:");
addQuestion(resp, $(this).parent().parent());
});
});
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="http://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="row sortwrap">
<div class="col-md-8">
New Category
<input type="text" class="form-control catinput" placeholder="Category Name" />
</div>
<div class="col-md-4">
<button class="btn btn-success categorybutton">Add</button>
</div>
</div>
<div id="cat-wrapper" class="row catwrap">
</div>
Hope that helps.
How can I get value from my html action link, I tried to set the value in js function and it is work, and the problem is js not get the value form html file, and this forloop only the first one will call the Javascript function.
this is my js function
function selectTemplate() {
$('#choose').on('click', function () {
var objTemplate = $(".styTemplate").val();
$.post(strRoot + "/Home/Index/", { styTemplate: objTemplate });
});
};
and this is my vbhtml code
#For Each item In Model
Dim currentItem = item
'<!-- single-awesome-project start -->
#<div Class="col-md-4 col-sm-4 col-xs-12 #Html.DisplayFor(Function(modelItem) currentItem.strTemplateType)">
<div Class="single-awesome-project">
<div Class="awesome-img">
<img src="#Url.Content("~/Content/TemplateCSS/img/portfolio/" & currentItem.strTemplateType & ".jpg")" alt="" />
<div Class="add-actions text-center">
<div Class="project-dec">
<a Class="venobox" data-gall="myGallery" href="#Url.Content("~/Content/TemplateCSS/img/portfolio/" & currentItem.strTemplateType & ".jpg")">
<h4>#currentItem.strTemplateName</h4>
<span> Web Development</span>
#Html.ActionLink("Choose", "companyInfomation", "Home", New With {.id = "choose"}, New With {.styTemplate = currentItem.strTemplateName})
</a>
</div>
</div>
</div>
</div>
</div>
'<!-- single-awesome-project end -->
Next
</div>
<script>
selectTemplate();
</script>
Maybe it's better to use onclick attribute? Use this instead of Html.ActionLink:
Choose
I've got a <div> element that contains multiple other <div>'s that are populated dynamically using jQuery/Ajax, I'm trying to run the following code but find() fails to get any of them.
Here's my HTML boilerplate prior to my data being populated.
<input type="text" id="inv-filter" class="form-control">
<div class="row itemList" style="margin-right: -2px;margin-left:-2px;">
</div>
And here's what it looks like after population.
<input type="text" id="inv-filter" class="form-control">
<div class="row itemList" style="margin-right: -2px;margin-left:-2px;">
<div class="col-xs-3 col-sm-2 shop-item" data-hash="Item Name 1">
</div>
<div class="col-xs-3 col-sm-2 shop-item" data-hash="Item Name 2">
</div>
......
</div>
My Javascript looks like the following:
$('#inv-filter').keyup(function() {
var search = $(this).val().toLowerCase();
var $sellContainer = $('.itemList');
if (search.trim() === '') {
$sellContainer.find('.shop-item').show();
$sellContainer.find('.shop-item.selected').hide();
return;
}
$sellContainer.find('.sell-item').each(function() {
if (!$(this).hasClass('selected') && $(this).data('hash').text().toLowerCase().includes(search)) {
$(this).show();
} else {
$(this).hide();
}
});
});
I've ran multiple tests inside console debugger such as $('.itemList').length() etc.. but doesn't appear to find any results & when entering text into my input field, nothing is happening
$sellContainer.find('.sell-item').each(function() { //replace sell-item with shop-item
if (!$(this).hasClass('selected') && $(this).data('hash').text().toLowerCase().includes(search)) {
$(this).show();
} else {
$(this).hide();
}
});
I have following js code
var page = '<div class="row delete_contact">
<div class="col-xs-6 contact_item>
<label class="control-label col-xs-2" for="id">ID:</label>
<div class="controls col-xs-3">
<input class="form-control id" name="id" value="' + id +'">
</div>
<a href="javascript:void(0)" class="delete_contact_details control-label">
<span class="delete_contact_details control-label col-xs-1 glyphicon glyphicon-trash">
</span>
</a>
</div>
</div>';
when we click on 'delete' image, it has to delete the full row(div). I tried following while page loading
$(function() {
$('.delete_contact_details').on( "click", function() {
$(this).closest('.delete_contact').remove();
});
});
But it is not calling the below code. Anyone please help!
Currently what you are using is called a "direct" binding which will only attach to element that exist on the page at the time your code makes the event binding call.
Its seems you are dynamically generating elements, use Event Delegation using .on() delegated-events approach.
$(function() {
$(document).on( "click", '.delete_contact_details', function() {
$(this).closest('.delete_contact').remove();
});
});
In place of document you should use closest static container.
Try:
$(document).ready(function() {
$('.delete_contact_details').click(function() {
$(this).closest('.delete_contact').remove();
});
});
I want to reset the form after calling an ajax function.
This is the code i gave in the jquery:
$("#frm_silder").reset();
Here frm_silder is the id of form. But when I'm using this code i got an eorror message like this.
$("#frm_silder").reset is not a function
In my html i give the id to form like this:
<form name="frm_silder" id="frm_silder" method="post">
So what is the problem in my code?
In jQuery
$('#frm_silder')[0].reset();
in Javascript
document.getElementById('frm_silder').reset()
You need to reset each element individually. Jquery does not have a function reset() that works on a form. reset() is a Javascript function that works on form elements only. You can however define a new jquery function reset() that iterates through all form elements and calls the javascript reset() on each of them.
$(document).ready(function(){
$('a').click(function(){
$('#reset').reset();
});
});
// we define a function reset
jQuery.fn.reset = function () {
$(this).each (function() { this.reset(); });
}
Demo
Alternatively, if you don't want to define a function, you can iterate through the form elements
$(document).ready(function() {
$('a').click(function() {
$('#reset').each(function() {
this.reset();
});
});
});
Demo
Source
I followed the solution given by #sameera. But it still throw me error.
I changed the reset to the following
$("form#frm_silder")[0].reset();
Then it worked fine.
You can use the following.
#using (Html.BeginForm("MyAction", "MyController", new { area = "MyArea" }, FormMethod.Post, new { #class = "" }))
{
<div class="col-md-6">
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-12">
#Html.LabelFor(m => m.MyData, new { #class = "col-form-label" })
</div>
<div class="col-lg-9 col-md-9 col-sm-9 col-xs-12">
#Html.TextBoxFor(m => m.MyData, new { #class = "form-control" })
</div>
</div>
<div class="col-md-6">
<div class="">
<button class="btn btn-primary" type="submit">Send</button>
<button class="btn btn-danger" type="reset"> Clear</button>
</div>
</div>
}
Then clear the form:
$('.btn:reset').click(function (ev) {
ev.preventDefault();
$(this).closest('form').find("input").each(function(i, v) {
$(this).val("");
});
});