I have a jquery code that is almost complete. I want the new values of the existing parameter to be added on the <a href> using jquery but my code only adds the value at the end of the href.
Sample case:
My parameters in the href are food-option AND talent-option.:
<a href="food-option=0&talent-option=0">
Then I have new values to be added for food option.
values: 123,456
My href should be like this:
<a href="food-option=0,123,456&talent-option=0">
This is my code that adds the value:
$(this).closest(".option-container").find("a.food-form-select-food").each(function () {
var _href = $(this).attr("href");
$(this).attr("href", _href + ',' + addnid);
});
But the result is like this:
<a href="food-option=0&talent-option=0,123,456">
Which is wrong.
Here is a JSfiddle/Demo of my work
Can somebody please help me?
Thank you very much in advance!
You are almost there.
Try this:
$(this).closest(".option-container").
find("a.food-form-select-food").each(function () {
var _href = $(this).attr("href").split("&");
_href[0] += ',' + addnid;
$(this).attr("href", _href.join("&"));
});
i think your looking for something like this:
$(this).closest(".option-container").find("a.food-form-select-food").each(function () {
var _href = $(this).attr("href");
var n = str.indexOf(",");
var output = _href.substr(0, position) + addnid + _href.substr(position);
});
and if you want more answers look at this:
Inserting string at position x of another string
try this, JSFIDDLE
$(document).ready(function () {
$(".select-addon").click(function () {
var addtitle = $(this).closest('.optionlist').find('.option-title').html();
var addnid = $(this).closest('.optionlist').find('.option-nid').html();
var html = '<li class="option-list">' + addtitle + '<div class="addnid2">' + addnid + '</div><span class="remove-addons"> Remove</span></li>';
$(this).closest(".option-container").find('#your-addons').append(html);
$(this).closest(".option-container").find("a.food-form-select-food").each(function () {
var _href = $(this).attr("href");
var splited = _href.split('&');
$(this).attr("href", splited[0] + ',' + addnid+'&'+splited[1]);
});
});
$(document).on('click', '.remove-addons', function () {
var addnid2 = $(this).closest('.option-list').find('.addnid2').html();
$(this).closest(".option-container").find("a.food-form-select-food").each(function () {
var href = $(this).attr('href');
$(this).attr('href', href.replace("," + addnid2, ""));
});
$(this).closest('li').remove()
});
});
.option-nid {
display: none;
}
.addnid2 {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="option-container" style="width:200px; float:left">
<div class="optionlist">
<div class="option-title">Food Set A</div>
<span class="select-addon">SELECT </span>
<div class="option-nid">132</div>
</div>
<div class="optionlist">
<div class="option-title">Food Set B</div>
<span class="select-addon">SELECT </span>
<div class="option-nid">133</div>
</div>
<div class="optionlist">
<div class="option-title">Food Set C</div>
<span class="select-addon">SELECT </span>
<div class="option-nid">134</div>
</div>
<br/>
<br/>
<br/>
<ol id="your-addons"></ol>
LINK
</div>
<div class="option-container col-md-6">
<div class="optionlist">
<div class="option-title">Food Set A</div>
<span class="select-addon">SELECT </span>
<div class="option-nid">132</div>
</div>
<div class="optionlist">
<div class="option-title">Food Set B</div>
<span class="select-addon">SELECT </span>
<div class="option-nid">133</div>
</div>
<div class="optionlist">
<div class="option-title">Food Set C</div>
<span class="select-addon">SELECT </span>
<div class="option-nid">134</div>
</div>
<br/>
<br/>
<br/>
<ol id="your-addons"></ol>
LINK
</div>
Related
I am very new to jQuery. The first part of the code is to check the inputs and after checked it should display the checked items the below format. How can do this with the help of jquery.
<ul class="approval approval_scrolltab mt-3">
<li>
<div class="approval--member">
<img src="assets/images/user.jpg" class="user--image" />
<div class="w-100">
<h6 class="approval--name">Name</h6>
<p>Initiator</p>
</div>
<div class="form-group">
<div class="checkbox">
<input name="one" type="checkbox" id="one" />
<label for="one"></label>
</div>
</div>
</div>
</li>
</ul>
After checked it should displays in this format.
<div class="col-xl-6 col-lg-6 col-md-6 offset-xl-1">
<h6 class="heading--form mb-2 mt-3 mt-sm-0">
User
</h6>
<ul class="approval approval_scrolltab mt-3">
<li>
<div class="approval--member">
<img src="assets/images/user.jpg" class="user--image" />
<div class="w-100">
<h6 class="approval--name">Name</h6>
<p>Initiator</p>
</div>
<a href="">
<span class="ic-close"></span>
</a>
</div>
</li>
</ul>
</div>
I tried like this.It was working fine for the names but got no idea how can display this user image attached with name and also there is a cancel icon too near the name.I am only being able to display name with this code.
<script>
$('input[type="checkbox"]').on('change', function () {
var name = $(this).attr('data-name');
var image = $(this).attr('data-image');
if ($(this).prop('checked')) {
$('#checked-names').append('<p data-name="' + name + '">' + name + '</p>');
$('#checked-images').append("<img src='image'")
} else {
$('#checked-names p[data-name="' + name + '"]').remove();
$('#checked-images').remove()
}
});
</script>
UPDATE
With this close button I want to remove this from checked list(which works great) as well as I want to uncheck this from checked in input.
$('body').on('click', '.ic-close', function() {
$(this).closest('li').remove()
$(this).closest('li').prop('checked',false) #didn't worked
});
This script below might be helpful for you. I only added an ID to the user-list and removed the a tag from the close button in your HTML. The JavaScript appends the HTML you wish with the name and the image to the list. If you click the close span, the item will be removed.
UPDATE:
To uncheck the checkbox by closing its user-list item, you have to add an attribute like data-name="Initiator" to the checkbox. In the JavaScript if have added two lines into the click listener of the ic-close item, see below.
$('input[type="checkbox"]').on('change', function() {
var image_url = $(this).closest( '.approval--member' ).find( 'img' ).attr('src');
var name = $(this).closest( '.approval--member' ).find( '.approval--name ~ p' ).text();
if($(this).prop('checked')) {
$('ul#user-list').append(
'<li id="' + name + '">' +
'<div class="approval--member">' +
'<img src="' + image_url + '" class="user--image" />' +
'<div class="w-100">' +
'<h6 class="approval--name">Name</h6>' +
'<p>' + name + '</p>' +
'</div>' +
'<span class="ic-close">Close</span>' +
'</div>' +
'</li>');
} else {
$('ul#user-list #' + name).remove();
}
$('body').on('click', '.ic-close', function() {
var name = $(this).closest('li').find('.approval--name ~ p' ).text();
$('input[data-name="' + name + '"]').prop( "checked", false );
$(this).closest('li').remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="approval approval_scrolltab mt-3">
<li>
<div class="approval--member">
<img src="assets/images/user.jpg" class="user--image" />
<div class="w-100">
<h6 class="approval--name">Name</h6>
<p>Initiator</p>
</div>
<div class="form-group">
<div class="checkbox">
<input data-name="Initiator" name="one" type="checkbox" id="one" />
<label for="one"></label>
</div>
</div>
</div>
</li>
</ul>
<div class="col-xl-6 col-lg-6 col-md-6 offset-xl-1">
<h6 class="heading--form mb-2 mt-3 mt-sm-0">
User
</h6>
<ul id="user-list" class="approval approval_scrolltab mt-3">
</ul>
</div>
Simply check if you really need jQuery, in 2020 the pure Javascript have the majority of the jQuery fonctions : http://youmightnotneedjquery.com/
You can get the checked attribute via an event like this :
var checkbox = document.querySelector('[type="checkbox"]');
// Event Listener:
checkbox.addEventListener('change', function(event) {
alert(event.target.checked);
if(event.target.checked) {
// Do want do you want when checked
}
});
I don't understand very well what you expected but I hope that it could help you.
Using jQuery and JavaScript I am trying to write some code that setups up one or more widgets. The widget accepts text in an input and adds it to a ul when a button is clicked.
Then items are added to the ul, a click listener is a setup to remove a specific item when clicked.
The code looks like this:
function WidgetThing(className) {
var items = [];
function removeItem(e) {
var idx = parseInt($(e.target).attr('data-index'));
items.splice(idx, 1);
updateItems();
}
function updateItems() {
var ul = $('.' + className + ' .items ul');
ul.html('');
items.forEach(function(item, idx) {
ul.append('<li data-index="' + idx + '">' + item + '</li>');
});
ul.on('click', 'li', removeItem);
}
$('.' + className + ' .add-button').click(function(e) {
var input = $('.' + className + ' input');
items.push(input.val());
input.val('');
updateItems();
});
}
$(document).ready(function() {
WidgetThing('widget1');
WidgetThing('widget2');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Widget1
<div class="widget1">
<div class="controls">
<input type="text" />
<button class='add-button'>Add Item</button>
</div>
<div class="items">
<ul></ul>
</div>
</div>
Widget2
<div class="widget2">
<div class="controls">
<input type="text" />
<button class='add-button'>Add Item</button>
</div>
<div class="items">
<ul></ul>
</div>
</div>
This works fine for adding items.
However, if I click the item to remove it, it also removes all items below the one selected.
How can I get this code to work? Am I taking the wrong approach?
Update Note: In the real app my updateItems() function has some side effects, so I need to take this approach to removing items from the array.
Working fiddle.
That could be achieved with less code than this, you could attach two events one to the buttons and another to the li elements for the remove :
$(document).ready(function() {
$('.add-button').click(function() {
var items = $(this).closest('.controls').next('.items');
$('ul', items).append('<li>' + $(this).prev('input').val() + '</li>');
});
$('ul').on('click', 'li', function() {
$(this).remove();
});
});
Here is a working snippet :
$(document).ready(function() {
$('.add-button').click(function() {
var items = $(this).closest('.controls').next('.items');
$('ul', items).append('<li>' + $(this).prev('input').val() + '</li>');
});
$('ul').on('click', 'li', function() {
$(this).remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Widget1
<div class="widget1">
<div class="controls">
<input type="text" />
<button class='add-button'>Add Item</button>
</div>
<div class="items">
<ul></ul>
</div>
</div>
Widget2
<div class="widget2">
<div class="controls">
<input type="text" />
<button class='add-button'>Add Item</button>
</div>
<div class="items">
<ul></ul>
</div>
</div>
I am trying to filter users by its data attribute , I have main div called user-append which contains users that I get from ajax get request , there can be 3 users or 100 users, its dynamical , this is my div with one user for the moment
<div id="user-append">
<div class="fc-event draggable-user" data-profesion="'+user.profesion+'" id="user_'+user.id+'" style="z-index: 9999;">
<div class="container-fluid">
<input type="hidden" value="'+user.id+'" id="user_'+ user.id + '_value" class="userId">
<div class="row" style="justify-content: center;">
<div class="col-xs-3 avatar-col">
<div class="innerAvatarUserLeft">
<img src="'+getUserImage(user.avatar)+'" width="100%" style="margin: 0 auto;">
</div>
</div>
<div class="col-xs-9 data-col">
<p class="fullName dataText">'+user.fullName+'</p>
<p class="usr_Gender dataText">Male</p>
<div style="position: relative">
<li class="availableUnavailable"></li>
<li class="usr_profesion dataText">AVAILABLE</li>
</div>
<p class="user_id" style="float:right;margin: 3px">'+user.employee_id+'</p>
</div>
</div>
</div>
</div>
</div>
as you can see I have data-profesion attribute from which I am trying to filter users depend on the profession that they have , I get the ajax request like this
$.ajax({
url: "/rest/users",
success: function (users) {
var options = [];
$user = $("#append_users");
$.each(users, function (i, user) {
options.push({
'profession': user.prof.Profession,
'gender': user.prof.Gender
});
userArr.push({
'id': user.id,
'firstName': user.prof.FirstName,
'lastName': user.prof.LastName,
'fullName': user.prof.FirstName + ' ' + user.profile.LastName,
'email': user.email,
'avatar': user.prof.Photo,
'profesion': user.prof.Profession
});
$('#filterByProfession').html('');
$('#filterByGender').html(''); // FIRST CLEAR IT
$.each(options, function (k, v) {
if (v.profession !== null) {
$('#filterByProfession').append('<option>' + v.profession + '</option>');
}
if (v.gender !== null) {
$('#filterByGender').append('<option>' + v.gender + '</option>');
}
});
});
});
and now I am trying to filter the users by its data-profesion, on change of my select option which I populate from the ajax get request , It should show only the users that contain that data-profesion value , something like this
$('#filterByProfession').change(function () {
var filterVal = $(this).val();
var userProfVal = $(".fc-event").attr("data-profesion");
if (filterVal !== userProfVal) {
}
});
You can use a CSS selector to find those users, and then hide them:
$('#filterByProfession').change(function () {
// first hide ALL users
$('.draggable-user').hide()
// then filter out the ones with the correct profession:
// (you need to escape the used quote)
.filter('[data-profesion="' + $(this).val().replace(/"/g, '\\"') + '"]')
// ... and show those
.show();
});
You're trying to get the userProfVal throughout a className selector which can return more than one element.
var userProfVal = $(".fc-event").attr("data-profesion");
^
Use the jQuery function .data() to get data attributes.
Look at this code snippet using the .each to loop over all elements returned by this selector .fc-event:
$('#filterByProfession').change(function() {
var filterVal = $(this).val();
$(".fc-event").hide().each(function() {
if ($(this).data("profesion") === filterVal) {
$(this).show();
}
});
});
Example with static data
$('#filterByProfession').change(function() {
var filterVal = $(this).val();
$(".fc-event").hide().each(function() {
if ($(this).data("profesion") === filterVal) {
$(this).show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='filterByProfession'>
<option>-----</option>
<option>Developer</option>
<option>Cloud computing</option>
</select>
<div id="user-append">
<div class="fc-event draggable-user" data-profesion="Developer" id="user_1" style="z-index: 9999;">
<div class="container-fluid">
<input type="hidden" value="1" id="user_1_value" class="userId">
<div class="row" style="justify-content: center;">
<div class="col-xs-3 avatar-col">
<div class="innerAvatarUserLeft">
<img src="'+getUserImage(user.avatar)+'" style="margin: 0 auto;">
</div>
</div>
<div class="col-xs-9 data-col">
Developer
<p class="fullName dataText">Ele</p>
<p class="usr_Gender dataText">Male</p>
<div style="position: relative">
<li class="availableUnavailable"></li>
<li class="usr_profesion dataText">AVAILABLE</li>
</div>
<p class="user_id" style="float:right;margin: 3px">11</p>
</div>
</div>
</div>
</div>
</div>
<div id="user-append">
<div class="fc-event draggable-user" data-profesion="Cloud computing" id="user_2" style="z-index: 9999;">
<div class="container-fluid">
<input type="hidden" value="2" id="user_2_value" class="userId">
<div class="row" style="justify-content: center;">
<div class="col-xs-3 avatar-col">
<div class="innerAvatarUserLeft">
<img src="'+getUserImage(user.avatar)+'" style="margin: 0 auto;">
</div>
</div>
<div class="col-xs-9 data-col">
Cloud computing
<p class="fullName dataText">Enri</p>
<p class="usr_Gender dataText">Male</p>
<div style="position: relative">
<li class="availableUnavailable"></li>
<li class="usr_profesion dataText">AVAILABLE</li>
</div>
<p class="user_id" style="float:right;margin: 3px">11</p>
</div>
</div>
</div>
</div>
</div>
See? the sections are being hidden according to the selected option.
Try using this
$(".fc-event[data-profesion='" + filterVal + "']").show();
$(".fc-event[data-profesion!='" + filterVal + "']").hide();
I want to change each div id with change function.
before:
<div id="a_1">a1</div>
<div id="b_1">b1</div>
<div id="c_1">c1</div>
<div id="d_1">d1</div>
<button onclick="change()">Değiştir</button>
after:
<div id="a_2">a2</div>
<div id="b_2">b2</div>
<div id="c_2">c2</div>
<div id="d_2">d2</div>
<button onclick="change()">Değiştir</button>
I've tried this function but it didnt work
function change()
{
var old_id=1;
var new_id=2;
alert( bas( $("#a_1").attr("id")) );
$("div[id$=_"+old_id+"]").attr("id", bas( $("div[id$=_"+old_id+"]").attr("id") ) +new_id);
}
How can I do?
Thanks.
After doing some small changes you can achieve these this easily.
Try this:
HTML Code:
<div id="a_1">a1</div>
<div id="b_1">b1</div>
<div id="c_1">c1</div>
<div id="d_1">d1</div>
<button onclick="change(1, 2)">Değiştir</button>
Javascript/Jquery Code:
function change(oldid, newid)
{
$('div[id $= "_' +oldid+ '"]').each(function(){
var clone =$(this).clone(true).attr('id' , 'id_' + newid);
$('body').append(clone);
});
var nextid = newid + 1;
$('body').append('<button onclick="change(' + newid + ',' + nextid +')">Değiştir</button>');
}
Working Example
I have added class attribute to the div elements. Here is the demo JSFIDDLE
HTML:
<div id="a_1" class="my_div">a1</div>
<div id="b_1" class="my_div">b1</div>
<div id="c_1" class="my_div">c1</div>
<div id="d_1" class="my_div">d1</div>
<button onclick="change_ids()">Değiştir</button>
JS:
change_ids=function()
{
var old_id=1;
var new_id=2;
$('div.my_div').each(function() {
var div_id = $(this).attr('id');
var arr = div_id.split("_");
//alert(arr[0]+" "+arr[1]);
var new_div_id = arr[0]+"_"+new_id;
$(this).attr('id', new_div_id);
$(this).html(new_div_id);
});
alert('Div ids changed')
}
I have the following html:
<div id="prog" class="downloads clearfix">
<div class="item">
<div class="image_container">
<img src="/img/downloads/company.png" width="168" height="238" alt="">
</div>
<div class="title">
pricelist: <label id="pr1"></label>
</div>
<div class="type">
pdf document
</div>
<div class="link">
<a id="pdfdocument" class="button" target="_blank" href="#">start Download </a>
</div>
</div>
</div>
I want build HTML which is inside the <div id="prog"> with Javascript:
<div id="prog" class="downloads clearfix"></div>
I'm trying to use this Javascript, but without success:
var tmpDocument, tmpAnchorTagPdf, tmpAnchorTagXls, parentContainer, i;
parentContainer = document.getElementById('prog');
for (i = 0; i < documents.length; i++) {
tmpDocument = documents[i];
tmpAnchorTagPdf = document.createElement('a id="pdfdocument" ');
tmpAnchorTagPdf.href = '/role?element=' + contentElement.id + '&handle=' + ope.handle;
tmpAnchorTagPdf.innerHTML = 'start Download';
tmpAnchorTagXls = document.createElement('a');
tmpAnchorTagXls.href = '/role?element=' + contentElement.id + '&handle=' + ope.handle;
tmpAnchorTagXls.innerHTML = 'start Download';
parentContainer.appendChild(tmpAnchorTagPdf);
parentContainer.appendChild(tmpAnchorTagXls);
}
If this is a section of code that you will be using more than once, you could take the following approach.
Here is the original div without the code you want to create:
<div id="prog" class="downloads clearfix">
</div>
Create a template in a hidden div like:
<div id="itemtemplate" style="display: none;">
<div class="item">
<div class="image_container">
<img src="/img/downloads/company.png" width="168" height="238" alt="">
</div>
<div class="title">
pricelist: <label></label>
</div>
<div class="type">
pdf document
</div>
<div class="link">
<a class="button" target="_blank" href="#">start Download </a>
</div>
</div>
</div>
Then duplicate it with jquery (OP originally had a jquery tag; see below for JS), update some HTML in the duplicated div, then add it to the document
function addItem() {
var item = $("#itemtemplate div.item").clone();
//then you can search inside the item
//let's set the id of the "a" back to what it was in your example
item.find("div.link a").attr("id", "pdfdocument");
//...the id of the label
item.find("div.title label").attr("id", "pr1");
//then add the objects to the #prog div
$("#prog").append(item);
}
update
Here is the same addItem() function for this example using pure Javascript:
function JSaddItem() {
//get the template
var template = document.getElementById("itemtemplate");
//get the starting item
var tempitem = template.firstChild;
while(tempitem != null && tempitem.nodeName != "DIV") {
tempitem = tempitem.nextSibling;
}
if (tempitem == null) return;
//clone the item
var item = tempitem.cloneNode(true);
//update the id of the link
var a = item.querySelector(".link > a");
a.id = "pdfdocument";
//update the id of the label
var l = item.querySelector(".title > label");
l.id = "pr1";
//get the prog div
var prog = document.getElementById("prog");
//append the new div
prog.appendChild(item);
}
I put together a JSFiddle with both approaches here.