jquery add element to first child? - javascript

I have a simple section with two buttons these elements are created dynamically, I want to append input to a first button using jquery.
Here is my solution
HTML
<div id="interactive-layers">
<div class="go_back">Go back</div>
<div buttonid="3" class="video-btns show" targetmovieid="4" starttime="2.44" endtime="8.36">
<span class="label">Submit</span></div>
<div buttonid="81" class="video-btns show" targetmovieid="undefined" starttime="2.44" endtime="8.36">
<span class="label">undefined</span></div>
</div>
Js
var getButons = $('.video-btns').attr('buttonid');
var targetmovieid = $(videobtns).attr('targetmovieid');
if(getButons == 81 && targetmovieid =='undefined'){
var inputf = $("<input id='username' style='background: red' class='sync-element' starttime='3' endtime='6'></input>");
inputf.appendTo('.video-btns');
}else{
console.log('something is fucking wrong');
}
Now when I run my app I get the following result
<div id="interactive-layers">
<div class="go_back">Go back</div>
<div buttonid="81" class="video-btns show" targetmovieid="4" starttime="2.44" endtime="8.36">
<span class="label">Submit</span>
<input id="username" style="background: red" class="sync-element" starttime="3" endtime="6">
</div>
<div buttonid="3" class="video-btns show" targetmovieid="undefined" starttime="2.44" endtime="8.36">
<span class="label">undefined</span>
<input id="username" style="background: red" class="sync-element" starttime="3" endtime="6">
</div>
</div>
My code adds to both buttons I just want to add to the button with buttonid=81
what am I doing wrong?

$('.video-btns').each(function() {
var getButons = $(this).attr('buttonid');
var targetmovieid = $(this).attr('targetmovieid');
if (getButons == 81 && targetmovieid == 'undefined') {
var inputf = $("<input id='username' style='background: red' class='sync-element' starttime='3' endtime='6'></input>");
inputf.appendTo(this);
} else {
console.log('something is fucking wrong');
}
});

Not sure if this is what you are looking for, but if you change your JS code to this:
$('.video-btns').each(function(key, value) {
let buttonid = $(this).attr("buttonid");
let targetmovieid = $(this).attr("targetmovieid");
console.log(buttonid + ', ' + targetmovieid)
if(buttonid == 81 && targetmovieid =='undefined'){
var inputf = $("<input id='username' style='background: red' class='sync-element' starttime='3' endtime='6'></input>");
inputf.appendTo($(this));
}
});
It will append the input to the buttons that meet your criteria by looping through them and getting those that match, #Tyddlywink mentions.
You could probably do some filtering or pass in some parameters for the buttonid and the targetmovieid to make it more generalized to suit your needs.

https://jsfiddle.net/tyddlywink/6b2frvz8/
do this instead var getButons = $('.video-btns') then loop through the results $.each(getButons) checking the buttonid of each item.
<div id="interactive-layers">
<div class="go_back">Go back</div>
<div buttonid="3" class="video-btns show" targetmovieid="4" starttime="2.44" endtime="8.36">
<span class="label">Submit</span></div>
<div buttonid="81" class="video-btns show" targetmovieid="undefined" starttime="2.44" endtime="8.36">
<span class="label">undefined</span></div>
</div>
Javascript:
$(document).ready(function() {
var getButons = $('.video-btns');
$.each(getButons, function() {
var targetmovieid = $(this).attr('targetmovieid');
if ($(this).attr("buttonid") == 81 && targetmovieid == 'undefined') {
var inputf = $("<input id='username' style='background: red' class='sync-element' starttime='3' endtime='6'> </input>");
inputf.appendTo($(this));
} else {
console.log('something is Family Show wrong');
}
})
})

You are targeting the appendTo to all elements with class video-btns, not just the one with the two attributes as specified in the if condition. Furthermore, when you get attr() of a jQuery collection, you get the result for the first element in that collection, not of any in that collection.
You can make your life easier by selecting immediately the button you need, including the conditions on the two attributes in the selector, using the square bracket notation:
var $btn = $('.video-btns[buttonid=81][targetmovieid=undefined]');
if (!$btn.length) {
console.log('something is very wrong');
} else {
$btn.append($("<input>", { id: 'username', style: 'background: red', class: 'sync-element', starttime: 3, endtime: 6 }));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="interactive-layers">
<div class="go_back">Go back</div>
<div buttonid="3" class="video-btns show" targetmovieid="4" starttime="2.44" endtime="8.36">
<span class="label">Submit</span></div>
<div buttonid="81" class="video-btns show" targetmovieid="undefined" starttime="2.44" endtime="8.36">
<span class="label">undefined</span></div>
</div>

You are appending the input to .video-btns class, and hence the element is getting added to both the buttons. Try appending using the Id instead of the class.
Edited:
var $btn = $('.video-btns');
$.each($btn, (index, currentBtn) => {
if($(currentBtn).attr('buttonid') == '81' && $(currentBtn).attr('targetmovieid') == "undefined")
{
$(currentBtn).append($("<input>", { id: 'username', style: 'background: red', class: 'sync-element', starttime: 3, endtime: 6 }));
}
})

Related

Edit dynamically created li elements in jquery

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>

Fix HTML header and button tag not updating text

I am trying to write some code that updates a header tag and a button tag. However, when I use the method .text(); it does not work. So I looked up the proper way to do it via other stack overflow questions, and I see basically the same thing. Everyone is telling me to use .text() or .html(). So I am really confused on why it is not working. I am not sure if it has anything to do with values already in the tag.
HTML:
<div class="contents">
<div class="card text-center myCard">
<div class="card-header"></div>
<div class="card-body">
<h5 class="card-title"></h5>
<p class="card-text"></p>
<button type="button" class="btn btn-primary ttBtn"></button>
</div>
<div class="card-footer text-muted"></div>
</div>
</div>
jQuery:
$(".eBtn").on(
"click",
function(event) {
event.preventDefault();
var href = $(this).attr('href');
console.log(href);
$.get(href, function(ary2, status) {
$("#displayAppName").val(ary2.appname);
$("#appcode").val(ary2.appcode);
$("#editStatus").val(ary2.status);
if (ary2.mapstatus == "" || ary2.mapstatus == null) {
mapBool = true;
$("#mapStatus").val("");
$("#createBtn").val('Create');
$('#modalCreateBtn').attr(
'href',
'/create?currentAppcode='
+ ary2.appcode
+ "&currentAcro="
+ ary2.acronym
+ "&currentAppname="
+ ary2.appname);
console.log("Card Create: " + $(".card-title").val());
} else {
$("#mapStatus").val("Mapped");
$("#createBtn").val('Edit');
$('#modalCreateBtn').attr(
'href',
'/edit?currentAppcode='
+ ary2.appcode
+ "&currentAcro="
+ ary2.acronym);
mapBool = true;
console.log("Card Edit: " + $(".card-title").val());
}
});
console.log("Main Boolean : " + this.mapBool)
console.log("Main Boolean : " + mapBool)
if(mapBool){
$(".card-title").text("Application Mapped!");
$(".card-text").text("Continue to view application");
$(".ttBtn").text("New Mapping after");
}
$("#exampleModal").modal();
});
jQuery Change HTML:
$(".card-title").text("Application Mapped!");
$(".card-text").text("Continue to view application");
$(".ttBtn").text("Continue");
Created variable ary2. Hope this help you.
var ary2 = [];
if (ary2.mapstatus == "" || ary2.mapstatus == null) {
$("#mapStatus").val("");
$("#createBtn").val('Create');
$('#modalCreateBtn').attr(
'href',
'/create?currentAppcode=' +
ary2.code +
"&currentAcro=" +
ary2.acro +
"&currentAppname=" +
ary2.name);
$(".card-title").text("Application Mapped!");
$(".card-text").text("Continue to view application");
$(".ttBtn").html("Continue");
} else {
$("#mapStatus").val("Mapped");
$("#createBtn").val('Edit');
$('#modalCreateBtn').attr(
'href',
'/edit?currentAppcode=' +
ary2.code +
"&currentAcro=" +
ary2.acro);
}
$(document).ready(function() {
$(".card-title").text("Application Mapped!");
$(".card-text").text("Continue to view application");
$(".ttBtn").html("Continue");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="contents">
<div class="card text-center myCard">
<div class="card-header"></div>
<div class="card-body">
<h5 class="card-title">Application not mapped!</h5>
<p class="card-text">Click the "New Tier" button to begin mapping.
</p>
<button type="button" class="btn btn-primary ttBtn">New
Mapping</button>
</div>
<div class="card-footer text-muted"></div>
</div>
</div>

I can´t remove the last item of array

I can remove any item of array unless the last one. I also use angularjs to show information in the view. I don´t know what is happening with the last item of this array. Please, anyone can help me?
Here is HTML:
<div class="row">
<div class="col-md-12">
<h4><strong>Documento {{index + 1}} de {{documentos.length}}:</strong> {{documentos[index].nome}}</h4>
<iframe style="background: #ccc;" ng-show="exibirPreview" frameborder="0" ng-src="{{versaoLink}}" width="100%" height="300px"></iframe>
<div class="alert alert-warning" ng-hide="exibirPreview">
#Html.Raw(Resources.Dialog.SignDocuments.TypeDocumentCanNotPreDisplayed)
</div>
<hr />
<div class="pull-right btn-row" ng-show="documentos.length > 1">
<button class="btn btn-default" type="button" ng-click="RemoveDoc(index)"><i class="fa fa-fw fa-times"></i> #Resources.Common.RemoveDocList</button>
</div>
</div>
</div>
Here is js/angularjs
$scope.documentos = [
{nome:"document1", chave: "8F65579E3737706F", extensao:".pdf"},
{nome:"document2", chave: "8F65579E3730007F", extensao:".pdf"},
{nome:"document3", chave: "8545579E3737706F", extensao:".pdf"},
{nome:"document4", chave: "8555579E3730007F", extensao:".pdf"}
]
$scope.ViewLink = function () {
var versao = $scope.documentos[$scope.index];
$scope.exibirPreview = versao.extensao == ".pdf" || versao.extensao == ".txt";
if (!$scope.exibirPreview) {
$scope.versaoLink = '';
} else {
$scope.versaoLink = '/Documento/VersaoView?chave=' + versao.chave;
}
};
$scope.ViewLink();
$scope.RemoveDoc = function (index) {
$scope.documentos.splice(index, 1);
$scope.ViewLink();
};
Or Plunker
In your HTML you are preventing the deletion of the last element:
<div class="pull-right btn-row" ng-show="documentos.length > 1">
<!-- -->
</div>
documentos.length > 1 means "hide when it reaches one item in the array".
It should be documentos.length == 0.
It's either this or your index value starts from 1 and not from 0.
The simplest solution would be to change your remove function to take in the document instead of the index. Try this:
$scope.RemoveDoc = function(document) {
var index = $scope.documents.indexOf(document);
$scope.documents.splice(index, 1);
}
in view:
<button class="btn" type="button" ng-click="RemoveDoc(document)">Delete</button>

Load More Button JS - Load new content on page

I'm trying to develop a Load-More button using Javascript calling an API done with PHP.
So far, so good. I can load the new objects in a range i += i + 4 (I load three new comments everytime I press the button).
This is my load-more button:
$(document).ready(function () {
$(".load-more").on('click', function () {
var tab = $(this).data('tab');
var next_page = $(this).data('next-page');
console.log(next_page);
console.log(tab);
$.get($(this).data('url') + '?tab=' + tab + '&page=' + next_page, function (data) {
addNewQuestions($.parseJSON(data));
});
});
});
And for every object loaded I want to print each of these html blocks.
<div class="question-summary narrow">
<div class="col-md-12">
<div class="votes">
<div class="mini-counts"><span title="7 votes">
{if $question['votes_count']}
{$question['votes_count']}
{else}
0
{/if}
</span></div>
<div>votes</div>
</div>
<div {if $question['solved_date']}
class="status answered-accepted"
{else}
class="status answer-selected"
{/if}
title="one of the answers was accepted as the correct answer">
<div class="mini-counts"><span title="1 answer">{$question['answers_count']}</span></div>
<div>answer</div>
</div>
<div class="views">
<div class="mini-counts"><span title="140 views">{$question['views_counter']}</span></div>
<div>views</div>
</div>
<div class="summary">
<h3>
<a href="{questionUrl($question['publicationid'])}" class="question-title" style="font-size: 15px; line-height: 1.4; margin-bottom: .5em;">
{$question['title']}
</a>
</h3>
</div>
<div class = "statistics col-sm-12 text-right" style="padding-top: 8px">
<span>
<i class = "glyphicon glyphicon-time"></i>
<span class="question-updated-at">{$question['creation_date']}</span>
</span>
<span>
<i class = "glyphicon glyphicon-comment"></i>
<span class="question-answers">{$question['answers_count']}</span>
</span>
</div>
</div>
</div>
The problem is that I have several conditions, as {if$question['votes_count']} and I'm struggling because I don't know how get those variables when rendering the html.
Then I found something but I can't figure out how to adapt to my case
On that addNewQuestions I think that a good approach would be:
function addNewQuestions(objects) {
$.each(objects, function (i, object) {
console.log(object);
var lastItem = $('div.active[role="tabpanel"] .question-line:last');
var newLine = lastItem.clone(true);
var newObject = newLine.find('.question-col:eq(' + i + ')');
newObject.find('.question-info-container').attr('data-id', object.publicationid);
newObject.find('.vote-count').html(object.votes);
updateTitleAndLink(newObject.find('.question-title'), object);
lastItem.after(newLine);
});
}
function updateTitleAndLink(questionTitle, object) {
questionTitle.attr('href', questionTitle.data('base-question-url') + object.publicationid);
questionTitle.html(object.title);
}
But nothing happens and I can't figure out why.
Any idea or suggestion?
Kind regards

How to get the value of a particular input field using id in the html templates

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

Categories

Resources