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.
Related
I want the user to be able to edit dynamically created list items that are input into a ul by the user.
I have no problem changing other items but the fact that the li items don't exist until input by the user is stumping me. I don't have any id's or classes to select to add a dblclick event to and selecting the child elements of all ul doesn't seem to work.
In short I just want to either:
click an icon on each list item that will allow me to edit the text
or
just double click the text which will allow me to edit it. (dblclick because the items are already draggable.)
I've tried a number of things but I'm not sure where to start now.
Thanks!
<div id="listWrapper" class="row">
<div id="dayInfo" class="container col-8">
<div class="card">
<img id="mondayImg" class="card-img-top">
<div class="card-body">
<h3 id="title" class="card-title">My Coding To-Do List</h3>
<div id="subTitle" class="row">
<div class="col">
<h5>Still to do</h5>
<button id="allFinished" class="btn btn-success">Move all to finished</button>
<hr>
<ul class="toBeSaved edit" id="stillToDo">
</ul>
<!-- <i class="fas fa-edit"></i> -->
</div>
<div class="col">
<h5>In Progress</h5>
<button id="allFinished2" class="btn btn-success">Move all to finished</button>
<hr>
<ul class="toBeSaved edit" id="inProgress">
</ul>
</div>
<div class="col">
<h5>Finished</h5>
<button id="removeFinished" class="btn btn-danger">Remove finished</button>
<hr>
<ul class="toBeSaved edit" id="finished">
</ul>
</div>
</div>
<div id="newItemWrapper">
<input id="newItem" placeholder="Add a new item">
<br>
<h6 id="newItemBtn" class="btn btn-primary">Add new item</h6>
<br>
<h6 id="save" class="btn btn-success">Save</h6>
<h6 id="clear" class="btn btn-warning">Clear</h6>
<p class="card-text"><small id="lastUpdated" class="text-muted toBeSaved">Last updated </small></p>
</div>
</div>
</div>
</div>
</div>
$(function() {
$("#newItem").focus();
//Adding a new items when click or enter pressed//
function addNewItem() {
let newInput = $("#newItem").val();
$("#stillToDo").append("<li>" + newInput + "</li>");
$("#newItem").val("");
$("#lastUpdated").text("Last updated " + Date());
};
$("#newItemBtn").click(addNewItem);
$("#newItem").keypress(function(e) {
if (event.which == 13) {
addNewItem();
}
});
//Moving list itmes and removing list items//
$("#allFinished").click(function() {
$("#finished").append($("#stillToDo li"))
});
$("#allFinished2").click(function() {
$("#finished").append($("#inProgress li"))
});
$("#removeFinished").click(function() {
$("#finished li").remove();
});
//So you can drag items across to another list
$("#stillToDo").sortable({
connectWith: "#finished, #inProgress"
});
$("#inProgress").sortable({
connectWith: "#finished, #stillToDo"
})
$("#finished").sortable({
connectWith: "#stillToDo, #inProgress"
});
//THIS IS SAVING LIST INFO and LAST UPDATED IN THE HTML 5 LOCAL STORAGE//
$(document).ready(function() {
$("#save").click(function(e) { //Clicking the "save button"//
e.preventDefault();
var everything = [];
$(".toBeSaved").each(function() {
everything.push(this.innerHTML);
})
localStorage.setItem('list', JSON.stringify(everything));
});
//RETREIVEING LISTS AND "UPDATED ON" FROM LOCAL STORAGE//
function loadEverything() {
if (localStorage.getItem('list')) {
var everything = JSON.parse(localStorage.getItem('list'));
$(".toBeSaved").each(function(i) {
this.innerHTML = everything[i];
})
}
}
loadEverything(); //<--This is calling the above function, without this nothing happens//
$("#clear").click(function(e) {
e.preventDefault();
localStorage.clear();
location.reload();
});
});
});
One simple way to edit text is to replace the text with an input element with it's value set to the text as follows:
//Edit added li elements
$(document).on('dblclick', 'ul.toBeSaved.edit li', function() {
let inEdit = $('<input/>');
let toEdit = $(this);
toEdit.html( inEdit.val( toEdit.text() ) );
inEdit.focus().select();
});
$(document).on('focusout keypress', 'ul.toBeSaved.edit li input', function(e) {
if( e.which === 13 || e.type === 'focusout') {
let val = $(this).val();
$(this).closest('li').text( val );
}
});
DEMO
$(function() {
$("#newItem").focus();
//Adding a new items when click or enter pressed//
function addNewItem() {
let newInput = $("#newItem").val();
$("#stillToDo").append("<li>" + newInput + "</li>");
$("#newItem").val("");
$("#lastUpdated").text("Last updated " + Date());
};
$("#newItemBtn").click(addNewItem);
$("#newItem").keypress(function(e) {
if (event.which == 13) {
addNewItem();
}
});
//End of adding a new items when click or enter pressed//
//Moving list itmes and removing list items//
$("#allFinished").click(function() {
$("#finished").append($("#stillToDo li"))
});
$("#allFinished2").click(function() {
$("#finished").append($("#inProgress li"))
});
$("#removeFinished").click(function() {
$("#finished li").remove();
});
//End of Moving list itmes and removing list items//
//So you can drag items across to another list
$("#stillToDo").sortable({
connectWith: "#finished, #inProgress"
});
$("#inProgress").sortable({
connectWith: "#finished, #stillToDo"
})
$("#finished").sortable({
connectWith: "#stillToDo, #inProgress"
});
//THIS IS SAVING LIST INFO and LAST UPDATED IN THE HTML 5 LOCAL STORAGE//
$(document).ready(function() {
$("#save").click(function(e) { //Clicking the "save button"//
e.preventDefault();
var everything = [];
$(".toBeSaved").each(function() {
everything.push(this.innerHTML);
})
localStorage.setItem('list', JSON.stringify(everything));
});
//\\END OF THIS IS SAVING LIST INFO and "UPDATED ON" IN THE BROWSER'S LOCAL STORAGE//
//RETREIVEING LISTS AND "UPDATED ON" FROM LOCAL STORAGE//
function loadEverything() {
if (localStorage.getItem('list')) {
var everything = JSON.parse(localStorage.getItem('list'));
$(".toBeSaved").each(function(i) {
this.innerHTML = everything[i];
})
}
}
loadEverything(); //<--This is calling the above function, without this nothing happens//
//END OF RETREIVEING LISTS AND "UPDATED ON" FROM LOCAL STORAGE//
$("#clear").click(function(e) {
e.preventDefault();
localStorage.clear();
location.reload();
});
});
//Edit added li elements
$(document).on('dblclick', 'ul.toBeSaved.edit li', function() {
let inEdit = $('<input/>');
let toEdit = $(this);
toEdit.html( inEdit.val( toEdit.text() ) );
inEdit.focus().select();
});
$(document).on('focusout keypress', 'ul.toBeSaved.edit li input', function(e) {
if( e.which === 13 || e.type === 'focusout') {
let val = $(this).val();
$(this).closest('li').text( val );
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-sortable/0.9.13/jquery-sortable-min.js" integrity="sha512-9pm50HHbDIEyz2RV/g2tn1ZbBdiTlgV7FwcQhIhvykX6qbQitydd6rF19iLmOqmJVUYq90VL2HiIUHjUMQA5fw==" crossorigin="anonymous"></script>
<div id="listWrapper" class="row">
<div id="dayInfo" class="container col-8">
<div class="card">
<img id="mondayImg" class="card-img-top">
<div class="card-body">
<h3 id="title" class="card-title">My Coding To-Do List</h3>
<div id="subTitle" class="row">
<div class="col">
<h5>Still to do</h5>
<button id="allFinished" class="btn btn-success">Move all to finished</button>
<hr>
<ul class="toBeSaved edit" id="stillToDo">
</ul>
<!-- <i class="fas fa-edit"></i> -->
</div>
<div class="col">
<h5>In Progress</h5>
<button id="allFinished2" class="btn btn-success">Move all to finished</button>
<hr>
<ul class="toBeSaved edit" id="inProgress">
</ul>
</div>
<div class="col">
<h5>Finished</h5>
<button id="removeFinished" class="btn btn-danger">Remove finished</button>
<hr>
<ul class="toBeSaved edit" id="finished">
</ul>
</div>
</div>
<div id="newItemWrapper">
<input id="newItem" placeholder="Add a new item">
<br>
<h6 id="newItemBtn" class="btn btn-primary">Add new item</h6>
<br>
<h6 id="save" class="btn btn-success">Save</h6>
<h6 id="clear" class="btn btn-warning">Clear</h6>
<p class="card-text"><small id="lastUpdated" class="text-muted toBeSaved">Last updated </small></p>
</div>
</div>
</div>
</div>
</div>
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");
});
So, I am making a school based project, and it has to be done in javascript and jquery. However these languages are quite new to me, so it's a bit of difficulty for me. My question: how can I append my button so it can submit the form that I have filled out?
a fiddle for u to get an idea of it. I want my button to be placed next to the green one, please do not mind the red minus button. that's something in progress. jsfiddle.net/DanDy/hqy73b0h
underneath is the code that I want to implement:
function submitCSMBtn(target, i) {
var submitBtn = $('<button/>', {
'class': 'btn btn-info fa fa-download',
'type': 'submit',
});
return submitBtn;
}
all the code in case you need to review it as a whole:
$(document).ready(function(){
var id = 0;
var addOpdracht = $('<a/>', {
'class': 'btn btn-success',
'id': 'addOpdracht'
}).on('click', function(){
$('form').append(getExerciseBlock(id));
id++;
}).html('<i class="fa fa-plus"></i>');
$('form').append(addOpdracht);
})
function getAddBtn(target, i){
var addBtn = $('<a/>', {
'class': 'btn btn-primary'
}).on('click', function(){
$(target).append(getWordPartInput(i));
}).html('<i class="fa fa-plus"></i>');
console.log(target);
return addBtn;
}
function getExerciseBlock(i){
var eBlock = $('<div/>',{
'id': i,
'class': 'col-md-12, eBlock'
});
$(eBlock).append(getAudioBtn(i), getWordInput(i), getWordPartInput(i),
getAddBtn(eBlock, i));
return eBlock;
}
function getAudioBtn(id, cValue){
cValue = cValue || '';
var audioBtn = $('<a/>', {
'class': 'btn btn-primary'
}).html('<i class="fa fa-volume-up"></i>');
return audioBtn;
}
function getWordInput(id, cValue){
cValue = cValue || '';
var wInput = $('<input/>', {
'class': 'form-group form-control',
'type': 'text',
'name': 'question_takeAudio_exerciseWord[]',
'placeholder': 'Exercise',
'id': 'exerciseGetWordInput'
})
return wInput;
}
function getWordPartInput(id, cValue){
cValue = cValue || '';
var wpInput = $('<input/>', {
'class': 'form-group form-control',
'type': 'text',
'value': cValue,
'placeholder': 'Syllables',
'id': 'SyllablesGetWordPartInput'
});
return wpInput;
}
function submitCSMBtn(target, i) {
var submitBtn = $('<button/>', {
'class': 'btn btn-info fa fa-download',
'type': 'submit',
});
return submitBtn;
}
I am trying to add my submit button so it will submit the form (has to go to JSON, maybe that will have a different approach... just giving extra info). from what I know I should use something with the command .on('click', function()) if not mistaken, and it should go in my eBlock if not mistaken either, but whenever I try this it will result in me losing functionality (ea, adding inputs etc. but I keep the layout). I have been looking around however to get a clear explaination of the on('click') function because it's new to me. what I have found was http://api.jquery.com/on/
not sure if this is the same. So if you guys could help me along, that would be great!
EDIT: my HTML code aswell. Apparentely that's needed too, sorry.
NOTE: I just took the code from body to body instead of putting the useless code in it aswell.
<body>
<div class="container">
<div class="panel-group">
<div class="panel panel-default">
<div class="panel panel-primary">
<div class="panel-heading">
<div class="row">
<h2 id="exerciseTitleCMS" class="col-md-8 col-sm-7 col-xs-6">CMS</h2>
<div class="col-md-offset-2 col-md-2">
<h2>
<select class="languageSelector form-control required" id="languageSelector" ></select>
</h2>
</div>
</div>
</div> <!-- end of panel-heading -->
<div class="panel-body">
<div class="jumbotron" id="mainList">
<form class="container-fluid" action="#" method="POST" required>
</form>
</div>
</div> <!-- end of panel-body -->
</div> <!-- end panel-primary -->
</div> <!--end panel-group -->
</div> <!-- end of container-->
</body>
Try this:
$('<button></button>')
.addClass('btn-class')
.attr('type', 'submit')
.appendTo('form-selector');
But rather than dynamically adding the submit button, you could also put the button in the HTML form, and then programmatically showing it on some event:
With jQuery:
$(function() {
$('#submit_button').hide();
$('#show_submit_button').on('click', function() {
$('#submit_button').show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='my_form' class='my_form_class'>
<input type='submit' id='submit_button' />
</form>
<button id='show_submit_button'>Show submit button!</button>
Or with CSS (and jQuery):
$(function() {
$('#toggle_submit_button').on('click', function() {
$('#submit_button').toggleClass('hidden_submit_buttton shown_submit_button');
});
});
.hidden_submit_button {
display: none;
}
.shown_submit_button {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='my_form' class='my_form_class'>
<input type='submit' id='submit_button' class='hidden_submit_button' />
</form>
<button id='toggle_submit_button'>Show/Hide submit button!</button>
You are doing it wrong.
There are few ways to append object.
instead of:
function submitCSMBtn(target, i) {
var submitBtn = $('<button/>', {
'class': 'btn btn-info fa fa-download',
'type': 'submit',
});
return submitBtn;
}
Most easiest way is you can append just plain html string:
var submitBtn = '<button class=\'btn btn-info fa fa-download\' type=\'submit\'><button />';
//then you can append the html string to element you want to append:
$('#your_element_ID').append(submitBtn);
here is my codepen link
my html code
<div id="main">
<h1>Wikipedia Viewer</h1>
<form class="form-inline">
<div class="container">
<div class="row">
<div class="col-sm-6 col-sm-offset-4 col-lg-7 col-lg-offset-4">
<div class="form-group">
<label class="sr-only" for="search">search</label>
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="button" class="btn btn-primary"><i class="fa fa-search"></i></button></form>
</div>
</div>
</div>
Surprise me!
</div>
<div id="search">
</search>
jquery code for making wikipedia api search call and then displaying title and overview.i want to associate links to respective article on dynamically created p element
$(document).ready(function() {
$("button").click(function() {
var article = $("input").val();
$.ajax({ //wikipedia api call
url: "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=" + article + "&format=json",
dataType: "jsonp",
success: function(data) {
for (var i = 0; i < data.query.search.length; i++) { //displaying titles and snippets accroding to search query. i want to associate link to each dynamically created p element.
var title = data.query.search[i].title;
var snippet = data.query.search[i].snippet;
$("#search").append("<p>" + title + "<br>" + snippet + "</p>");
}
$("#main").attr({
'style': 'display: none'
});
},
error: function() {
$("h1").html("oops");
}
});
});
});
Change your $("#search").append() as follows:
$("#search")
.append("<p><a href='https://en.wikipedia.org/wiki/" + title + "'>" + title + "</a>" +
"<br>" + snippet + "</p>"
);
Codepen
I have two div html elements with different id and here I am using spinner. Whenever values in the spinner input changes alert box will be displayed.
HTML code
<div id="accordion2" class="panel-group" style="display: block;">
<div id="accordion2" class="panel-group">
<div id="Tea">
<div class="spinner Tea input-group ">
<input type="text" id = "servings" class="form-control input- sm" value="Tea"/>
<div class="input-group-btn-vertical">
<button class="btn Tea btn-default">
<i class="fa fa-caret-up"></i>
</button>
<button class="btn Tea btn-default">
<i class="fa fa-caret-down"></i>
</button>
</div>
<h4 id="energy" class="Tea"> Tea </h4>
</div>
<div id="Coffee">
<div class="spinner Coffee input-group ">
<input type="text" id = "servings" class="form-control input-sm" value="Coffee"/>
<div class="input-group-btn-vertical">
<button class="btn Coffee btn-default">
<i class="fa fa-caret-up"></i>
</button>
<button class="btn Coffee btn-default">
<i class="fa fa-caret-down"></i>
</button>
</div>
<h4 id="energy" class="Coffee">Coffee</h4>
</div>
</div>
</div>
JQuery code
$(function(){
$('.spinner:first-of-type input').on('click', function() {
$('.spinner:first-of-type input').val(parseInt($('.spinner:first-of-type input').val(), 10) + 1);
var val = $('.spinner:first-of-type input').val();
changeValues(val);
});
$('.spinner:last-of-type input').on('click', function() {
$('.spinner input').val( parseInt($('.spinner input').val(), 10) - 1);
});
function changeValues(value){
alert($('#energy').attr('class').split(' '));
};
});
But in the alert box whenever I click the spinner up arrow only Tea is displayed.
what I expect is when the spinner is clicked from Tea div tea should be displayed and when from coffee , coffee should be displayed.Please help me out
I'm not sure I totally got what you are trying to do, but it seems to me that you want to increment and decrement number of beverage cups on up/down buttons click. For this you would better modify mark up a little (remove duplicated ids, add classes for convenience). And I may look like this then:
$(function() {
$('.spinner').on('click', '.servings', function(e) {
$(this).val(parseInt($(this).val() || 0, 10) + 1);
var val = $(this).val();
changeValues.call(e.delegateTarget, val);
})
.on('click', '.up', function(e) {
$(e.delegateTarget).find('.servings').val(function() {
return ++this.value;
});
})
.on('click', '.down', function(e) {
var $input = $(e.delegateTarget).find('.servings');
if (+$input.val() > 1) {
$input.val(function() {
return --this.value;
});
}
});
function changeValues(value) {
var type = $(this).find('.energy').data('type');
alert(type);
};
});
Demo: http://plnkr.co/edit/9vXC0RipxkzqhXrHJAKD?p=preview
try this:
$(function () {
$('.spinner').each(function () {
var $el = $(this),
$buttons = $el.find('button'),
$h4 = $el.find('h4'),
input = $el.find('input').get(0);
function showAlert() {
alert($h4.get(0).className);
}
$buttons.eq(0).on('click', function (event) {
event.preventDefault();
input.value = (parseInt(input.value, 10) || 0) + 1;
showAlert();
});
$buttons.eq(1).on('click', function (event) {
event.preventDefault();
input.value = (parseInt(input.value, 10) || 0) - 1;
});
});
});
JSFiddle http://jsfiddle.net/yLtn57aw/2/
Hope this helps